Skip to main content

index

Note

This is the documentation for next-auth@latest. Check out the documentation of v4 here.

If you are looking for the migration guide, visit the next-auth@latest Migration Guide.

Installation​

npm install next-auth@5 @auth/core

Environment variable inferrence​

NEXTAUTH_URL and NEXTAUTH_SECRET have been inferred since v4.

Since NextAuth.js v5 can also automatically infer environment variables that are prefiexed with AUTH_.

For example AUTH_GITHUB_ID and AUTH_GITHUB_SECRET will be used as the clientId and clientSecret options for the GitHub provider.

tip

The environment variable name inferring has the following format for OAuth providers: AUTH_{PROVIDER}_{ID|SECRET}.

PROVIDER is the uppercase snake case version of the provider's id, followed by either ID or SECRET respectively.

AUTH_SECRET and AUTH_URL are also aliased for NEXTAUTH_SECRET and NEXTAUTH_URL for consistency.

To add social login to your app, the configuration becomes:

auth.ts
import NextAuth from "next-auth"
import GitHub from "next-auth/providers/GitHub"
export const { handlers, auth } = NextAuth({ providers: [GitHub] })

And the .env.local file:

.env.local
AUTH_GITHUB_ID=...
AUTH_GITHUB_SECRET=...
AUTH_SECRET=...
tip

In production, AUTH_SECRET is a required environment variable - if not set, NextAuth.js will throw an error. See MissingSecretError for more details.

If you need to override the default values for a provider, you can still call it as a function GitHub({...}) as before.

default()​

default(config): NextAuthResult

Initialize NextAuth.js.

Example​

auth.ts
import NextAuth from "next-auth"
import GitHub from "@auth/core/providers/github"

export const { handlers, auth } = NextAuth({ providers: [GitHub] })

Parameters​

ParameterType
configNextAuthConfig

Returns​

NextAuthResult


Account​

Usually contains information about the provider being used and also extends TokenSet, which is different tokens returned by OAuth Providers.

Properties​

provider​

provider: string

Provider's id for this account. Eg.: "google"


providerAccountId​

providerAccountId: string

This value depends on the type of the provider being used to create the account.

  • oauth/oidc: The OAuth account's id, returned from the profile() callback.
  • email: The user's email address.
  • credentials: id returned from the authorize() callback

type​

type: ProviderType

Provider's type for this account


expires_at​

optional expires_at: number

Calculated value based on OAuth2TokenEndpointResponse.expires_in.

It is the absolute timestamp (in seconds) when the OAuth2TokenEndpointResponse.access_token expires.

This value can be used for implementing token rotation together with OAuth2TokenEndpointResponse.refresh_token.

See​

userId​

optional userId: string

id of the user this account belongs to

See​

https://authjs.dev/reference/adapters#user


NextAuthConfig​

Configure NextAuth.js.

Properties​

providers​

providers: Provider< any >[]

List 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.

Default​
;[]
Inherited from​

AuthConfig.providers


adapter​

optional adapter: Adapter

You can use the adapter option to pass in your database adapter.

Inherited from​

AuthConfig.adapter


callbacks​

optional callbacks: Partial< CallbacksOptions< Profile, Account > > & {authorized: (params) => Awaitable< undefined | boolean | NextResponse< unknown > >;}

Callbacks are asynchronous functions you can use to control what happens when an auth-related action is performed. Callbacks allow you to implement access controls without a database or to integrate with external databases or APIs.

callbacks.authorized​

optional authorized: (params) => Awaitable< undefined | boolean | NextResponse< unknown > >

Invoked when a user needs authorization, using Middleware.

You can override this behavior by returning a NextResponse.

Example​
app/auth.ts
...
async authorized({ request, auth }) {
const url = request.nextUrl

if(request.method === "POST") {
const { authToken } = (await request.json()) ?? {}
// If the request has a valid auth token, it is authorized
const valid = await validateAuthToken(authToken)
if(valid) return true
return NextResponse.json("Invalid auth token", { status: 401 })
}

// Logged in users are authenticated, otherwise redirect to login page
return !!auth.user
}
...
danger

If you are returning a redirect response, make sure that the page you are redirecting to is not protected by this callback, otherwise you could end up in an infinite redirect loop.

Parameters​
ParameterTypeDescription
paramsobject-
params.authnull | AuthSessionThe authenticated user or token, if any.
params.requestNextRequestThe request to be authorized.
Returns​

Awaitable< undefined | boolean | NextResponse< unknown > >

