Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

API reference

Auth.js API reference

Auth.js (NextAuth) authentication

Identifiers
124
With full guides
114
Types
9

Topics covered

  • Provider setup
  • JWT vs DB sessions
  • Callbacks
  • Middleware protection
  • Database adapters
  • Credentials provider
  • Role-based access
  • CSRF & security

Class

NameWhat it does
AuthErrorAuthError is the base class for all Auth.js errors and extends JavaScript’s Error. It supports a typed error category, optional structured cause data, and formatted server logging through Auth.js’s logger.error option.

Component

NameWhat it does
SessionProviderSessionProvider is a client-side React Context provider for the Next.js Pages Router. It makes session data available to descendants and coordinates session updates across browser tabs and windows.

Function

NameWhat it does
NextAuthNextAuth initializes Auth.js for a Next.js application from a NextAuthConfig and returns integration methods. Its result includes universal authentication access and route handlers.
authAuth.js’s Next.js auth function is a universal server-side authentication API. Export it from NextAuth configuration, call it to read the session, or use it to wrap handlers and inspect request authentication.
signInsignIn starts an Auth.js authentication flow. Pass a provider to authenticate with it directly, or omit the provider to show the configured sign-in page.
signOutFunction
getServerSessionFunction
CredentialsAuth.js’s Credentials provider lets you implement custom sign-in with arbitrary fields and your own validation logic. It is intended for existing authentication systems, does not persist these users in the database, and requires JWT sessions.
GoogleGoogle is a built-in Auth.js OAuth provider. Add it to the framework configuration, provide Google OAuth credentials, and register the provider-specific callback URL.
GitHubThe GitHub provider adds GitHub OAuth sign-in to Auth.js. Use it directly in the providers list or call it with configuration to override defaults.
unstable_updateunstable_update asynchronously updates session data using a partial session-shaped input. It resolves to the resulting Session or null.
DrizzleAdapterDrizzleAdapter connects Auth.js to a supported Drizzle ORM database. Pass the database instance and optionally a custom schema; it returns an Auth.js Adapter.
PrismaAdapterPrismaAdapter connects Auth.js to a Prisma-backed database. Give it an initialized Prisma client and place the returned Adapter in Auth.js configuration.
AuthAuth is Auth.js Core’s main request handler: it accepts a Web-standard Request and authentication configuration, then asynchronously returns a Web-standard Response.
handlershandlers is the route-handler collection returned by NextAuth. Export it from the Auth.js configuration and re-export its GET and POST methods from the Next.js App Router authentication route.
getTokengetToken reads an Auth.js JWT from request cookies or the Authorization header. It returns the decoded payload by default, the raw token when requested, or null when no usable JWT is found.
getCsrfTokengetCsrfToken() asynchronously returns the current Auth.js CSRF token for state-changing requests such as authentication or session updates.
getProvidersgetProviders() asynchronously retrieves the configured authentication providers in a client-safe record. It can resolve to null when no provider data is available.
getSessionIn Auth.js Express, getSession resolves the session associated with an incoming request. Use it in middleware or route handling, then check the result before serving protected content.
encodeencode asynchronously issues an Auth.js JWT from JWTEncodeParams. By default, the JWT is encrypted with A256CBC-HS512 using a key derived from the configured or supplied secret.
decodedecode asynchronously decodes an Auth.js-issued JWT. It returns the decoded payload or null, and supports a generic payload type.
customFetchcustomFetch lets an OAuth provider use a replacement fetch function for direct requests to its OAuth endpoints. It supports integrations such as proxies, custom fetch libraries, logging, mocks, and provider-specific request adjustments.
jwt callbackThe jwt callback runs when Auth.js creates or updates a JSON Web Token. Return the token, optionally with custom claims; use the session callback to explicitly expose selected claims to the client.
session callbackThe session callback customizes the session object returned to the client whenever Auth.js checks a session. Use it to expose selected JWT or database-user data, while avoiding sensitive fields.
signIn callbackThe signIn callback decides whether an authentication attempt may continue. Return true to allow it, false to deny it, or a URL string to redirect the user.
redirect callbackThe redirect callback controls where Auth.js sends users after callback-URL redirects, such as sign-in or sign-out. Return the requested destination when it meets your policy, or a safe fallback such as baseUrl.
authorized callbackThe authorized callback controls access when Auth.js Middleware evaluates a request. Return an authorization decision for normal flow, or a NextResponse for custom redirects and responses.

