next-auth Documentation

Authentication for the Web.

28,306 stars TypeScript TypeScript 1 file ยท ~16,374 tokens #auth#authentication#csrf#jwt#nextauth#nextjs#nodejs#nuxt
RAW Doc

Docker & Self-Hosted Deployment Verified OCI

Deploy next-auth on any server, homelab, or cloud container platform.

1-Click Terminal Command
bash (docker run)
docker run -d --name next-auth -p 3000:3000 --restart always nextauthjs/next-auth:latest
Configured Services & Ports
โš™๏ธ authjs-docker-test
image: build locally
๐Ÿ”Œ Ports: 3000:3000
docker-compose.yml
yaml (docker-compose.yml)
services:
  authjs-docker-test:
    build: .
    environment:
      - TEST_KEYCLOAK_USERNAME
      - TEST_KEYCLOAK_PASSWORD
      - AUTH_KEYCLOAK_ID
      - AUTH_KEYCLOAK_SECRET
      - AUTH_KEYCLOAK_ISSUER
      - AUTH_SECRET="MohY0/2zSQw/psWEnejC2ka3Al0oifvY4YjOkUaFfnI="
      - AUTH_URL=http://localhost:3000/auth
    ports:
      - "3000:3000"

1. Project Overview & Quickstart (nextauthjs/next-auth)

File: README.md

Auth js is now part of Better Auth. We recommend new projects to start with Better Auth unless there are some very specific feature gaps (most notably stateless session management without a database).

Features

Flexible and easy to use

  • Designed to work with any OAuth service, it supports 2.0+, OIDC
  • Built-in support for many popular sign-in services
  • Email/Passwordless authentication
  • Passkeys/WebAuthn support
  • Bring Your Database - or none! - stateless authentication with any backend (Active Directory, LDAP, etc.)
  • Runtime-agnostic, runs anywhere! (Docker, Node.js, Serverless, etc.)

Own your data

Auth.js can be used with or without a database.

Secure by default

  • Promotes the use of passwordless sign-in mechanisms
  • Designed to be secure by default and encourage best practices for safeguarding user data
  • Uses Cross-Site Request Forgery (CSRF) Tokens on POST routes (sign in, sign out)
  • Default cookie policy aims for the most restrictive policy appropriate for each cookie
  • When JSON Web Tokens are used, they are encrypted by default (JWE) with A256CBC-HS512
  • Features tab/window syncing and session polling to support short-lived sessions
  • Attempts to implement the latest guidance published by Open Web Application Security Project

Advanced configuration allows you to define your routines to handle controlling what accounts are allowed to sign in, for encoding and decoding JSON Web Tokens and to set custom cookie security policies and session properties, so you can control who can sign in and how often sessions have to be re-validated.

TypeScript

Auth.js libraries are written with type safety in mind. Check out the docs for more information.

Security

If you think you have found a vulnerability (or are not sure) in Auth.js or any of the related packages (i.e. Adapters), we ask you to read our Security Policy to reach out responsibly. Please do not open Pull Requests/Issues/Discussions before consulting with us.

Acknowledgments

Auth.js is made possible thanks to all of its contributors.

Contributing

We're open to all community contributions! If you'd like to contribute in any way, please first read
our Contributing Guide.

License

ISC


File: apps/playgrounds/README.md

The playgrounds have been moved to nextauthjs/playgrounds.


File: apps/examples/sveltekit/README.md

The example repository is maintained from a monorepo. Pull Requests should be opened against nextauthjs/next-auth.

Overview

This is the official SvelteKit Auth example for Auth.js.

Getting started

You can instantly deploy this example to Vercel by clicking the following button.


File: apps/examples/solid-start/README.md

The example repository is maintained from a monorepo. Pull Requests should be opened against nextauthjs/next-auth.

Overview

This is the official SolidStart Auth example for Auth.js.

Getting started

You can follow the guide below, or click the following button to deploy this example to Vercel.

Installing

sh
pnpm add -D solid-start-vercel
sh
npm i -D solid-start-vercel
sh
yarn add -D solid-start-vercel

Adding to Vite config

ts
import solid from "solid-start/vite"
import dotenv from "dotenv"
import { defineConfig } from "vite"
// @ts-expect-error no typing
import vercel from "solid-start-vercel"

export default defineConfig(() => {
  dotenv.config()
  return {
    plugins: [solid({ ssr: true, adapter: vercel({ edge: false }) })],
  }
})

Environment Variables

  • ENABLE_VC_BUILD=1 .

Finishing up

Create a GitHub repo and push the code to it, then deploy it to Vercel.


File: apps/examples/qwik/README.md

Qwik City App โšก๏ธ


Project Structure

This project is using Qwik with QwikCity. QwikCity is just an extra set of tools on top of Qwik to make it easier to build a full site, including directory-based routing, layouts, and more.

Inside your project, you'll see the following directory structure:

text
โ”œโ”€โ”€ public/
โ”‚   โ””โ”€โ”€ ...
โ””โ”€โ”€ src/
    โ”œโ”€โ”€ components/
    โ”‚   โ””โ”€โ”€ ...
    โ””โ”€โ”€ routes/
        โ””โ”€โ”€ ...
  • src/routes: Provides the directory-based routing, which can include a hierarchy of layout.tsx layout files, and an index.tsx file as the page. Additionally, index.ts files are endpoints. Please see the routing docs for more info.

  • src/components: Recommended directory for components.

  • public: Any static assets, like images, can be placed in the public directory. Please see the Vite public directory for more info.

Add Integrations and deployment

Use the pnpm qwik add command to add additional integrations. Some examples of integrations includes: Cloudflare, Netlify or Express Server, and the Static Site Generator (SSG).

shell
pnpm qwik add # or `pnpm qwik add`

Development

Development mode uses Vite's development server. The dev command will server-side render (SSR) the output during development.

shell
npm start # or `pnpm start`

Note: during dev mode, Vite may request a significant number of .js files. This does not represent a Qwik production build.

Preview

The preview command will create a production build of the client modules, a production build of src/entry.preview.tsx, and run a local server. The preview server is only for convenience to preview a production build locally and should not be used as a production server.