Overrides​

AuthConfig.callbacks


cookies​

optional cookies: Partial< CookiesOptions >

You can override the default cookie names and options for any of the cookies used by NextAuth.js. 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 behavior to support setting different cookies policies in development and production builds, as you will be opting out of the built-in dynamic policy.

  • ⚠ This is an advanced option. 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.
Default​
{
}
Inherited from​

AuthConfig.cookies


debug​

optional debug: boolean

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

  • ⚠ If you added a custom logger, this setting is ignored.
Default​
false
Inherited from​

AuthConfig.debug


events​

optional events: Partial< EventCallbacks >

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), but typically contains a user object and/or contents of the JSON Web Token and other information relevant to the event.

Default​
{
}
Inherited from​

AuthConfig.events


jwt​

optional jwt: Partial< JWTOptions >

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.

Inherited from​

AuthConfig.jwt


logger​

optional logger: Partial< LoggerInstance >

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

Example​
// /pages/api/auth/[...nextauth].js
import log from "logging-service"
export default NextAuth({
logger: {
error(code, ...message) {
log.error(code, message)
},
warn(code, ...message) {
log.warn(code, message)
},
debug(code, ...message) {
log.debug(code, message)
}
}
})
  • ⚠ When set, the debug option is ignored
Default​
console
Inherited from​

AuthConfig.logger


pages​

optional pages: Partial< PagesOptions >

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.

Default​
{
}
Example​
  pages: {
signIn: '/auth/signin',
signOut: '/auth/signout',
error: '/auth/error',
verifyRequest: '/auth/verify-request',
newUser: '/auth/new-user'
}
Inherited from​

AuthConfig.pages


redirectProxyUrl​

optional redirectProxyUrl: string

When set, during an OAuth sign-in flow, the redirect_uri of the authorization request will be set based on this value.

This is useful if your OAuth Provider only supports a single redirect_uri or you want to use OAuth on preview URLs (like Vercel), where you don't know the final deployment URL beforehand.

The url needs to include the full path up to where Auth.js is initialized.

Note​

This will auto-enable the state OAuth2Config.checks on the provider.

Example​
"https://authjs.example.com/api/auth"

You can also override this individually for each provider.

Example​
GitHub({
...
redirectProxyUrl: "https://github.example.com/api/auth"
})
Default​

AUTH_REDIRECT_PROXY_URL environment variable

See also: Guide: Securing a Preview Deployment

Inherited from​

AuthConfig.redirectProxyUrl


secret​

optional secret: string

A random string used to hash tokens, sign cookies and generate cryptographic keys. If not specified, it falls back to AUTH_SECRET or NEXTAUTH_SECRET from environment variables. To generate a random string, you can use the following command:

  • On Unix systems, type openssl rand -hex 32 in the terminal
  • Or generate one online
Inherited from​

AuthConfig.secret


session​

optional session: object

Configure your session like if you want to use JWT or a database, how long until an idle session expires, or to throttle write operations in case you are using a database.

Type declaration​
session.generateSessionToken​

optional generateSessionToken: () => string

Generate a custom session token for database-based sessions. By default, a random UUID or string is generated depending on the Node.js version. However, you can specify your own custom string (such as CUID) to be used.

Default​

randomUUID or randomBytes.toHex depending on the Node.js version

Returns​

string

session.maxAge​

optional maxAge: number

Relative time from now in seconds when to expire the session

Default​
2592000 // 30 days
session.strategy​

optional strategy: "jwt" | "database"

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.

Documentation | Adapter | About JSON Web Tokens

session.updateAge​

optional updateAge: number

How often the session should be updated in seconds. If set to 0, session is updated every time.

Default​
86400 // 1 day
Inherited from​

AuthConfig.session


theme​

optional theme: Theme

Changes the theme of built-in pages.

Inherited from​

AuthConfig.theme


trustHost​

optional trustHost: boolean

Todo​
Inherited from​

AuthConfig.trustHost


useSecureCookies​

optional useSecureCookies: boolean

When set to true 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. You can manually set this option to false to disable this security feature and allow cookies to be accessible from non-secured URLs (this is not recommended).

  • ⚠ This is an advanced option. 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.

The default is false HTTP and true for HTTPS sites.

Inherited from​

AuthConfig.useSecureCookies


NextAuthResult​

The result of invoking NextAuth, initialized with the NextAuthConfig. It contains methods to set up and interact with NextAuth.js in your Next.js app.

Properties​