Hook

NameWhat it does
useSessionuseSession is a client-side React hook for reading and updating the current Auth.js session. It returns session data, authentication status, and an update method.

Interface

NameWhat it does
JWTAuth.js JWT utilities issue, decode, and retrieve encrypted JSON Web Tokens. They use AUTH_SECRET or a supplied secret and are intended primarily for the app that issued them.
SessionSession is Auth.js’s shared interface for the active logged-in user. It is returned by APIs such as auth, useSession, and getSession, and can be extended with TypeScript module augmentation.
AdapterUserAdapterUser is the database-facing user shape used by an Auth.js adapter. It represents someone who can sign in and carries the identity data needed to associate that person with accounts and authentication records.

Type Alias

NameWhat it does
UserUser is the Auth.js profile shape returned by an OAuth provider’s profile callback. Auth.js exposes it in JWT and session callbacks, and as the second session-callback parameter for database sessions.
AccountAccount is the Auth.js core type for information about the provider used during authentication. It also includes TokenSet fields for provider-returned token data.
ProfileProfile is the user-information object returned by an OAuth provider. Auth.js makes it available for provider mapping and relevant callbacks, with OIDC profiles potentially coming from an ID token or user-info response.
AuthConfigAuthConfig is the configuration type for Auth.js’s core Auth method. Use it to define authentication behavior and pass the resulting object to Auth or framework-specific initialization.
NextAuthConfigNextAuthConfig is the current Auth.js configuration type for Next.js. Use it to type a reusable configuration object, especially shared options that do not require an adapter.
DefaultSessionType Alias
AdapterSessionAdapterSession is the persisted session shape used by Auth.js database adapters. It records the expiration time, lookup token, and associated user ID.
AdapterAccountAdapterAccount describes an account record managed by an Auth.js adapter. It links a user to a provider and carries the provider-specific account identity used by adapter operations.
VerificationTokenVerificationToken is the database record for email magic-link authentication. It contains the user’s email identifier, a hashed token, and its expiration time.
AwaitableAwaitable<T> is Auth.js's public type for a result that can be supplied immediately as T or asynchronously through PromiseLike<T>. It lets callbacks and provider hooks support either synchronous or asynchronous implementations.
CredentialsConfigCredentialsConfig defines the options for Auth.js’s Credentials provider. It specifies sign-in inputs and custom authorization behavior, with authorize returning a User on success or null on failure.
OAuthConfigType Alias
ProviderType Alias

Const