shell
pnpm preview # or `pnpm preview`

Production

The production build will generate client and server modules by running both client and server build commands. The build command will use TypeScript to run a type check on the source code.

shell
pnpm build # or `pnpm build`

File: apps/examples/nextjs-pages/README.md

The example repository is maintained from a monorepo. Pull Requests should be opened against nextauthjs/next-auth.

Overview

NextAuth.js is a complete open source authentication solution.

This is an example application that shows how next-auth is applied to a basic Next.js app.

The deployed version can be found at next-auth-example.vercel.app

About NextAuth.js

NextAuth.js is an easy to implement, full-stack (client/server) open source authentication library originally designed for Next.js and Serverless. Our goal is to support even more frameworks in the future.

Go to next-auth.js.org for more information and documentation.

NextAuth.js is not officially associated with Vercel or Next.js.

Getting Started

1. Clone the repository and install dependencies

text
git clone https://github.com/nextauthjs/next-auth-example.git
cd next-auth-example
npm install

2. Configure your local environment

Copy the .env.local.example file in this directory to .env.local (which will be ignored by Git):

text
cp .env.local.example .env.local

Add details for one or more providers (e.g. Google, Twitter, GitHub, Email, etc).

Database

A database is needed to persist user accounts and to support email sign in. However, you can still use NextAuth.js for authentication without a database by using OAuth for authentication. If you do not specify a database, JSON Web Tokens will be enabled by default.

You can skip configuring a database and come back to it later if you want.

For more information about setting up a database, please check out the following links:

3. Configure Authentication Providers

  1. Review and update options in auth.ts as needed.

  2. When setting up OAuth, in the developer admin page for each of your OAuth services, you should configure the callback URL to use a callback path of {server}/api/auth/callback/{provider}.

e.g. For Google OAuth you would use: http://localhost:3000/api/auth/callback/google

A list of configured providers and their callback URLs is available from the endpoint api/auth/providers. You can find more information at https://authjs.dev/getting-started/providers/oauth-tutorial

  1. You can also choose to specify an SMTP server for passwordless sign in via email.

4. Start the application

To run your site locally, use:

text
npm run dev

To run it in production mode, use:

text
npm run build
npm run start

5. Preparing for Production

Follow the Deployment documentation

License

ISC


File: apps/examples/nextjs/README.md

The example repository is maintained from a monorepo. Pull Requests should be opened against nextauthjs/next-auth.

Overview

NextAuth.js is a complete open source authentication solution.

This is an example application that shows how next-auth is applied to a basic Next.js app.

The deployed version can be found at next-auth-example.vercel.app

About NextAuth.js

NextAuth.js is an easy to implement, full-stack (client/server) open source authentication library originally designed for Next.js and Serverless. Our goal is to support even more frameworks in the future.

Go to next-auth.js.org for more information and documentation.

NextAuth.js is not officially associated with Vercel or Next.js.

Getting Started

1. Clone the repository and install dependencies

text
git clone https://github.com/nextauthjs/next-auth-example.git
cd next-auth-example
pnpm install

2. Configure your local environment

Copy the .env.local.example file in this directory to .env.local (which will be ignored by Git):

text
cp .env.local.example .env.local

Add details for one or more providers (e.g. Google, Twitter, GitHub, Email, etc).

Database

A database is needed to persist user accounts and to support email sign in. However, you can still use NextAuth.js for authentication without a database by using OAuth for authentication. If you do not specify a database, JSON Web Tokens will be enabled by default.

You can skip configuring a database and come back to it later if you want.

For more information about setting up a database, please check out the following links:

3. Configure Authentication Providers

  1. Review and update options in auth.ts as needed.

  2. When setting up OAuth, in the developer admin page for each of your OAuth services, you should configure the callback URL to use a callback path of {server}/api/auth/callback/{provider}.

e.g. For Google OAuth you would use: http://localhost:3000/api/auth/callback/google

A list of configured providers and their callback URLs is available from the endpoint api/auth/providers. You can find more information at https://authjs.dev/getting-started/providers/oauth-tutorial

  1. You can also choose to specify an SMTP server for passwordless sign in via email.

4. Start the application

To run your site locally, use:

text
pnpm run dev

To run it in production mode, use:

text
pnpm run build
pnpm run start

5. Preparing for Production

Follow the Deployment documentation

License

ISC


File: apps/examples/express/README.md

The example repository is maintained from a monorepo. Pull Requests should be opened against nextauthjs/next-auth.

Overview

This is the official Express Auth example for Auth.js.

Getting started

You can instantly deploy this example to Vercel by clicking the following button.

Environment Variables

Once deployed, kindly ensure you set all required environment variables in the Environment section of your hosting service.

Node.js Compatibility

The recommended version of Node.js to use in this example is Node.js v20.0.0.

If you are using a version of Node.js lower than this (for example the minimum supported node version v18.0.0), you may need to enable Web Crypto API via the --experimental-webcrypto flag in the start and dev scripts of your package.json file.

Instead of using the experimental flag, you may use the following polyfill:

ts
// polyfill.cjs
globalThis.crypto ??= require("crypto").webcrypto

And then import it within a top-level file in the application:

ts
// server.ts
import "./polyfill.cjs"

File: apps/dev/sveltekit/README.md

The example repository is maintained from a monorepo. Pull Requests should be opened against nextauthjs/next-auth.

Documentation

2. Official Technical Reference & Guides (nextauthjs/docs)

File: README.md

