---
title: 'Next.js'
description: 'Run bknd inside Next.js'
---
import InstallBknd from '/snippets/install-bknd.mdx';

## Installation
To get started with Next.js and bknd you can either install the package manually, and follow the descriptions below, or use the CLI starter:

<Tabs>
   <Tab title="CLI Starter">
      Create a new Next.js CLI starter project by running the following command:

      ```sh
      npx bknd create -i nextjs
      ```
   </Tab>
   <Tab title="Manual">
      Create a new Next.js project by following the [official guide](https://nextjs.org/docs/pages/api-reference/cli/create-next-app), and then install bknd as a dependency:

      <InstallBknd />
   </Tab>
</Tabs>

## Serve the API
``` tsx
// pages/api/[...route].ts
import { serve } from "bknd/adapter/nextjs";

export const config = {
   runtime: "edge", // or "experimental-edge", depending on your nextjs version
   unstable_allowDynamic: ["**/*.js"]
};

export default serve({
   connection: {
      url: process.env.DB_URL!,
      authToken: process.env.DB_AUTH_TOKEN!
   }
});
```
For more information about the connection object, refer to the [Database](/usage/database) guide.

## Enabling the Admin UI
Create a file `[[...admin]].tsx` inside the `pages/admin` folder:
```tsx
// pages/admin/[[...admin]].tsx
import type { InferGetServerSidePropsType as InferProps } from "next";
import { withApi } from "bknd/adapter/nextjs";
import dynamic from "next/dynamic";
import "bknd/dist/styles.css";

const Admin = dynamic(() => import("bknd/ui").then((mod) => mod.Admin), {
   ssr: false,
});

export const getServerSideProps = withApi(async (context) => {
   return {
      props: {
         user: context.api.getUser(),
      },
   };
});

export default function AdminPage({ user }: InferProps<typeof getServerSideProps>) {
   if (typeof document === "undefined") return null;
   return <Admin
      withProvider={{ user }}
      config={{ basepath: "/admin", logo_return_path: "/../" }}
   />;
}
```

## Example usage of the API in pages dir
Using pages dir, you need to wrap the `getServerSideProps` function with `withApi` to get access
to the API. With the API, you can query the database or retrieve the authentication status:
```tsx
import { withApi } from "bknd/adapter/nextjs";
import type { InferGetServerSidePropsType as InferProps } from "next";

export const getServerSideProps = withApi(async (context) => {
   const { data = [] } = await context.api.data.readMany("todos");
   const user = context.api.getUser();

   return { props: { data, user } };
});

export default function Home(props: InferProps<typeof getServerSideProps>) {
   const { data, user } = props;
   return (
      <div>
         <h1>Data</h1>
         <pre>{JSON.stringify(data, null, 2)}</pre>

         <h1>User</h1>
         <pre>{JSON.stringify(user, null, 2)}</pre>
      </div>
   );
}
```