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

## Installation
Install bknd as a dependency:
<InstallBknd />

## 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: {
      type: "libsql",
      config: {
         url: process.env.DB_URL!,
         authToken: process.env.DB_AUTH_TOKEN!
      }
   }
});
```
For more information about the connection object, refer to the [Setup](/setup/introduction) 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>
   );
}
```