index
This is the documentation for next-auth@5
, which is currently experimental. For the documentation of the latest stable version, see next-auth@4.
If you are looking for the migration guide, visit next-auth@5 Migration Guide.
Signing in and signing outβ
The App Router embraces Server Actions that can be leveraged to decrease the amount of JavaScript sent to the browser.
Next.js Server Actions is under development. In the future, NextAuth.js will integrate with Server Actions and provide first-party APIs. The below is a workaround until then.
import { auth } from "../auth"
import { cookies, headers } from "next/headers"
function CSRF() {
const value = cookies().get("next-auth.csrf-token")?.value.split("|")[0]
return <input type="hidden" name="csrfToken" value={value} />
}
export function SignIn({ provider, ...props }: any) {
return (
<form action={`/api/auth/signin/${provider}`} method="post">
<button {{...props}}/>
<CSRF/>
</form>
)
}
export function SignOut(props: any) {
return (
<form action="/api/auth/signout" method="post">
<button {...props}/>
<CSRF/>
</form>
)
}
Alternatively, you can create client components, using the signIn()
and signOut
methods:
"use client";
import { signIn, signOut } from "@next-auth/react";
export function SignIn({ provider, ...props }: any) {
return <button {...props} onClick={() => signIn(provider)} />;
}
export function SignOut(props: any) {
return <button {...props} onClick={() => signOut()} />;
}
Then, you could for example use it like this:
import { headers } from "next/headers";
import { SignIn, SignOut } from "./auth-components";
export default async function Page() {
const session = await auth(headers());
if (session) {
return (
<>
<pre>{JSON.stringify(session, null, 2)}</pre>
<SignOut>Sign out</SignOut>
</>
);
}
return <SignIn id="github">Sign in with github</SignIn>;
}
default()β
Initialize NextAuth.js.
Exampleβ
import NextAuth from "next-auth";
import GitHub from "@auth/core/providers/github";
export const { handlers, auth } = NextAuth({ providers: [GitHub] });
default(
config
:NextAuthConfig
):NextAuthResult
Parametersβ
Parameter | Type |
---|---|
config | NextAuthConfig |
Returnsβ
NextAuthConfigβ
Configure NextAuth.js.
Propertiesβ
providersβ
providers:
Provider
<Profile
>[]
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?β
adapter:
Adapter
You can use the adapter option to pass in your database adapter.
Inherited fromβ
AuthConfig.adapter
callbacks?β
callbacks:
NextAuthCallbacks
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.
Overridesβ
AuthConfig.callbacks
cookies?β
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?β
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?β
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?β
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?β
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 option is ignored
Defaultβ
console;
Inherited fromβ
AuthConfig.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β
AuthConfig.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β
AuthConfig.redirectProxyUrl
secret?β
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?β
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β
Member | Type | Description |
---|---|---|
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 |
maxAge ? | number | Relative time from now in seconds when to expire the sessionDefault ts<br />2592000 // 30 days<br /> |
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 ? | number | How often the session should be updated in seconds. If set to 0 , session is updated every time.Default ts<br />86400 // 1 day<br /> |
Inherited fromβ
AuthConfig.session
theme?β
theme:
Theme
Changes the theme of built-in pages.
Inherited fromβ
AuthConfig.theme
trustHost?β
trustHost:
boolean
Todoβ
Inherited fromβ
AuthConfig.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β
AuthConfig.useSecureCookies
NextAuthResultβ
The result of invoking default, initialized with the NextAuthConfig. It contains methods to set up and interact with NextAuth.js in your Next.js app.
Propertiesβ
authβ
auth:
Function
Type declarationβ
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, Route Handlers or React Server Components.
Exampleβ
export { auth as middleware } from "./auth";
Exampleβ
import { auth } from "../auth";
import { headers } from "next/headers";
export default async function Page() {
const { token } = await auth(headers());
return <div>Hello {token?.name}</div>;
}
Exampleβ
import { auth } from "../../auth";
export const POST = auth((req) => {
// req.auth
});
(...
args
:WithAuthArgs
):Promise
<AuthData
& {expires
:string
;}> |Promise
<NextResponse
> | (...args
: [request: NextAuthRequest, event: NextFetchEvent]) =>Promise
<NextResponse
>
Parametersβ
Parameter | Type |
---|---|
...args | WithAuthArgs |
Returnsβ
Promise
<AuthData
& {expires
: string
;}> | Promise
<NextResponse
> | (...args
: [request: NextAuthRequest, event: NextFetchEvent]) => Promise
<NextResponse
>
handlersβ
handlers:
AppRouteHandlers
The NextAuth.js Route Handler methods. After initializing NextAuth.js in auth.ts
,
export these methods from app/api/auth/[...nextauth]/route.ts
.
Exampleβ
import { handlers } from "../../../../auth";
export const { GET, POST } = handlers;
export const runtime = "edge";