Files
better-auth/docs/content/docs/integrations/next.mdx
2024-09-07 11:42:12 +03:00

176 lines
5.0 KiB
Plaintext

---
title: Next JS integration
description: Learn how to integrate Better Auth with Next.js
---
Better Auth can be easily integrated with Next.js. It'll also comes with utilities to make it easier to use Better Auth with Next.js.
## Installation
First, install Better Auth
```package-install
npm install better-auth
```
## Set Environment Variables
Create a `.env` file in the root of your project and add the following environment variables:
**Set Base URL**
```txt title=".env"
BETTER_AUTH_URL=http://localhost:3000 # Base URL of your app
```
**Set Secret**
Random value used by the library for encryption and generating hashes. You can generate one using the button below or you can use something like openssl.
```txt title=".env"
BETTER_AUTH_SECRET=
```
<GenerateSecret/>
## Configure Server
### Create Better Auth instance
We recommend to create `auth.ts` file inside your `lib/` directory. This file will contain your Better Auth instance.
```ts twoslash title="auth.ts"
import { betterAuth } from "better-auth"
export const auth = betterAuth({
database: {
provider: "sqlite", //change this to your database provider
url: "./db.sqlite", // path to your database or connection string
}
// Refer to the api documentation for more configuration options
})
```
<Callout type="warn">
Better Auth currently supports only SQLite, MySQL, and PostgreSQL. It uses Kysely under the hood, so you can also pass any Kysely dialect directly to the database object.
</Callout>
### Create API Route
We need to mount the handler to an API route. Create a route file inside `/api/[...auth]` directory. And add the following code:
```ts twoslash title="api/[...auth]/route.ts"
//@filename: @/lib/auth.ts
import { betterAuth } from "better-auth"
export const auth = betterAuth({
database: {
provider: "sqlite", //change this to your database provider
url: "./db.sqlite", // path to your database or connection string
}
// Refer to the api documentation for more configuration options
})
// ---cut---
//@filename: api/[...auth]/route.ts
//---cut---
import { auth } from "@/lib/auth";
import { toNextJsHandler } from "better-auth/next-js";
export const { GET, POST } = toNextJsHandler(auth.handler);
```
<Callout type="info">
You can change the path on your better-auth configuration but it's recommended to keep it as `/api/[...auth]`
</Callout>
### Migrate the database
Run the following command to create the necessary tables in your database:
```bash
npx better-auth migrate
```
## Create a client
Create a client instance. You can name the file anything you want. Here we are creating `client.ts` file inside the `lib/` directory.
```ts twoslash title="client.ts"
import { createAuthClient } from "better-auth/react" // make sure to import from better-auth/react
export const client = createAuthClient({
//you can pass client configuration here
})
```
Once you have created the client, you can use it to sign up, sign in, and perform other actions.
Some of the actinos are reactive. The client use [nano-store](https://github.com/nanostores/nanostores) to store the state and re-render the components when the state changes.
The client also uses [better-fetch](https://github.com/bekacru/better-fetch) to make the requests. You can pass the fetch configuration to the client.
## RSC and Server actions
The `api` object exported from the auth instance contains all the actions that you can perform on the server. Every endpoint made inside better auth is a invokable as a function. Including plugins endpoints.
**Example: Getting Session on a server action**
```tsx twoslash title="server.ts"
//@filename: @/lib/auth.ts
import { betterAuth } from "better-auth"
export const auth = betterAuth({
database: {
provider: "sqlite", //change this to your database provider
url: "./db.sqlite", // path to your database or connection string
}
// Refer to the api documentation for more configuration options
})
// ---cut---
//@filename: server.ts
//---cut---
import { auth } from "@/lib/auth"
import { headers } from "next/headers"
const someAuthenticatedAction = async () => {
"use server";
const session = await auth.api.getSession({
headers: headers()
})
};
```
**Example: Getting Session on a RSC**
```tsx
import { auth } from "@/lib/auth"
import { headers } from "next/headers"
export async function ServerComponent() {
const session = await auth.api.getSession({
headers: headers()
})
if(!session) {
return <div>Not authenticated</div>
}
return (
<div>
<h1>Welcome {session.user.name}</h1>
</div>
)
}
```
## Middleware
You can use the `authMiddleware` to protect your routes. It's a wrapper around the Next.js middleware.
```ts twoslash title="middleware.ts"
import { authMiddleware } from "better-auth/next-js"
export default authMiddleware({
redirectTo: "/sign-in" // redirect to this path if the user is not authenticated
})
export const config = {
matcher: ['/dashboard/:path*'],
}
```