Note: We have migrated the docs [`nextauthjs/docs`](https://github.com/nextauthjs/docs) code to our new primary monorepo at [`nextauthjs/next-auth`](https://github.com/nextauthjs/next-auth). This repository will be deprecated and most likely archived in the future.

Overview

This is the repository for the documentation page for NextAuth.js!

NextAuth.js is a complete open source authentication solution for Next.js applications.

This documentation site is based on the Docusaurus framework.

Getting Started

To start a local environment of this project, please do the following.

  1. Clone the repository.
bash
$ git clone https://github.com/nextauthjs/docs.git
  1. Install dependencies
bash
$ npm install
  1. Start the development server
bash
$ npm start

And thats all! Now you should have a local copy of this docs site running at localhost:3000!

Contributing

We're open to all community contributions! If you'd like to contribute in any way, please first read our Contributing Guide.

License

ISC


File: docs/configuration/providers/credentials.md


id: credentials title: Credentials

How to

The Credentials provider allows you to handle signing in with arbitrary credentials, such as a username and password, two-factor authentication or hardware device (e.g. YubiKey U2F / FIDO).

It is intended to support use cases where you have an existing system you need to authenticate users against.

js title="pages/api/auth/[...nextauth].js"
import CredentialsProvider from "next-auth/providers/credentials"
...
providers: [
  CredentialsProvider({
    // The name to display on the sign in form (e.g. 'Sign in with...')
    name: 'Credentials',
    // The credentials is used to generate a suitable form on the sign in page.
    // You can specify whatever fields you are expecting to be submitted.
    // e.g. domain, username, password, 2FA token, etc.
    // You can pass any HTML attribute to the  tag through the object.
    credentials: {
      username: { label: "Username", type: "text", placeholder: "jsmith" },
      password: {  label: "Password", type: "password" }
    },
    async authorize(credentials, req) {
      // You need to provide your own logic here that takes the credentials
      // submitted and returns either a object representing a user or value
      // that is false/null if the credentials are invalid.
      // e.g. return { id: 1, name: 'J Smith', email: '[email protected]' }
      // You can also use the `req` object to obtain additional parameters
      // (i.e., the request IP address)
      const res = await fetch("/your/endpoint", {
        method: 'POST',
        body: JSON.stringify(credentials),
        headers: { "Content-Type": "application/json" }
      })
      const user = await res.json()

      // If no error and we have user data, return it
      if (res.ok && user) {
        return user
      }
      // Return null if user data could not be retrieved
      return null
    }
  })
]
...

See the Credentials provider documentation for more information.

:::note
The Credentials provider can only be used if JSON Web Tokens are enabled for sessions. Users authenticated with the Credentials provider are not persisted in the database.
:::

Options

Name Description Type Required
id Unique ID for the provider string Yes
name Descriptive name for the provider string Yes
type Type of provider, in this case credentials "credentials" Yes
credentials The credentials to sign-in with Object Yes
authorize Callback to execute once user is to be authorized (credentials, req) => Promise Yes

File: docs/configuration/providers/email.md


id: email title: Email

How to

The Email provider sends "magic links" via email that the user can click on to sign in.
You have likely seen them before if you have used software like Slack.

Adding support for signing in via email in addition to one or more OAuth services provides a way for users to sign in if they lose access to their OAuth account (e.g. if it is locked or deleted).

Configuration is similar to other providers, but the options are different:

js title="pages/api/auth/[...nextauth].js"
import EmailProvider from `next-auth/providers/email`
...
providers: [
  EmailProvider({
    server: process.env.EMAIL_SERVER,
    from: process.env.EMAIL_FROM,
    // maxAge: 24 * 60 * 60, // How long email links are valid for (default 24h)
  }),
],
...

See the Email provider documentation for more information on how to configure email sign in.

:::note
The email provider requires a database, it cannot be used without one.
:::

Options

Name Description Type Required
id Unique ID for the provider string Yes
name Descriptive name for the provider string Yes
type Type of provider, in this case email "email" Yes
server Path or object pointing to the email server string or Object Yes
sendVerificationRequest Callback to execute when a verification request is sent (params) => Promise Yes
from The email address from which emails are sent, default: "[email protected]" string No
maxAge How long until the e-mail can be used to log the user in seconds. Defaults to 1 day number No

File: docs/configuration/providers/oauth.md


id: oauth title: OAuth

Authentication Providers in NextAuth.js are OAuth definitions that allow your users to sign in with their favorite preexisting logins. You can use any of our many predefined providers, or write your own custom OAuth configuration.

:::note
NextAuth.js is designed to work with any OAuth service, it supports OAuth 1.0, 1.0A, 2.0 and OpenID Connect and has built-in support for most popular sign-in services.
:::

Without going into too much detail, the OAuth flow generally has 6 parts:

  1. The application requests authorization to access service resources from the user
  2. If the user authorized the request, the application receives an authorization grant
  3. The application requests an access token from the authorization server (API) by presenting authentication of its own identity, and the authorization grant
  4. If the application identity is authenticated and the authorization grant is valid, the authorization server (API) issues an access token to the application. Authorization is complete.
  5. The application requests the resource from the resource server (API) and presents the access token for authentication
  6. If the access token is valid, the resource server (API) serves the resource to the application

Source: https://dzone.com/articles/open-id-connect-authentication-with-oauth20-author

For more details, check out Aaron Parecki's blog post OAuth2 Simplified or Postman's blog post OAuth 2.0: Implicit Flow is Dead, Try PKCE Instead.

How to

  1. Register your application at the developer portal of your provider. There are usually links to the portals included in the aforementioned documentation pages for each supported provider with details on how to register your application.

  2. The redirect URI (sometimes called Callback URL) should follow this format:

text
[origin]/api/auth/callback/[provider]

[provider] refers to the id of your provider (see options). For example, Twitter on localhost this would be:

text
http://localhost:3000/api/auth/callback/twitter

Using Google in our example application would look like this:

text
https://next-auth-example.vercel.app/api/auth/callback/google
  1. Create a .env file at the root of your project and add the client ID and client secret. For Twitter this would be:
text
TWITTER_ID=YOUR_TWITTER_CLIENT_ID
TWITTER_SECRET=YOUR_TWITTER_CLIENT_SECRET
  1. Now you can add the provider settings to the NextAuth options object. You can add as many OAuth providers as you like, as you can see providers is an array.
js title="pages/api/auth/[...nextauth].js"
import TwitterProvider from "next-auth/providers/"
...
providers: [
  TwitterProvider({
    clientId: process.env.TWITTER_ID,
    clientSecret: process.env.TWITTER_SECRET
  })
],
...
  1. Once a provider has been setup, you can sign in at the following URL: [origin]/api/auth/signin. This is an unbranded auto-generated page with all the configured providers.

Options

Whenever you configure a custom or a built-in OAuth provider, you have the following options available:

text
/* Detailed source-code truncated for AI context efficiency. */

`authorization` option

Configure how to construct the request to the Authorization endpoint.

There are two ways to use this option:

  1. You can either set authorization to be a full URL, like "https://example.com/oauth/authorization?scope=email".
  2. Use an object with url and params like so
    js
    authorization: {
      url: "https://example.com/oauth/authorization",
      params: { scope: "email" }
    }

:::tip
If your Provider is OpenID Connect (OIDC) compliant, we recommend using the wellKnown option instead.
:::

`token` option

Configure how to construct the request to the Token endpoint.

There are three ways to use this option:

  1. You can either set token to be a full URL, like "https://example.com/oauth/token?some=param".
  2. Use an object with url and params like so
    js
    token: {
      url: "https://example.com/oauth/token",
      params: { some: "param" }
    }
  3. Completely take control of the request:
    js
    token: {
      url: "https://example.com/oauth/token",
      async request(context) {
        // context contains useful properties to help you make the request.
        const tokens = await makeTokenRequest(context)
        return { tokens }
      }
    }

:::warning
Option 3. should not be necessary in most cases, but if your provider does not follow the spec, or you have some very unique constraints it can be useful. Try to avoid it, if possible.
:::

:::tip
If your Provider is OpenID Connect (OIDC) compliant, we recommend using the wellKnown option instead.
:::

`userinfo` option

A userinfo endpoint returns information about the logged-in user. It is not part of the OAuth specification, but usually available for most providers.

There are three ways to use this option:

  1. You can either set userinfo to be a full URL, like "https://example.com/oauth/userinfo?some=param".
  2. Use an object with url and params like so
    js
    userinfo: {
      url: "https://example.com/oauth/userinfo",
      params: { some: "param" }
    }
  3. Completely take control of the request:
    js
    userinfo: {
      url: "https://example.com/oauth/userinfo",
      // The result of this method will be the input to the `profile` callback.
      async request(context) {
        // context contains useful properties to help you make the request.
        return await makeUserinfoRequest(context)
      }
    }

:::warning
Option 3. should not be necessary in most cases, but if your provider does not follow the spec, or you have some very unique constraints it can be useful. Try to avoid it, if possible.
:::

:::tip
In the rare case you don't care about what this endpoint returns, or your provider does not have one, you could create a noop function:

js
userinfo: {
  request: () => {}
}

:::

:::tip
If your Provider is OpenID Connect (OIDC) compliant, we recommend using the wellKnown option instead. OIDC usually returns an id_token from the token endpoint. next-auth can decode the id_token to get the user information, instead of making an additional request to the userinfo endpoint. Just set idToken: true at the top-level of your provider configuration. If not set, next-auth will still try to contact this endpoint.
:::

`client` option

An advanced option, hopefully you won't need it in most cases. next-auth uses openid-client under the hood, see the docs on this option here.

Using a custom provider

You can use an OAuth provider that isn't built-in by using a custom object.

As an example of what this looks like, this is the provider object returned for the Google provider:

js
{
  id: "google",
  name: "Google",
  type: "oauth",
  wellKnown: "https://accounts.google.com/.well-known/openid-configuration",
  authorization: { params: { scope: "openid email profile" } },
  idToken: true,
  checks: ["pkce", "state"],
  profile(profile) {
    return {
      id: profile.sub,
      name: profile.name,
      email: profile.email,
      image: profile.picture,
    }
  },
}

As you can see, if your provider supports OpenID Connect and the /.well-known/openid-configuration endpoint contains support for the grant_type: authorization_code, you only need to pass the URL to that configuration file and define some basic fields like name and type.

Otherwise, you can pass a more full set of URLs for each OAuth2.0 flow step, for example:

js
{
  id: "kakao",
  name: "Kakao",
  type: "oauth",
  authorization: "https://kauth.kakao.com/oauth/authorize",
  token: "https://kauth.kakao.com/oauth/token",
  userinfo: "https://kapi.kakao.com/v2/user/me",
  profile(profile) {
    return {
      id: profile.id,
      name: profile.kakao_account?.profile.nickname,
      email: profile.kakao_account?.email,
      image: profile.kakao_account?.profile.profile_image_url,
    }
  },
}

Replace all the options in this JSON object with the ones from your custom provider - be sure to give it a unique ID and specify the required URLs, and finally add it to the providers array when initializing the library:

js title="pages/api/auth/[...nextauth].js"
import TwitterProvider from "next-auth/providers/twitter"
...
providers: [
  TwitterProvider({
    clientId: process.env.TWITTER_ID,
    clientSecret: process.env.TWITTER_SECRET,
  }),
  {
    id: 'customProvider',
    name: 'CustomProvider',
    type: 'oauth',
    scope: ''  // Make sure to request the users email address
    ...
  }
]
...

Built-in providers

NextAuth.js comes with a set of built-in providers. You can find them here. Each built-in provider has its own documentation page:

{Object.entries(require("../../../providers.json"))
.filter(([key]) => !["email", "credentials"].includes(key))
.sort(([, a], [, b]) => a.localeCompare(b))
.map(([key, name]) => (

text
<a href={`/providers/${key}`}>{name}</a>
  ,

)
)}

Override default options

For built-in providers, in most cases you will only need to specify the clientId and clientSecret. If you need to override any of the defaults, add your own options.

Even if you are using a built-in provider, you can override any of these options to tweak the default configuration.

:::note
The user provided options are deeply merged with the default options. That means you only have to override part of the options that you need to be different. For example if you want different scopes, overriding authorization.params.scope is enough, instead of the whole authorization option.
:::

js title=/api/auth/[...nextauth].js
import Auth0Provider from "next-auth/providers/auth0"

Auth0Provider({
  clientId: process.env.CLIENT_ID,
  clientSecret: process.env.CLIENT_SECRET,
  issuer: process.env.ISSUER,
  authorization: { params: { scope: "openid your_custom_scope" } },
})

Another example, the profile callback will return id, name, email and picture by default, but you might need more information from the provider. After setting the correct scopes, you can then do something like this:

js title=/api/auth/[...nextauth].js
import GoogleProvider from "next-auth/providers/google"

GoogleProvider({
  clientId: process.env.GOOGLE_CLIENT_ID,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET,
  profile(profile) {
    return {
      // Return all the profile information you need.
      // The only truly required field is `id`
      // to be able identify the account when added to a database
    }
  },
})

Adding a new built-in provider

If you think your custom provider might be useful to others, we encourage you to open a PR and add it to the built-in list so others can discover it much more easily!

You only need to add two changes:

  1. Add your config: src/providers/{provider}.ts
    โ€ข make sure you use a named default export, like this: export default function YourProvider
  2. Add provider documentation: /docs/providers/{provider}.md

That's it! ๐ŸŽ‰ Others will be able to discover and use this provider much more easily now!


File: docs/configuration/callbacks.md


id: callbacks title: Callbacks

Callbacks are asynchronous functions you can use to control what happens when an action is performed.

Callbacks are extremely powerful, especially in scenarios involving JSON Web Tokens as they allow you to implement access controls without a database and to integrate with external databases or APIs.

:::tip
If you want to pass data such as an Access Token or User ID to the browser when using JSON Web Tokens, you can persist the data in the token when the jwt callback is called, then pass the data through to the browser in the session callback.
:::

You can specify a handler for any of the callbacks below.

js title="pages/api/auth/[...nextauth].js"
...
  callbacks: {
    async signIn({ user, account, profile, email, credentials }) {
      return true
    },
    async redirect({ url, baseUrl }) {
      return baseUrl
    },
    async session({ session, user, token }) {
      return session
    },
    async jwt({ token, user, account, profile, isNewUser }) {
      return token
    }
...
}

The documentation below shows how to implement each callback, their default behaviour and an example of what the response for each callback should be. Note that configuration options and authentication providers you are using can impact the values passed to the callbacks.

Sign in callback

Use the signIn() callback to control if a user is allowed to sign in.

js title="pages/api/auth/[...nextauth].js"
...
callbacks: {
  async signIn({ user, account, profile, email, credentials }) {
    const isAllowedToSignIn = true
    if (isAllowedToSignIn) {
      return true
    } else {
      // Return false to display a default error message
      return false
      // Or you can return a URL to redirect to:
      // return '/unauthorized'
    }
  }
}
...
  • When using the Email Provider the signIn() callback is triggered both when the user makes a Verification Request (before they are sent an email with a link that will allow them to sign in) and again after they activate the link in the sign-in email.

    Email accounts do not have profiles in the same way OAuth accounts do. On the first call during email sign in the email object will include a property verificationRequest: true to indicate it is being triggered in the verification request flow. When the callback is invoked after a user has clicked on a sign-in link, this property will not be present.

    You can check for the verificationRequest property to avoid sending emails to addresses or domains on a blocklist (or to only explicitly generate them for email address in an allow list).

  • When using the Credentials Provider the user object is the response returned from the authorize callback and the profile object is the raw body of the HTTP POST submission.

:::note
When using NextAuth.js with a database, the User object will be either a user object from the database (including the User ID) if the user has signed in before or a simpler prototype user object (i.e. name, email, image) for users who have not signed in before.

When using NextAuth.js without a database, the user object will always be a prototype user object, with information extracted from the profile.
:::

:::note
Redirects returned by this callback cancel the authentication flow. Only redirect to error pages that, for example, tell the user why they're not allowed to sign in.

To redirect to a page after a successful sign in, please use the callbackUrl option or the redirect callback.
:::

Redirect callback

The redirect callback is called anytime the user is redirected to a callback URL (e.g. on signin or signout).

By default only URLs on the same URL as the site are allowed, you can use the redirect callback to customise that behaviour.

The default redirect callback looks like this:

js title="pages/api/auth/[...nextauth].js"
...
callbacks: {
  redirect({ url, baseUrl   }) {
    if (url.startsWith(baseUrl)) return url
    // Allows relative callback URLs
    else if (url.startsWith("/")) return new URL(url, baseUrl).toString()
    return baseUrl
  }
}
...

:::note
The redirect callback may be invoked more than once in the same flow.
:::

JWT callback

This callback is called whenever a JSON Web Token is created (i.e. at sign
in) or updated (i.e whenever a session is accessed in the client). The returned value will be signed and optionally encrypted, and it is stored in a cookie.

Requests to /api/auth/signin, /api/auth/session and calls to getSession(), useSession() will invoke this function, but only if you are using a JWT session. This method is not invoked when you persist sessions in a database.

  • As with database persisted session expiry times, token expiry time is extended whenever a session is active.
  • The arguments user, account, profile and isNewUser are only passed the first time this callback is called on a new session, after the user signs in. In subsequent calls, only token will be available.

The contents user, account, profile and isNewUser will vary depending on the provider and on if you are using a database or not. You can persist data such as User ID, OAuth Access Token in this token. To make it available in the browser, check out the session() callback as well.

js title="pages/api/auth/[...nextauth].js"
...
callbacks: {
  async jwt({ token, account }) {
    // Persist the OAuth access_token to the token right after signin
    if (account) {
      token.accessToken = account.access_token
    }
    return token
  }
}
...

:::tip
Use an if branch to check for the existence of parameters (apart from token). If they exist, this means that the callback is being invoked for the first time (i.e. the user is being signed in). This is a good place to persist additional data like an access_token in the JWT. Subsequent invocations will only contain the token parameter.
:::

:::warning
NextAuth.js does not limit how much data you can store in a JSON Web Token, however a ~4096 byte limit per cookie is commonly imposed by browsers.

If you need to persist a large amount of data, you will need to persist it elsewhere (e.g. in a database). A common solution is to store a key in the cookie that can be used to look up the remaining data in the database, for example, in the session() callback. Opt into database persisted sessions by setting session: {strategy: "database"}.
:::

Session callback

The session callback is called whenever a session is checked. By default, only a subset of the token is returned for increased security. If you want to make something available you added to the token through the jwt() callback, you have to explicitly forward it here to make it available to the client.

e.g. getSession(), useSession(), /api/auth/session

  • When using database sessions, the User object is passed as an argument.
  • When using JSON Web Tokens for sessions, the JWT payload is provided instead.
js title="pages/api/auth/[...nextauth].js"
...
callbacks: {
  async session({ session, token, user }) {
    // Send properties to the client, like an access_token from a provider.
    session.accessToken = token.accessToken
    return session
  }
}
...

:::tip
When using JSON Web Tokens the jwt() callback is invoked before the session() callback, so anything you add to the
JSON Web Token will be immediately available in the session callback, like for example an access_token from a provider.
:::

:::warning
The session object is not persisted server side, even when using database sessions - only data such as the session token, the user, and the expiry time is stored in the session table.

If you need to persist session data server side, you can use the accessToken returned for the session as a key - and connect to the database in the session() callback to access it. Session accessToken values do not rotate and are valid as long as the session is valid.

If using JSON Web Tokens instead of database sessions, you should use the User ID or a unique key stored in the token (you will need to generate a key for this yourself on sign in, as access tokens for sessions are not generated when using JSON Web Tokens).
:::


File: docs/configuration/databases.md


id: databases title: Databases

NextAuth.js offers multiple database adapters. Check out the overview.

As of v4 NextAuth.js no longer ships with an adapter included by default. If you would like to persist any information, you need to install one of the many available adapters yourself. See the individual adapter documentation pages for more details.

To learn more about databases in NextAuth.js and how they are used, check out databases in the FAQ.


How to use a database

See the documentation for adapters for more information on advanced configuration, including how to use NextAuth.js with other databases using a custom adapter.


File: docs/configuration/events.md


id: events title: Events

Events are asynchronous functions that do not return a response, they are useful for audit logs / reporting or handling any other side-effects.

You can specify a handler for any of these events below, for debugging or for an audit log.

:::note
The execution of your authentication API will be blocked by an await on your event handler. If your event handler starts any burdensome work it should not block its own promise on that work.
:::

Events

signIn

Sent on a successful sign in.

The message will be an object and contain:

  • user (from your adapter or from the provider if a credentials type provider)
  • account (from your adapter or the provider)
  • profile (from the provider, is undefined on credentials provider, use user instead)
  • isNewUser (whether your adapter had a user for this account already)

signOut

Sent when the user signs out.

The message object will contain one of these depending on if you use JWT or database persisted sessions:

  • token: The JWT token for this session.
  • session: The session object from your adapter that is being ended

createUser

Sent when the adapter is told to create a new user.

The message object will contain the user.

updateUser

Sent when the adapter is told to update an existing user. Currently, this is only sent when the user verifies their email address.

The message object will contain the user.

linkAccount

Sent when an account in a given provider is linked to a user in our user database. For example, when a user signs up with Twitter or when an existing user links their Google account.

The message object will contain:

  • user: The user object from your adapter.
  • providerAccount: The object returned from the provider.

session

Sent at the end of a request for the current session.

The message object will contain one of these depending on if you use JWT or database persisted sessions:

  • token: The JWT token for this session.
  • session: The session object from your adapter.

File: docs/configuration/nextjs.md

Next.js

Middleware

You can use a Next.js Middleware with NextAuth.js to protect your site.

Next.js 12 has introduced Middleware. It is a way to run logic before accessing any page, even when they are static. On platforms like Vercel, Middleware is run at the Edge.

If the following options look familiar, this is because they are a subset of these options. You can extract these to a common configuration object to reuse them. In the future, we would like to be able to run everything in Middleware. (See Caveats).

You can get the withAuth middleware function from next-auth/middleware either as a default or a named import:

Prerequisites

You must set the NEXTAUTH_SECRET environment variable when using this middleware. If you are using the secret option this value must match.

We strongly recommend replacing the secret value completely with this NEXTAUTH_SECRET environment variable. This environment variable will be picked up by both the NextAuth config, as well as the middleware config.


js
import withAuth from "next-auth/middleware"
// or
import { withAuth } from "next-auth/middleware"

`callbacks`

  • Required: No

Description

Callbacks are asynchronous functions you can use to control what happens when an action is performed.

Example (default value)

js
callbacks: {
   authorized({ req , token }) {
     if(token) return true // If there is a token, the user is authenticated
   }
 }

`pages`

  • Required: No

Description

Specify URLs to be used if you want to create custom sign in, and error pages. Pages specified will override the corresponding built-in page.

Example (default value)

js
pages: {
  signIn: '/auth/signin',
  error: '/auth/error',
}

See the documentation for the pages option for more information.


Examples

withAuth is very flexible, there are multiple ways to use it.

:::note
If you do not define the options, NextAuth.js will use the default values for the omitted options.
:::

default re-export

js title="pages/_middleware.js"
export { default } from "next-auth/middleware"

With this one line, when someone tries to load any of your pages, they will have to be logged-in first. Otherwise, they are redirected to the login page. It will assume that you are using the NEXTAUTH_SECRET environment variable.

default `withAuth` export

js title="pages/admin/_middleware.js"
import { withAuth } from "next-auth/middleware"

export default withAuth({
  callbacks: {
    authorized: ({ token }) => token?.role === "admin"
  }
})

With the above code, you just made sure that only user's with the admin role can access any of the pages under thge /admin route. (Including nested routes as well, like /admin/settings etc.).

wrap middleware

ts title="pages/admin/_middleware.ts"
import type { NextRequest } from "next/server"
import type { JWT } from "next-auth"

import { withAuth } from "next-auth/middleware"

export default withAuth(function middleware(req: NextRequest & { nextauth: { token: JWT } }) {
  console.log(req.nextauth.token)
}, {
  callbacks: {
    authorized: ({ token }) => token?.role === "admin"
  }
})

The middleware function will only be invoked if the authorized callback returns true.


Caveats

  • Currently only supports session verification, as parts of the sign-in code need to run in a Node.js environment. In the future, we would like to make sure that NextAuth.js can fully run at the Edge
  • Only supports the "jwt" session strategy. We need to wait until databases at the Edge become mature enough to ensure a fast experience. (If you know of an Edge-compatible database, we would like if you proposed a new Adapter)

File: docs/configuration/options.md


id: options title: Options

Environment Variables

NEXTAUTH_URL

When deploying to production, set the NEXTAUTH_URL environment variable to the canonical URL of your site.

text
NEXTAUTH_URL=https://example.com

If your Next.js application uses a custom base path, specify the route to the API endpoint in full. More informations about the usage of custom base path here.

e.g. NEXTAUTH_URL=https://example.com/custom-route/api/auth

:::tip
When you're using a custom base path, you will need to pass the basePath page prop to the <SessionProvider>. More informations here.
:::

:::note
We automatically detect when you deploy to Vercel so you don't have to define this variable.
:::

NEXTAUTH_SECRET

Used to encrypt the NextAuth.js JWT, and to hash email verification tokens. This is the default value for the secret option. The secret option might be removed in the future in favor of this.

If you are using Middleware this environment variables must be set.

NEXTAUTH_URL_INTERNAL

If provided, server-side calls will use this instead of NEXTAUTH_URL. Useful in environments when the server doesn't have access to the canonical URL of your site. Defaults to NEXTAUTH_URL.

text
NEXTAUTH_URL_INTERNAL=http://10.240.8.16

Options

Options are passed to NextAuth.js when initializing it in an API route.

providers

  • Default value: []
  • Required: Yes

Description

An array of authentication providers for signing in (e.g. Google, Facebook, Twitter, GitHub, Email, etc) in any order. This can be one of the built-in providers or an object with a custom provider.

See the providers documentation for a list of supported providers and how to use them.


secret

  • Default value: string (SHA hash of the "options" object) in development, no default in production.
  • Required: Yes, in production!

Description

A random string is used to hash tokens, sign/encrypt cookies and generate cryptographic keys.

If you set NEXTAUTH_SECRET as an environment variable, you don't have to define this option.

If no value specified specified in development (and there is no NEXTAUTH_SECRET variable either), it uses a hash for all configuration options, including OAuth Client ID / Secrets for entropy.

:::warning
Not providing any secret or NEXTAUTH_SECRET will throw an error in production.
:::

You can quickly create a good value on the command line via this openssl command.

bash
$ openssl rand -base64 32

:::tip
If you rely on the default secret generation in development, you might notice JWT decryption errors, since the secret changes whenever you change your configuration. Defining an explicit secret will make this problem go away. We will likely make this option mandatory, even in development, in the future.
:::


session

  • Default value: object
  • Required: No

Description

The session object and all properties on it are optional.

Default values for this option are shown below:

js
session: {
  // Choose how you want to save the user session.
  // The default is `"jwt"`, an encrypted JWT (JWE) in the session cookie.
  // If you use an `adapter` however, we default it to `"database"` instead.
  // You can still force a JWT session by explicitly defining `"jwt"`.
  // When using `"database"`, the session cookie will only contain a `sessionToken` value,
  // which is used to look up the session in the database.
  strategy: "database",

  // Seconds - How long until an idle session expires and is no longer valid.
  maxAge: 30 * 24 * 60 * 60, // 30 days

  // Seconds - Throttle how frequently to write to database to extend a session.
  // Use it to limit write operations. Set to 0 to always update the database.
  // Note: This option is ignored if using JSON Web Tokens
  updateAge: 24 * 60 * 60, // 24 hours
}

jwt

  • Default value: object
  • Required: No

Description

JSON Web Tokens can be used for session tokens if enabled with session: { strategy: "jwt" } option. JSON Web Tokens are enabled by default if you have not specified an adapter.

JSON Web Tokens are encrypted (JWE) by default. We recommend you keep this behaviour, but you can override this using the encode and decode methods.

JSON Web Token Options

js
jwt: {
  // The maximum age of the NextAuth.js issued JWT in seconds.
  // Defaults to `session.maxAge`.
  maxAge: 60 * 60 * 24 * 30,
  // You can define your own encode/decode functions for signing and encryption
  // if you want to override the default behavior.
  async encode({ secret, token, maxAge }) {},
  async decode({ secret, token }) {},
}

An example JSON Web Token contains a payload like this:

js
{
  name: 'Iain Collins',
  email: '[email protected]',
  picture: 'https://example.com/image.jpg',
  iat: 1594601838,
  exp: 1597193838
}

JWT Helper

You can use the built-in getToken() helper method to verify and decrypt the token, like this:

js
import { getToken } from "next-auth/jwt"

const secret = process.env.NEXTAUTH_SECRET

export default async function handler(req, res) {
  // if using `NEXTAUTG_SECRET` env variable, we detect it, and you won't actually need to `secret`
  // const token = await getToken({ req })
  const token = await getToken({ req, secret })
  console.log("JSON Web Token", token)
  res.end()
}

For convenience, this helper function is also able to read and decode tokens passed from the Authorization: 'Bearer token' HTTP header.

Required

The getToken() helper requires the following options:

  • req - (object) Request object
  • secret - (string) JWT Secret. Use NEXTAUTH_SECRET instead.

You must also pass any options configured on the jwt option to the helper.

e.g. Including custom session maxAge and custom signing and/or encryption keys or options

Optional

It also supports the following options:

  • secureCookie - (boolean) Use secure prefixed cookie name

    By default, the helper function will attempt to determine if it should use the secure prefixed cookie (e.g. true in production and false in development, unless NEXTAUTH_URL contains an HTTPS URL).

  • cookieName - (string) Session token cookie name

    The secureCookie option is ignored if cookieName is explicitly specified.

  • raw - (boolean) Get raw token (not decoded)

    If set to true returns the raw token without decrypting or verifying it.

:::note
The JWT is stored in the Session Token cookie, the same cookie used for tokens with database sessions.
:::


pages

  • Default value: {}
  • Required: No

Description

Specify URLs to be used if you want to create custom sign in, sign out and error pages.

Pages specified will override the corresponding built-in page.

For example:

js
pages: {
  signIn: '/auth/signin',
  signOut: '/auth/signout',
  error: '/auth/error', // Error code passed in query string as ?error=
  verifyRequest: '/auth/verify-request', // (used for check email message)
  newUser: '/auth/new-user' // New users will be directed here on first sign in (leave the property out if not of interest)
}

See the documentation for the pages option for more information.


callbacks

  • Default value: object
  • Required: No

Description

Callbacks are asynchronous functions you can use to control what happens when an action is performed.

Callbacks are extremely powerful, especially in scenarios involving JSON Web Tokens as they allow you to implement access controls without a database and to integrate with external databases or APIs.

You can specify a handler for any of the callbacks below.

js
callbacks: {
  async signIn({ user, account, profile, email, credentials }) {
    return true
  },
  async redirect({ url, baseUrl }) {
    return baseUrl
  },
  async session({ session, token, user }) {
    return session
  },
  async jwt({ token, user, account, profile, isNewUser }) {
    return token
  }
}

See the callbacks documentation for more information on how to use the callback functions.


events

  • Default value: object
  • Required: No

Description

Events are asynchronous functions that do not return a response, they are useful for audit logging.

You can specify a handler for any of these events below - e.g. for debugging or to create an audit log.

The content of the message object varies depending on the flow (e.g. OAuth or Email authentication flow, JWT or database sessions, etc). See the events documentation for more information on the form of each message object and how to use the events functions.

js
events: {
  async signIn(message) { /* on successful sign in */ },
  async signOut(message) { /* on signout */ },
  async createUser(message) { /* user created */ },
  async updateUser(message) { /* user updated - e.g. their email was verified */ },
  async linkAccount(message) { /* account (e.g. Twitter) linked to a user */ },
  async session(message) { /* session is active */ },
  async error(message) { /* error in authentication flow */ }
}

adapter

  • Default value: none
  • Required: No

Description

By default NextAuth.js does not include an adapter any longer. If you would like to persist user / account data, please install one of the many available adapters. More information can be found in the adapter documentation.


debug

  • Default value: false
  • Required: No

Description

Set debug to true to enable debug messages for authentication and database operations.


logger

  • Default value: console
  • Required: No

Description

Override any of the logger levels (undefined levels will use the built-in logger), and intercept logs in NextAuth. You can use this to send NextAuth logs to a third-party logging service.

The code parameter for error and warn are explained in the Warnings and Errors pages respectively.

Example:

js title="/pages/api/auth/[...nextauth].js"
import log from "logging-service"

export default NextAuth({
  ...
  logger: {
    error(code, metadata) {
      log.error(code, metadata)
    },
    warn(code) {
      log.warn(code)
    },
    debug(code, metadata) {
      log.debug(code, metadata)
    }
  }
  ...
})

:::note
If the debug level is defined by the user, it will be called regardless of the debug: false option.
:::


theme

  • Default value: object
  • Required: No

Description

Changes the color scheme theme of pages as well as allows some minor customization. Set theme.colorScheme to "light", if you want to force pages to always be light. Set to "dark", if you want to force pages to always be dark. Set to "auto", (or leave this option out) if you want the pages to follow the preferred system theme. (Uses the prefers-color-scheme media query.)

In addition, you can define a logo URL in theme.logo which will be rendered above the main card in the default signin/signout/error/verify-request pages, as well as a theme.brandColor which will affect the accent color of these pages.

js
theme: {
  colorScheme: "auto", // "auto" | "dark" | "light"
  brandColor: "", // Hex color code
  logo: "" // Absolute URL to image
}

Advanced Options

Advanced options are passed the same way as basic options, but may have complex implications or side effects. You should try to avoid using advanced options unless you are very comfortable using them.


useSecureCookies

  • Default value: true for HTTPS sites / false for HTTP sites
  • Required: No

Description

When set to true (the default for all site URLs that start with https://) then all cookies set by NextAuth.js will only be accessible from HTTPS URLs.

This option defaults to false on URLs that start with http:// (e.g. http://localhost:3000) for developer convenience.

:::note
Properties on any custom cookies that are specified override this option.
:::

:::warning
Setting this option to false in production is a security risk and may allow sessions to be hijacked if used in production. It is intended to support development and testing. Using this option is not recommended.
:::


cookies

  • Default value: {}
  • Required: No

Description

Cookies in NextAuth.js are chunked by default, meaning that once they reach the 4kb limit, we will create a new cookie with the .{number} suffix and reassemble the cookies in the correct order when parsing / reading them. This was introduced to avoid size constraints which can occur when users want to store additional data in their sessionToken, for example.

You can override the default cookie names and options for any of the cookies used by NextAuth.js.

This is an advanced option and using it is not recommended as you may break authentication or introduce security flaws into your application.

You can specify one or more cookies with custom properties, but if you specify custom options for a cookie you must provide all the options for that cookie.

If you use this feature, you will likely want to create conditional behaviour to support setting different cookies policies in development and production builds, as you will be opting out of the built-in dynamic policy.

:::tip
An example of a use case for this option is to support sharing session tokens across subdomains.
:::

Example

js
cookies: {
  sessionToken: {
    name: `__Secure-next-auth.session-token`,
    options: {
      httpOnly: true,
      sameSite: 'lax',
      path: '/',
      secure: true
    }
  },
  callbackUrl: {
    name: `__Secure-next-auth.callback-url`,
    options: {
      sameSite: 'lax',
      path: '/',
      secure: true
    }
  },
  csrfToken: {
    name: `__Host-next-auth.csrf-token`,
    options: {
      httpOnly: true,
      sameSite: 'lax',
      path: '/',
      secure: true
    }
  },
  pkceCodeVerifier: {
    name: `${cookiePrefix}next-auth.pkce.code_verifier`,
    options: {
      httpOnly: true,
      sameSite: 'lax',
      path: '/',
      secure: useSecureCookies
    }
  },
  state: {
    name: `${cookiePrefix}next-auth.state`,
    options: {
      httpOnly: true,
      sameSite: "lax",
      path: "/",
      secure: useSecureCookies,
    },
  },
}

:::warning
Using a custom cookie policy may introduce security flaws into your application and is intended as an option for advanced users who understand the implications. Using this option is not recommended.
:::