The Auth0 Next.js SDK is a library for implementing user authentication in Next.js applications.
[Documentation](#documentation) - [Getting Started](#getting-started) - [API Reference](https://auth0.github.io/nextjs-auth0/) - [Feedback](#feedback)
## Documentation
- [QuickStart](https://auth0.com/docs/quickstart/webapp/nextjs) - our guide for adding Auth0 to your Next.js app.
- [Examples](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md) - lots of examples for your different use cases.
- [Security](https://github.com/auth0/nextjs-auth0/blob/main/SECURITY.md) - Some important security notices that you should check.
- [Docs Site](https://auth0.com/docs) - explore our docs site and learn more about Auth0.
## Getting Started
### 1. Install the SDK
```shell
npm i @auth0/nextjs-auth0
```
This library requires Node.js 20 LTS and newer LTS versions.
### 2. Add the environment variables
Add the following environment variables to your `.env.local` file:
```env
AUTH0_DOMAIN=
AUTH0_CLIENT_ID=
AUTH0_CLIENT_SECRET=
AUTH0_SECRET=
APP_BASE_URL= # optional for dynamic preview environments
```
The `AUTH0_DOMAIN`, `AUTH0_CLIENT_ID`, and `AUTH0_CLIENT_SECRET` can be obtained from the [Auth0 Dashboard](https://manage.auth0.com) once you've created an application. **This application must be a `Regular Web Application`**.
The `AUTH0_SECRET` is the key used to encrypt the session and transaction cookies. You can generate a secret using `openssl`:
```shell
openssl rand -hex 32
```
The `APP_BASE_URL` is the URL that your application is running on. When developing locally, this is most commonly `http://localhost:3000`.
If you omit it, the SDK will infer the base URL from the incoming request host at runtime.
> [!IMPORTANT]
> You will need to register the following URLs in your Auth0 Application via the [Auth0 Dashboard](https://manage.auth0.com):
>
> - Add `http://localhost:3000/auth/callback` to the list of **Allowed Callback URLs**
> - Add `http://localhost:3000` to the list of **Allowed Logout URLs**
>
> When using dynamic hosts (preview environments), ensure the resulting callback and logout URLs are registered in your Auth0 application.
#### Dynamic base URLs (Preview deployments)
For preview environments (`Vercel`, `Netlify`), you can omit `APP_BASE_URL` and let the SDK infer the base URL from the incoming request host at runtime. This keeps dynamic preview URLs working without extra configuration.
If you know the base URL at startup (for example, a stable production domain), set `appBaseUrl` or `APP_BASE_URL` to a single absolute URL. Comma-separated values are not supported.
Because the Host header is untrusted input, Auth0's Allowed Callback URLs are the safety net in this mode: if the inferred host is not registered, Auth0 rejects the authorize request.
Example (dynamic):
```ts
import { Auth0Client } from "@auth0/nextjs-auth0/server";
export const auth0 = new Auth0Client();
```
Example (static):
```ts
import { Auth0Client } from "@auth0/nextjs-auth0/server";
export const auth0 = new Auth0Client({
appBaseUrl: "https://app.example.com"
});
```
> [!NOTE]
> When relying on dynamic base URLs in production, the SDK enforces secure cookies. If you explicitly set `AUTH0_COOKIE_SECURE=false`, `session.cookie.secure=false`, or `transactionCookie.secure=false`, the SDK throws `InvalidConfigurationError`.
### 3. Create the Auth0 SDK client
Create an instance of the Auth0 client. This instance will be imported and used in anywhere you need access to the authentication methods on the server.
Add the following contents to a file named `lib/auth0.ts`:
```ts
import { Auth0Client } from "@auth0/nextjs-auth0/server";
export const auth0 = new Auth0Client();
```
> [!NOTE]
> The Auth0Client automatically uses safe defaults to manage authentication cookies. For advanced use cases, you can customize transaction cookie behavior by providing your own configuration. See [Transaction Cookie Configuration](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#transaction-cookie-configuration) for details.
### 4. Add the authentication middleware
Authentication requests in Next.js are intercepted at the network boundary using a middleware or proxy file.
Follow the setup below depending on your Next.js version.
#### On Next.js 15
Create a `middleware.ts` file in the root of your project:
```ts
import type { NextRequest } from "next/server";
import { auth0 } from "./lib/auth0"; // Adjust path if your auth0 client is elsewhere
export async function middleware(request: NextRequest) {
return await auth0.middleware(request);
}
export const config = {
matcher: [
/*
* Match all request paths except for:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico, sitemap.xml, robots.txt (metadata files)
*/
"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)"
]
};
```
> [!NOTE]
> If you're using a `src/` directory, the `middleware.ts` file must be created inside the `src/` directory.
#### On Next.js 16
Next.js 16 introduces a new convention called proxy.ts, replacing middleware.ts.
This change better represents the network interception boundary and unifies request handling
for both the Edge and Node runtimes.
Create a proxy.ts file in the root of your project (Or rename your existing middleware.ts to proxy.ts):
```ts
import { auth0 } from "./lib/auth0";
export async function proxy(request: Request) { // Note that proxy uses the standard Request type
return await auth0.middleware(request);
}
export const config = {
matcher: [
"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)"
]
};
```
> [!IMPORTANT]
> Starting with **Next.js 16**, the recommended file for handling authentication boundaries is **`proxy.ts`**. You can still continue using **`middleware.ts`** for backward compatibility, it will work under the **Edge runtime** in Next.js 16. However, it is **deprecated** for the Node runtime and will be removed in a future release.
>
> The new proxy layer also executes slightly earlier in the routing pipeline, so make sure your matcher patterns do not conflict with other proxy or middleware routes.
>
> Additionally, the Edge runtime now applies stricter header and cookie validation,
> so avoid setting non-string cookie values or invalid header formats.
> [!IMPORTANT]
> This broad middleware matcher is essential for rolling sessions and security features. For scenarios when rolling sessions are disabled, see [Session Configuration](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#session-configuration) for alternative approaches.
You can now begin to authenticate your users by redirecting them to your application's `/auth/login` route:
```tsx
import { auth0 } from "./lib/auth0"; // Adjust path if your auth0 client is elsewhere
export default async function Home() {
const session = await auth0.getSession();
if (!session) {
return (
Sign up
Log in
);
}
return (
Welcome, {session.user.name}!
);
}
```
> [!IMPORTANT]
> A default `` is safe — the SDK detects the AUTO prefetch header and returns `204 No Content` without writing a transaction cookie. Avoid `` (FULL prefetch): it sends no detectable prefetch header, so the SDK cannot distinguish it from a real navigation and will start a login flow. Use a plain `
` tag or `` if you need to be safe across all prefetch modes. See [Preventing "431 Request Header Fields Too Large" Errors](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#preventing-431-request-header-fields-too-large-errors) for details.
## Customizing the client
You can customize the client by using the options below:
| Option | Type | Description |
| --------------------------- | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| domain | `string \| DomainResolver` | The Auth0 domain for the tenant (e.g.: `example.us.auth0.com`). Accepts a static string or a `DomainResolver` function for [Multiple Custom Domains](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#multiple-custom-domains-mcd). Falls back to `AUTH0_DOMAIN` environment variable. |
| clientId | `string` | The Auth0 client ID. If it's not specified, it will be loaded from the `AUTH0_CLIENT_ID` environment variable. |
| clientSecret | `string` | The Auth0 client secret. If it's not specified, it will be loaded from the `AUTH0_CLIENT_SECRET` environment variable. |
| authorizationParameters | `AuthorizationParameters` | The authorization parameters to pass to the `/authorize` endpoint. See [Passing authorization parameters](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#passing-authorization-parameters) for more details. |
| clientAssertionSigningKey | `string` or `CryptoKey` | Private key for use with `private_key_jwt` clients. This can also be specified via the `AUTH0_CLIENT_ASSERTION_SIGNING_KEY` environment variable.