auth​

auth: (...args) => Promise< null | AuthSession > & (...args) => Promise< null | AuthSession > & (...args) => Promise< null | AuthSession > & (...args) => AppRouteHandlerFn

A universal method to interact with NextAuth.js in your Next.js app. After initializing NextAuth.js in auth.ts, use this method in Middleware, Server Components, Route Handlers (app/), and Edge or Node.js API Routes (pages/).

In Middleware​

info

Adding auth to your Middleware is optional, but recommended to keep the user session alive.

Authentication is done by the callbacks.authorized callback.

Example​
middleware.ts
export { auth as middleware } from "./auth"

Alternatively you can wrap your own middleware with auth, where req is extended with auth:

Example​
middleware.ts
import { auth } from "./auth"
export default auth((req) => {
// req.auth
})
// Optionally, don't invoke Middleware on some paths
// Read more: https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"]
}

In Server Components​

Example​
app/page.ts
import { auth } from "../auth"

export default async function Page() {
const { user } = await auth()
return <p>Hello {user?.name}</p>
}

In Route Handlers​

Example​
app/api/route.ts
import { auth } from "../../auth"

export const POST = auth((req) => {
// req.auth
})

In Edge API Routes​

Example​
pages/api/protected.ts
import { auth } from "../../auth"

export default auth((req) => {
// req.auth
})

export const config = { runtime: "edge" }

In API Routes​

Example​
pages/api/protected.ts
import { auth } from "../auth"
import type { NextApiRequest, NextApiResponse } from "next"

export default async (req: NextApiRequest, res: NextApiResponse) => {
const session = await auth(req, res)
if (session) {
// Do something with the session
return res.json("This is protected content.")
}
res.status(401).json("You must be signed in.")
}

In getServerSideProps​

Example​
pages/protected-ssr.ts
import { auth } from "../auth"
//...
export const getServerSideProps: GetServerSideProps = async (context) => {
const session = await auth(context)

if (session) {
// Do something with the session
return { props: { session, content: (await res.json()).content } }
}

return { props: {} }
}

handlers​

handlers: AppRouteHandlers

The NextAuth.js Route Handler methods. These are used to expose an endpoint for OAuth/Email providers, as well as REST API endpoints (such as /api/auth/session) that can be contacted from the client.

After initializing NextAuth.js in auth.ts, re-export these methods.

In app/api/auth/[...nextauth]/route.ts:

app/api/auth/[...nextauth]/route.ts
export { GET, POST } from "../../../../auth"
export const runtime = "edge" // optional

Then auth.ts:

auth.ts
// ...
export const { handlers: { GET, POST }, auth } = NextAuth({...})

Methods​

signIn()​

signIn<P, R>( provider?, options?, authorizationParams?): Promise< R extends false ? any : never >

Sign in with a provider.

Example​
app/layout.tsx
import { signIn } from "../auth"

export default function Layout() {
return (
<form action={async () => {
"use server"
await signIn("github")
}}>
<button>Sign in with GitHub</button>
</form>
)
Type parameters​
ParameterDefault
P extends unknown-
R extends booleantrue
Parameters​
ParameterTypeDescription
provider?PProvider to sign in to
options?{redirect: R; redirectTo: string;} & Record< string, any >-
authorizationParams?string | string[][] | Record< string, string > | URLSearchParams-
Returns​

Promise< R extends false ? any : never >


signOut()​

signOut<R>(options?): Promise< R extends false ? any : never >

Sign out the user.

Example​
app/layout.tsx
import { signOut } from "../auth"

export default function Layout() {
return (
<form action={async () => {
"use server"
await signOut()
}}>
<button>Sign out</button>
</form>
)
Type parameters​
ParameterDefault
R extends booleantrue
Parameters​
ParameterTypeDescription
options?object-
options.redirect?RIf set to false, the signOut method will return the URL to redirect to instead of redirecting automatically.
options.redirectTo?stringThe URL to redirect to after signing out. By default, the user is redirected to the current page.
Returns​

Promise< R extends false ? any : never >


Profile​

The user info returned from your OAuth provider.

See​

https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims


Session​

Returned by useSession, getSession, returned by the session callback and also the shape received as a prop on the SessionProvider React Context

useSession | getSession | SessionProvider | session callback


User​

The shape of the returned object in the OAuth providers' profile callback, available in the jwt and session callbacks, or the second parameter of the session callback, when using a database.

signIn callback | session callback | jwt callback | profile OAuth provider callback