NameWhat it does
ResendResend is an Auth.js passwordless email provider that sends magic links with verification tokens. It requires a database adapter, a verified sending domain, and a Resend API key.
AppleAuth.js provides a built-in Apple OAuth provider. Add Apple to the providers array and configure AUTH_APPLE_ID plus AUTH_APPLE_SECRET.
FacebookAuth.js’s Facebook provider adds Facebook OAuth sign-in to an application. Configure it with the Facebook App ID and App Secret, then register the provider-specific callback URL.
DiscordDiscord is a built-in Auth.js OAuth provider. Call it with a Discord client ID and secret, then include the returned configuration in Auth.js’s providers list.
Auth0Auth0 is a built-in Auth.js provider for signing users in through Auth0. Add it to the provider list, configure the documented credentials, and register the provider callback URL.
OktaOkta is a built-in Auth.js OpenID Connect provider. Register it in your framework configuration and provide AUTH_OKTA_ID, AUTH_OKTA_SECRET, and AUTH_OKTA_ISSUER through environment variables.
CognitoCognito is a built-in Auth.js OpenID Connect provider. Register it directly or configure it with a client ID, client secret, and Cognito issuer.
AzureADAzureAD is Auth.js’s built-in Azure Active Directory OIDC provider. It is deprecated in favor of the Microsoft Entra ID provider because Azure Active Directory was renamed.
KeycloakKeycloak is a built-in Auth.js OpenID Connect provider. Add it to the providers list and configure the client ID, secret, and realm-specific issuer.
LinkedInAuth.js includes a built-in LinkedIn provider. Add it to the providers array and configure the LinkedIn client credentials with AUTH_LINKEDIN_ID and AUTH_LINKEDIN_SECRET.
SpotifySpotify is a built-in Auth.js OAuth provider for adding Spotify sign-in. Register it with Spotify credentials and use the documented callback URL.
TwitchAuth.js provides a built-in Twitch OpenID Connect provider. Configure it with Twitch credentials and register its callback URL in the Twitch application console.
GitLabAuth.js provides a built-in GitLab OAuth 2 provider. Configure it with GitLab client credentials and register it in the Auth.js providers list.
SlackAuth.js provides a built-in Slack provider for adding Slack sign-in. Configure the Slack client credentials, register the HTTPS callback URL, and include Slack in the Auth.js provider list.
NodemailerNodemailer provides Auth.js email magic-link sign-in through an SMTP server. It sends verification-token links that sign users in or create their accounts, with a database required for token storage.
PasskeyPasskey enables WebAuthn registration and authentication in Auth.js. It requires a compatible database adapter, an Authenticator table, and explicit experimental WebAuthn enablement.
WebAuthnConst
TwitterTwitter is a built-in Auth.js OAuth provider. Add it to the providers array, configure its credentials through the standard environment variables, and use its Twitter callback URL.
MongoDBAdapterMongoDBAdapter connects Auth.js to MongoDB by turning a MongoDB client source into an Auth.js Adapter. It supports direct clients and custom client factories, with optional connection-close handling.
SupabaseAdapterSupabaseAdapter creates an Auth.js adapter backed by a Supabase database. Provide the database URL and access secret, then register the result in Auth.js configuration.
FirebaseAdapterFirebaseAdapter is Auth.js’s official Firestore adapter, built on the Firebase Admin SDK. Use it as the adapter in Auth.js configuration to persist authentication data in Firestore.
DynamoDBAdapterDynamoDBAdapter creates an Auth.js database adapter backed by DynamoDB. It requires an AWS SDK v3 DynamoDBDocument client and optionally accepts configuration for table and key names.
KyselyAdapterKyselyAdapter connects Auth.js to a Kysely database and returns an Auth.js Adapter. Its typed wrapper validates that the database interface includes the fields Auth.js expects.
SequelizeAdapterSequelizeAdapter connects Auth.js to a Sequelize database client and returns an Auth.js Adapter. Install the adapter, Sequelize, and the database driver, then provide the configured client to Auth.js.
NeonAdapterNeonAdapter connects Auth.js to Neon PostgreSQL through a Neon serverless Pool. Pass the Pool to Auth.js as its database adapter.
UpstashRedisAdapterUpstashRedisAdapter connects Auth.js to Upstash Redis for adapter-backed persistence. It accepts a Redis client and optional key-prefix settings, then returns an Auth.js Adapter.
XataAdapterXataAdapter connects Auth.js to Xata for persisting users, sessions, and other authentication data. Configure it with a generated XataClient instance.
FaunaAdapterFaunaAdapter is Auth.js’s official Fauna adapter. Pass it a Fauna Client and optionally adapter configuration to obtain an Auth.js Adapter.
PostgresAdapterPostgresAdapter is Auth.js’s official PostgreSQL adapter. Give it a PostgreSQL Pool to obtain an Adapter for the NextAuth configuration.
MicrosoftEntraIDMicrosoftEntraID is Auth.js’s built-in OpenID Connect provider for Microsoft Entra ID. Configure client credentials and optionally an issuer to restrict authentication to a specific tenant.
AuthentikAuthentik is a built-in Auth.js provider for signing in through an Authentik OpenID Connect application. Configure its client credentials and issuer, then add it to the Auth.js providers list.
DescopeAuth.js provides a built-in Descope sign-in integration. Configure it as an OIDC provider with the Descope client ID, access key, and issuer.
DropboxThe Dropbox provider is a built-in Auth.js OAuth integration. Configure it with Dropbox client credentials and add the resulting provider to the Auth.js providers array.
NotionAuth.js includes a built-in Notion OAuth provider. Configure it with Notion credentials and a redirect URI, then register the matching callback URL.
RedditAuth.js includes Reddit as a built-in OAuth provider. Configure Reddit credentials in NextAuth, and use duration: "permanent" when a refresh token is required.
SalesforceAuth.js includes Salesforce as a built-in OAuth/OIDC provider. Add it to the provider list, set the Salesforce client credentials, and register the documented callback URL in Salesforce.
HubspotHubSpot is a built-in Auth.js OAuth provider. Configure its client credentials with environment variables, add the provider to Auth.js, and register the framework-specific callback URL.
AtlassianConst
BattlenetBattleNet is Auth.js’s built-in Battle.net OAuth 2 provider. Configure it with a client ID, client secret, and a supported regional issuer.
BoxBox is a built-in Auth.js OAuth provider. Configure it with Box credentials and add it to the providers array; in Next.js, register the /api/auth/callback/box callback URL.
FoursquareFourSquare is a built-in Auth.js OAuth provider. Configure it with client credentials and a required YYYYMMDD-formatted API version, then register it in the providers list.
InstagramAuth.js provides a built-in Instagram OAuth integration. Configure it with an Instagram client ID and client secret, then register the documented callback URL.
KakaoKakao is an OAuth provider for Auth.js. Configure Kakao credentials, enable web login, register the Auth.js callback URL, and add the provider to your framework integration.
LineLine is Auth.js’s built-in LINE integration. Configure it with LINE OAuth credentials and register the provider with Auth.js to add LINE login.
MailchimpMailchimp is a built-in Auth.js OAuth provider. Add it to the providers list and configure the documented Mailchimp credentials; Auth.js supplies default provider settings.
NaverNaver is a built-in Auth.js OAuth provider. Add it to the providers list and configure the Naver client ID and secret through the documented environment variables.
NetlifyAuth.js includes a built-in Netlify OAuth provider. Register it in the provider list and configure the Netlify client credentials through the documented environment variables or provider options.
PatreonPatreon is a built-in Auth.js OAuth provider. Configure it with Patreon credentials and add the resulting provider configuration to Auth.js.
PinterestAuth.js provides a built-in Pinterest OAuth provider. Add Pinterest to the providers list and configure AUTH_PINTEREST_ID and AUTH_PINTEREST_SECRET for the standard setup.
StravaStrava is a built-in Auth.js OAuth provider. Add it to the providers list and supply credentials through AUTH_STRAVA_ID and AUTH_STRAVA_SECRET or explicit provider options.
TodoistTodoist is a built-in Auth.js OAuth provider. Configure it with Todoist client credentials and add the resulting provider configuration to Auth.js.
VkVk is Auth.js’s built-in VK OAuth provider. Add it to the providers list, configure VK credentials, and optionally override its default API-version endpoints.
WikimediaAuth.js includes a built-in Wikimedia OAuth provider. Configure its client credentials, register the framework-specific callback URL, and add Wikimedia to the Auth.js providers list.
WordPressAuth.js provides a built-in WordPress OAuth provider. Register its callback URL, supply the WordPress client credentials, and add WordPress to the Auth.js providers configuration.
YandexYandex is a built-in Auth.js OAuth provider. Configure it with a Yandex client ID and client secret, then include it in the Auth.js providers list.
ZoomThe Zoom provider factory adds Zoom OAuth authentication to Auth.js. Configure it with Zoom client credentials and include the resulting provider in Auth.js's providers array.
SendgridSendgrid is an Auth.js email provider for passwordless sign-in. It sends verification links through Sendgrid and requires a database adapter to store verification tokens.
MailgunMailgun enables passwordless Auth.js sign-in by emailing magic links with verification tokens. It requires a database adapter for token storage and supports JWT or database-managed sessions.
PostmarkPostmark is an Auth.js email provider for passwordless sign-in. It sends tokenized magic links and requires a database adapter to store verification tokens.

