# Nitro Integration (/docs/integrations/nitro)

Integrate Better Auth with Nitro.



Better Auth can be integrated with your [Nitro Application](https://nitro.build/) (an open source framework to build web servers).

This guide aims to help you integrate Better Auth with your Nitro application in a few simple steps.

## Create a new Nitro Application [#create-a-new-nitro-application]

Start by scaffolding a new Nitro application using the following command:

```bash title="Terminal"
npx create-nitro-app
```

This will create the `nitro-app` directory and install all the dependencies. You can now open the `nitro-app` directory in your code editor.

### Prisma Adapter Setup [#prisma-adapter-setup]

<Callout>
  This guide assumes that you have a basic understanding of Prisma. If you are new to Prisma, you can check out the [Prisma documentation](https://www.prisma.io/docs/getting-started).

  The `sqlite` database used in this guide will not work in a production environment. You should replace it with a production-ready database like `PostgreSQL`.
</Callout>

For this guide, we will be using the Prisma adapter. You can install prisma client by running the following command:

<CodeBlockTabs defaultValue="npm" groupId="persist-install">
  <CodeBlockTabsList>
    <CodeBlockTabsTrigger value="npm">
      npm
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="pnpm">
      pnpm
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="yarn">
      yarn
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="bun">
      bun
    </CodeBlockTabsTrigger>
  </CodeBlockTabsList>

  <CodeBlockTab value="npm">
    ```bash
    npm install @prisma/client
    ```
  </CodeBlockTab>

  <CodeBlockTab value="pnpm">
    ```bash
    pnpm add @prisma/client
    ```
  </CodeBlockTab>

  <CodeBlockTab value="yarn">
    ```bash
    yarn add @prisma/client
    ```
  </CodeBlockTab>

  <CodeBlockTab value="bun">
    ```bash
    bun add @prisma/client
    ```
  </CodeBlockTab>
</CodeBlockTabs>

`prisma` can be installed as a dev dependency using the following command:

<CodeBlockTabs defaultValue="npm" groupId="persist-install">
  <CodeBlockTabsList>
    <CodeBlockTabsTrigger value="npm">
      npm
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="pnpm">
      pnpm
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="yarn">
      yarn
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="bun">
      bun
    </CodeBlockTabsTrigger>
  </CodeBlockTabsList>

  <CodeBlockTab value="npm">
    ```bash
    npm install -D prisma
    ```
  </CodeBlockTab>

  <CodeBlockTab value="pnpm">
    ```bash
    pnpm add -D prisma
    ```
  </CodeBlockTab>

  <CodeBlockTab value="yarn">
    ```bash
    yarn add --dev prisma
    ```
  </CodeBlockTab>

  <CodeBlockTab value="bun">
    ```bash
    bun add --dev prisma
    ```
  </CodeBlockTab>
</CodeBlockTabs>

Generate a `schema.prisma` file in the `prisma` directory by running the following command:

```bash title="Terminal"
npx prisma init
```

You can now replace the contents of the `schema.prisma` file with the following:

```prisma title="prisma/schema.prisma"
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "sqlite"
  url      = env("DATABASE_URL")
}

// Will be deleted. Just need it to generate the prisma client
model Test {
  id   Int    @id @default(autoincrement())
  name String
}
```

Ensure that you update the `DATABASE_URL` in your `.env` file to point to the location of your database.

```txt title=".env"
DATABASE_URL="file:./dev.db"
```

Run the following command to generate the Prisma client & sync the database:

```bash title="Terminal"
npx prisma db push
```

### Install & Configure Better Auth [#install--configure-better-auth]

Follow steps 1 & 2 from the [installation guide](/docs/installation) to install Better Auth in your Nitro application & set up the environment variables.

Once that is done, create your Better Auth instance within the `server/utils/auth.ts` file.

```ts title="server/utils/auth.ts"
import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export default betterAuth({
  database: prismaAdapter(prisma, { provider: "sqlite" }),
  emailAndPassword: { enabled: true },
});
```

### Update Prisma Schema [#update-prisma-schema]

Use the Better Auth CLI to update your Prisma schema with the required models by running the following command:

```bash title="Terminal"
npx auth generate --config server/utils/auth.ts
```

<Callout>
  The `--config` flag is used to specify the path to the file where you have created your Better Auth instance.
</Callout>

Head over to the `prisma/schema.prisma` file & save the file to trigger the format on save.

After saving the file, you can run the `npx prisma db push` command to update the database schema.

## Mount The Handler [#mount-the-handler]

You can now mount the Better Auth handler in your Nitro application. You can do this by adding the following code to your `server/api/auth/[...all].ts` file:

```ts title="server/api/auth/[...all].ts"
import auth from "~/server/utils/auth";

export default auth;
```

<Callout>
  This is a [catch-all](https://nitro.build/guide/routing#catch-all-route) route that will handle all requests to `/api/auth/*`.
</Callout>

### CORS [#cors]

You can configure CORS for your Nitro app using a [route rule](https://nitro.build/docs/routing#cors) in your `nitro.config.ts`:

```ts title="nitro.config.ts"
import { defineConfig } from "nitro";

export default defineConfig({
  routeRules: {
    "/api/auth/**": {
      cors: {
        origin: ["http://localhost:3000"],
        credentials: true,
      },
    },
  },
});
```

<Callout>
  If you use cookie-based sessions, set `credentials: true` and list your frontend's exact origin(s) in `origin`. A wildcard origin (`cors: true`) cannot be combined with credentials. If you only use bearer tokens, `credentials` isn't required. Ensure that the config is in sync with your frontend application.
</Callout>

Learn more about CORS on the [Nitro documentation](https://nitro.build/docs/routing#cors).

### Auth Guard/Middleware [#auth-guardmiddleware]

You can add an auth guard to your Nitro application to protect routes that require authentication. You can do this by creating a new file `server/utils/require-auth.ts` and adding the following code:

```ts title="server/utils/require-auth.ts"
import { defineHandler, HTTPError } from "nitro";
import auth from "~/server/utils/auth.ts";

/**
 * Middleware used to require authentication for a route.
 *
 * Can be extended to check for specific roles or permissions.
 */
export default defineHandler(async (event) => {
  const session = await auth.api.getSession({
    headers: event.req.headers,
  });

  if (!session) {
    throw HTTPError.status(401, "Unauthorized");
  }

  // You can save the session to the event context for later use
  event.context.auth = session;
});

```

You can now use the [Object Syntax Event Handler](https://h3.dev/guide/basics/handler#object-syntax) to apply middleware to specific routes:

```ts title="server/api/secret.get.ts"
import { defineHandler } from "nitro";
import requireAuth from "~/server/utils/require-auth.ts";

export default defineHandler({
  middleware: [requireAuth],
  handler: () =>
    Response.json(
      { message: "Secret data" },
      { status: 201, statusText: "Secret data" },
    ),
});
```

### Example [#example]

See an [example Nitro application integrated with Better Auth & Prisma](https://github.com/BayBreezy/nitrojs-better-auth-prisma).

