next-auth
If you are looking to migrate from v4, visit the Upgrade Guide (v5).
Installationβ
- npm
- Yarn
- pnpm
npm install next-auth@beta
yarn add next-auth@beta
pnpm add next-auth@beta
Environment variable inferenceβ
NEXTAUTH_URL
and NEXTAUTH_SECRET
have been inferred since v4.
Since NextAuth.js v5 can also automatically infer environment variables that are prefixed with AUTH_
.
For example AUTH_GITHUB_ID
and AUTH_GITHUB_SECRET
will be used as the clientId
and clientSecret
options for the GitHub provider.
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:
import NextAuth from "next-auth"
import GitHub from "next-auth/providers/github"
export const { handlers, auth } = NextAuth({ providers: [ GitHub ] })
And the .env.local
file:
AUTH_GITHUB_ID=...
AUTH_GITHUB_SECRET=...
AUTH_SECRET=...
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.
Lazy initializationβ
You can also initialize NextAuth.js lazily (previously known as advanced intialization), which allows you to access the request context in the configuration in some cases, like Route Handlers, Middleware, API Routes or getServerSideProps
.
The above example becomes:
import NextAuth from "next-auth"
import GitHub from "next-auth/providers/github"
export const { handlers, auth } = NextAuth(req => {
if (req) {
console.log(req) // do something with the request
}
return { providers: [ GitHub ] }
})
This is useful if you want to customize the configuration based on the request, for example, to add a different provider in staging/dev environments.
default()β
default(
config
):NextAuthResult
Initialize NextAuth.js.
Parametersβ
βͺ config: NextAuthConfig
| (request
) => NextAuthConfig
Returnsβ
Exampleβ
import NextAuth from "next-auth"
import GitHub from "@auth/core/providers/github"
export const { handlers, auth } = NextAuth({ providers: [GitHub] })
Lazy initialization:
Exampleβ
import NextAuth from "next-auth"
import GitHub from "@auth/core/providers/github"
export const { handlers, auth } = NextAuth((req) => {
console.log(req) // do something with the request
return {
providers: [GitHub],
},
})
Accountβ
Usually contains information about the provider being used
and also extends TokenSet
, which is different tokens returned by OAuth Providers.
Extendsβ
Partial
<OpenIDTokenEndpointResponse
>
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 theauthorize()
callback
typeβ
type:
ProviderType
Provider's type for this account
expires_atβ
expires_at?:
number
Calculated value based on [OAuth2TokenEndpointResponse.expires_in]([object Object]).
It is the absolute timestamp (in seconds) when the [OAuth2TokenEndpointResponse.access_token]([object Object]) expires.
This value can be used for implementing token rotation together with [OAuth2TokenEndpointResponse.refresh_token]([object Object]).
Seeβ
- https://authjs.dev/guides/basics/refresh-token-rotation#database-strategy
- https://www.rfc-editor.org/rfc/rfc6749#section-5.1
userIdβ
userId?:
string
id of the user this account belongs to
Seeβ
https://authjs.dev/reference/core/adapters#user
NextAuthConfigβ
Configure NextAuth.js.
Extendsβ
Omit
<AuthConfig
,"raw"
>
Propertiesβ
providersβ
providers:
Provider
[]
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β
Omit.providers
adapterβ
adapter?:
Adapter
You can use the adapter option to pass in your database adapter.
Inherited fromβ
Omit.adapter
basePathβ
basePath?:
string
The base path of the Auth.js API endpoints.
Defaultβ
"/auth"
Inherited fromβ
Omit.basePath
callbacksβ
callbacks?:
Partial
<CallbacksOptions
<Profile
,Account
> > &object
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.
Type declarationβ
authorizedβ
authorized?: (
params
) =>Awaitable
<undefined
|boolean
|NextResponse
<unknown
> |Response
>
Invoked when a user needs authorization, using Middleware.
You can override this behavior by returning a [NextResponse]([object Object]).
Parametersβ
βͺ params: object
βͺ params.auth: null
| Session
The authenticated user or token, if any.
βͺ params.request: NextRequest
The request to be authorized.
Returnsβ
Awaitable
< undefined
| boolean
| NextResponse
< unknown
> | Response
>
Exampleβ
...
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
}
...
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.
Overridesβ
Omit.callbacks
cookiesβ
cookies?:
Partial
<CookiesOptions
>
You can override the default cookie names and options for any of the cookies used by Auth.js. You can specify one or more cookies with custom properties and missing options will use the default values defined by Auth.js. 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β
Omit.cookies
debugβ
debug?:
boolean
Set debug to true to enable debug messages for authentication and database operations.
- β If you added a custom [AuthConfig.logger]([object Object]), this setting is ignored.
Defaultβ
false
Inherited fromβ
Omit.debug
eventsβ
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β
Omit.events
experimentalβ
experimental?:
Record
<string
,boolean
>
Use this option to enable experimental features. When enabled, it will print a warning message to the console.
Noteβ
Experimental features are not guaranteed to be stable and may change or be removed without notice. Please use with caution.
Defaultβ
{}
Inherited fromβ
Omit.experimental
jwtβ
jwt?:
Partial
<JWTOptions
>
JSON Web Tokens are enabled by default if you have not specified an [AuthConfig.adapter]([object Object]). JSON Web Tokens are encrypted (JWE) by default. We recommend you keep this behaviour.
Inherited fromβ
Omit.jwt
loggerβ
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 [AuthConfig.debug]([object Object]) option is ignored
Defaultβ
console
Inherited fromβ
Omit.logger
pagesβ
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β
Omit.pages
redirectProxyUrlβ
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β
Omit.redirectProxyUrl
secretβ
secret?:
string
|string
[]
A random string used to hash tokens, sign cookies and generate cryptographic keys.
To generate a random string, you can use the Auth.js CLI: npx auth secret
Noteβ
You can also pass an array of secrets, in which case the first secret that successfully decrypts the JWT will be used. This is useful for rotating secrets without invalidating existing sessions. The newer secret should be added to the start of the array, which will be used for all new sessions.
Inherited fromβ
Omit.secret
sessionβ
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β
generateSessionTokenβ
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.
Returnsβ
string
Defaultβ
randomUUID
or randomBytes.toHex
depending on the Node.js version
maxAgeβ
maxAge?:
number
Relative time from now in seconds when to expire the session
Defaultβ
2592000 // 30 days
strategyβ
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
updateAgeβ
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β
Omit.session
themeβ
theme?:
Theme
Changes the theme of built-in [AuthConfig.pages]([object Object]).
Inherited fromβ
Omit.theme
trustHostβ
trustHost?:
boolean
Auth.js relies on the incoming request's host
header to function correctly. For this reason this property needs to be set to true
.
Make sure that your deployment platform sets the host
header safely.
Official Auth.js-based libraries will attempt to set this value automatically for some deployment platforms (eg.: Vercel) that are known to set the host
header safely.
Inherited fromβ
Omit.trustHost
useSecureCookiesβ
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β
Omit.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
|Session
> & (...args
) =>Promise
<null
|Session
> & (...args
) =>Promise
<null
|Session
> & (...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β
Adding auth
to your Middleware is optional, but recommended to keep the user session alive.
Authentication is done by the callbacks.authorized callback.
Exampleβ
export { auth as middleware } from "./auth"
Alternatively you can wrap your own middleware with auth
, where req
is extended with auth
:
Exampleβ
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β
import { auth } from "../auth"
export default async function Page() {
const { user } = await auth()
return <p>Hello {user?.name}</p>
}
In Route Handlersβ
Exampleβ
import { auth } from "../../auth"
export const POST = auth((req) => {
// req.auth
})
In Edge API Routesβ
Exampleβ
import { auth } from "../../auth"
export default auth((req) => {
// req.auth
})
export const config = { runtime: "edge" }
In API Routesβ
Exampleβ
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β
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: {} }
}
Type declarationβ
Type declarationβ
Type declarationβ
Type declarationβ
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
:
export { GET, POST } from "../../../../auth"
export const runtime = "edge" // optional
Then auth.ts
:
// ...
export const { handlers: { GET, POST }, auth } = NextAuth({...})
signInβ
signIn: <
P
,R
>(provider
?,options
?,authorizationParams
?) =>Promise
<R
extendsfalse
?any
:never
>
Sign in with a provider. If no provider is specified, the user will be redirected to the sign in page.
By default, the user is redirected to the current page after signing in. You can override this behavior by setting the redirectTo
option.
Type parametersβ
βͺ P extends BuiltInProviderType
| string
& object
βͺ R extends boolean
= true
Parametersβ
βͺ provider?: P
Provider to sign in to
βͺ options?: FormData
| object
& Record
< string
, any
>
βͺ authorizationParams?: string
| string
[][] | Record
< string
, string
> | URLSearchParams
Returnsβ
Promise
< R
extends false
? any
: never
>
Exampleβ
import { signIn } from "../auth"
export default function Layout() {
return (
<form action={async () => {
"use server"
await signIn("github")
}}>
<button>Sign in with GitHub</button>
</form>
)
If an error occurs during signin, an instance of AuthError will be thrown. You can catch it like this:
import { AuthError } from "next-auth"
import { signIn } from "../auth"
export default function Layout() {
return (
<form action={async (formData) => {
"use server"
try {
await signIn("credentials", formData)
} catch(error) {
if (error instanceof AuthError) // Handle auth errors
throw error // Rethrow all other errors
}
}}>
<button>Sign in</button>
</form>
)
}
signOutβ
signOut: <
R
>(options
?) =>Promise
<R
extendsfalse
?any
:never
>
Sign out the user. If the session was created using a database strategy, the session will be removed from the database and the related cookie is invalidated. If the session was created using a JWT, the cookie is invalidated.
By default the user is redirected to the current page after signing out. You can override this behavior by setting the redirectTo
option.
Type parametersβ
βͺ R extends boolean
= true
Parametersβ
βͺ options?: object
βͺ options.redirect?: R
If set to false
, the signOut
method will return the URL to redirect to instead of redirecting automatically.
βͺ options.redirectTo?: string
The URL to redirect to after signing out. By default, the user is redirected to the current page.
Returnsβ
Promise
< R
extends false
? any
: never
>
Exampleβ
import { signOut } from "../auth"
export default function Layout() {
return (
<form action={async () => {
"use server"
await signOut()
}}>
<button>Sign out</button>
</form>
)
Profileβ
The user info returned from your OAuth provider.
Seeβ
https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims
Sessionβ
The active session of the logged in user.
Extendsβ
DefaultSession
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.
AuthErrorβ
Base error class for all Auth.js errors.
It's optimized to be printed in the server logs in a nicely formatted way
via the logger.error
option.
Extendsβ
Error
Propertiesβ
typeβ
type:
ErrorType
The error type. Used to identify the error in the logs.