Enum

NameWhat it does
signIn eventevents.signIn is an asynchronous Auth.js event handler for work triggered by a sign-in. It is intended for side effects such as audit logging, not for controlling whether authentication succeeds.
signOut eventThe Auth.js signOut event is an asynchronous hook invoked during sign-out. Configure it for side effects such as audit logging, using a payload that reflects the active JWT or database session.
createUserEnum
updateUserupdateUser is an optional Auth.js adapter method for persisting changes to an existing user. It receives partial user data with a required id and returns the updated AdapterUser.
linkAccountlinkAccount is an optional Auth.js adapter method that persists an account connection in the database. Auth.js uses it internally, and applications may use it for manual linking.
session eventThe Auth.js session event is an asynchronous notification hook for session activity. Use it for side effects such as audit logging; its message varies with the authentication flow and session strategy.

Pipe

NameWhat it does
providersproviders is the Auth.js configuration array that enables authentication integrations. Add built-in provider definitions or custom OAuth/OIDC provider objects to make them available for sign-in.
adapterAn Auth.js adapter is the data-access layer that normalizes user, account, session, and related authentication persistence behind a common interface. Pass an adapter object, or configure one through an adapter factory, in Auth.js options.
callbacksAuth.js callbacks are asynchronous hooks that control authentication actions, including sign-in decisions, JWT contents, redirects, and client-visible session data. Configure them inside the callbacks option.
pagesAuth.js custom pages map page types such as signIn to application routes. Configured routes replace the matching built-in pages and must exist in the application.
sessionRetrieve the authenticated user's session in server or client code. Auth.js uses auth() on the server and useSession() on the client, with SessionProvider required for client-side access.
secretsecret is the Auth.js configuration value used to hash tokens, sign cookies, and generate cryptographic keys. Provide a random string or an ordered array to support secret rotation.
trustHosttrustHost is an optional boolean that lets Auth.js rely on the request’s host header when the deployment safely controls it. Set it to true for trusted deployments, especially behind a trusted proxy.
basePathbasePath sets the URL prefix for Auth.js API endpoints. It defaults to /api/auth in Next.js and /auth in other integrations.
cookiesAuth.js lets you override names and options for its cookies through the cookies configuration. Unspecified values retain Auth.js defaults, while session-cookie contents depend on the JWT or database session strategy.
eventsAuth.js events are optional asynchronous lifecycle handlers for side effects such as audit logging. They observe authentication activity without returning an authentication response.
debugAuth.js’s debug option enables detailed console diagnostics for authentication and database activity. Prefer enabling it during development and protect or sanitize logs because they can contain sensitive information.
themePipe
jwtAuth.js JWT utilities encode and decode the encrypted JWTs used by Auth.js. They use AUTH_SECRET or an explicit secret and are intended primarily for the app that issued them.
useSecureCookiesuseSecureCookies controls whether Auth.js cookies require HTTPS. It defaults to false for HTTP URLs and true for HTTPS sites.
experimentalPipe

Search across every package and filter by type in your dashboard.

Start learning