@auth/core
Experimental @auth/core
is under active development.
This is the main entry point to the Auth.js library.
Based on the Request and Response Web standard APIs. Primarily used to implement framework-specific packages, but it can also be used directly.
Installation
npm install @auth/core
Usage
import { Auth } from "@auth/core"
const request = new Request("https://example.com")
const response = await Auth(request, {...})
console.log(response instanceof Response) // true
Resources
AuthConfig
Configure the Auth method.
Example
import Auth, { type AuthConfig } from "@auth/core"
export const authConfig: AuthConfig = {...}
const request = new Request("https://example.com")
const response = await AuthHandler(request, authConfig)
See
Extends
IntegrationAuthConfig
.DeprecatedAuthConfig
Properties
adapter?
optional adapter: Adapter;
You can use the adapter option to pass in your database adapter.
basePath?
optional basePath: string;
The base path of the Auth.js API endpoints.
Default
"/api/auth"
in “next-auth” (for historical reasons only); "/auth"
for all other frameworks
callbacks?
optional callbacks: {
jwt: (params) => Awaitable<null | JWT>;
redirect: (params) => Awaitable<string>;
session: (params) => Awaitable<Session | DefaultSession>;
signIn: (params) => Awaitable<string | boolean>;
};
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.
jwt()?
optional jwt: (params) => Awaitable<null | JWT>;
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). Anything you return here will be saved in the JWT and forwarded to the session callback. There you can control what should be returned to the client. Anything else will be kept from your frontend. The JWT is encrypted by default via your AUTH_SECRET environment variable.
Parameters
Parameter | Type | Description |
---|---|---|
params | Object | - |
params.account | null | Account | Contains information about the provider that was used to sign in. Also includes TokenSet Note available when trigger is "signIn" or "signUp" |
params.isNewUser ? | boolean | Deprecated use trigger === "signUp" instead |
params.profile ? | Profile | The OAuth profile returned from your provider. (In case of OIDC it will be the decoded ID Token or /userinfo response) Note available when trigger is "signIn" . |
params.session ? | any | When using AuthConfig.session strategy: "jwt" , this is the datasent from the client via the useSession().update method.⚠ Note, you should validate this data before using it. |
params.token | JWT | When trigger is "signIn" or "signUp" , it will be a subset of JWT,name , email and image will be included.Otherwise, it will be the full JWT for subsequent calls. |
params.trigger ? | "signIn" | "signUp" | "update" | Check why was the jwt callback invoked. Possible reasons are: - user sign-in: First time the callback is invoked, user , profile and account will be present.- user sign-up: a user is created for the first time in the database (when AuthConfig.session.strategy is set to "database" )- update event: Triggered by the useSession().update method.In case of the latter, trigger will be undefined . |
params.user | User | AdapterUser | Either the result of the OAuthConfig.profile or the CredentialsConfig.authorize callback. Note available when trigger is "signIn" or "signUp" .Resources: - Credentials Provider - User database model |
Returns
redirect()?
optional redirect: (params) => Awaitable<string>;
This callback is called anytime the user is redirected to a callback URL (i.e. on signin or signout). By default only URLs on the same host as the origin are allowed. You can use this callback to customise that behaviour.
Example
callbacks: {
async redirect({ url, baseUrl }) {
// Allows relative callback URLs
if (url.startsWith("/")) return `${baseUrl}${url}`
// Allows callback URLs on the same origin
if (new URL(url).origin === baseUrl) return url
return baseUrl
}
}
Parameters
Parameter | Type | Description |
---|---|---|
params | Object | - |
params.baseUrl | string | Default base URL of site (can be used as fallback) |
params.url | string | URL provided as callback URL by the client |
Returns
Awaitable
<string
>
session()?
optional session: (params) => Awaitable<Session | DefaultSession>;
This callback is called whenever a session is checked.
(i.e. when invoking the /api/session
endpoint, using useSession
or getSession
).
The return value will be exposed to the client, so be careful what you return here!
If you want to make anything available to the client which you’ve added to the token
through the JWT callback, you have to explicitly return it here as well.
⚠ By default, only a subset (email, name, image) of the token is returned for increased security.
The token argument is only available when using the jwt session strategy, and the user argument is only available when using the database session strategy.
Example
callbacks: {
async session({ session, token, user }) {
// Send properties to the client, like an access_token from a provider.
session.accessToken = token.accessToken
return session
}
}
Parameters
Parameter | Type |
---|---|
params | { session : { user : AdapterUser ; } & AdapterSession ; user : AdapterUser ; } & { session : Session ; token : JWT ; } & { newSession : any ; trigger : "update" ; } |
Returns
Awaitable
<Session
| DefaultSession
>
signIn()?
optional signIn: (params) => Awaitable<string | boolean>;
Controls whether a user is allowed to sign in or not.
Returning true
continues the sign-in flow.
Returning false
or throwing an error will stop the sign-in flow and redirect the user to the error page.
Returning a string will redirect the user to the specified URL.
Unhandled errors will throw an AccessDenied
with the message set to the original error.
Example
callbacks: {
async signIn({ profile }) {
// Only allow sign in for users with email addresses ending with "yourdomain.com"
return profile?.email?.endsWith("@yourdomain.com")
}
Parameters
Parameter | Type | Description |
---|---|---|
params | Object | - |
params.account | null | Account | - |
params.credentials ? | Record <string , CredentialInput > | If Credentials provider is used, it contains the user credentials |
params.email ? | Object | If Email provider is used, on the first call, it contains averificationRequest: true property 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 propertyto avoid sending emails to addresses or domains on a blocklist or to only explicitly generate them for email address in an allow list. |
params.email.verificationRequest ? | boolean | - |
params.profile ? | Profile | If OAuth provider is used, it contains the full OAuth profile returned by your provider. |
params.user | User | AdapterUser | - |
Returns
Awaitable
<string
| boolean
>
cookies?
optional 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
{}
debug?
optional debug: boolean;
Set debug to true to enable debug messages for authentication and database operations.
- ⚠ If you added a custom AuthConfig.logger, this setting is ignored.
Default
false
Deprecated
Use logLevel: "verbose"
instead.
Inherited from
DeprecatedAuthConfig.debug
events?
optional events: {
createUser: (message) => Awaitable<void>;
linkAccount: (message) => Awaitable<void>;
session: (message) => Awaitable<void>;
signIn: (message) => Awaitable<void>;
signOut: (message) => Awaitable<void>;
updateUser: (message) => Awaitable<void>;
};
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
{}
createUser()?
optional createUser: (message) => Awaitable<void>;
Parameters
Parameter | Type |
---|---|
message | Object |
message.user | User |
Returns
Awaitable
<void
>
linkAccount()?
optional linkAccount: (message) => Awaitable<void>;
Parameters
Parameter | Type |
---|---|
message | Object |
message.account | Account |
message.profile | User | AdapterUser |
message.user | User | AdapterUser |
Returns
Awaitable
<void
>
session()?
optional session: (message) => Awaitable<void>;
The message object will contain one of these depending on if you use JWT or database persisted sessions:
token
: The JWT for this session.session
: The session object from your adapter.
Parameters
Parameter | Type |
---|---|
message | Object |
message.session | Session |
message.token | JWT |
Returns
Awaitable
<void
>
signIn()?
optional signIn: (message) => Awaitable<void>;
If using a credentials
type auth, the user is the raw response from your
credential provider.
For other providers, you’ll get the User object from your adapter, the account,
and an indicator if the user was new to your Adapter.
Parameters
Parameter | Type |
---|---|
message | Object |
message.account | null | Account |
message.isNewUser ? | boolean |
message.profile ? | Profile |
message.user | User |
Returns
Awaitable
<void
>
signOut()?
optional signOut: (message) => Awaitable<void>;
The message object will contain one of these depending on if you use JWT or database persisted sessions:
token
: The JWT for this session.session
: The session object from your adapter that is being ended.
Parameters
Parameter | Type |
---|---|
message | { session : undefined | null | void | AdapterSession ; } | { token : null | JWT ; } |
Returns
Awaitable
<void
>
updateUser()?
optional updateUser: (message) => Awaitable<void>;
Parameters
Parameter | Type |
---|---|
message | Object |
message.user | User |
Returns
Awaitable
<void
>
experimental?
optional experimental: ExperimentalOptions;
Enable/disable experimental features.
Note
Experimental features are not guaranteed to be stable and may change or be removed without notice.
jwt?
optional jwt: Partial<JWTOptions>;
JSON Web Tokens are enabled by default if you have not specified an AuthConfig.adapter. JSON Web Tokens are encrypted (JWE) by default. We recommend you keep this behaviour.
Deprecated
Inherited from
DeprecatedAuthConfig.jwt
logLevel?
optional logLevel: "error" | "warn" | "verbose" | "silent";
Set the log level for the built-in logger.
If any of the log levels are overriden in AuthConfig.logger, this setting is ignored for that level.
Default
"error"
logger?
optional logger: Partial<LoggerInstance>;
Override any of the logger levels (undefined
levels will use the built-in logger),
and intercept logs in Auth.js. You can use this option to send Auth.js logs to a third-party logging service.
Example
// /auth.ts
import log from "logging-service"
export const { handlers, auth, signIn, signOut } = 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
pages?
optional pages: 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.
Example
pages: {
signIn: '/auth/signin',
signOut: '/auth/signout',
error: '/auth/error',
verifyRequest: '/auth/verify-request',
newUser: '/auth/new-user'
}
providers
providers: Provider[];
The only required option.
The 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.
raw?
optional raw: typeof raw;
By default, the @auth/core
package returns a Response
object.
It might be easier though to not needing to re-parse the response if you are creating
a framework-specific package. This option will make the Auth.js core return
the internal response object instead.
Inherited from
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
secret?
optional secret: string | string[];
A cryptographically random string or list of strings that is used to hash tokens, seal cookies (JWT encryption by default) and generate other cryptographic keys.
You can generate a random string with our CLI: npx auth secret
or use a tool like openssl
.
If you pass an array of secrets, we will iterate over them from first-to-last, trying to unseal JWT encrypted cookies.
Note
This is useful for rotating secrets without invalidating existing sessions. The newer secret should be added to the start of the array. This will be used for all new sessions.
We support inferring up to 4 secrets from the environment variables AUTH_SECRET
, AUTH_SECRET_1
, AUTH_SECRET_2
, AUTH_SECRET_3
,
in which case, this option is optional.
session?
optional session: {
generateSessionToken: () => string;
maxAge: number;
seal: (params) => Awaitable<string>;
strategy: "jwt" | "database" | "cookie";
unseal: (params) => Awaitable<null | JWT>;
updateAge: number;
};
Configure how you want to persist your session, how often it should be updated, or in what format it should be saved.
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.
Note
this is not equivalent to the ID of the session in the database, to avoid leaking information, eg. if the database creates predictable IDs.
Default
randomUUID
or randomBytes.toHex
depending on the Node.js version
Returns
string
maxAge?
optional maxAge: number;
Either a relative time in seconds, or an absolute Date
when to expire the session.
- If a relative time is set, the session expiry is updated when the session is accessed,
but at most at the rate of
updateAge
value.
Note
This strikes a balance between updating the session too often or letting it expire mid-action while the user is interacting with the site.
- If an absolute
Date
is set, the session will expire at that time, regardless of activity.
Note
Currently, there is no way to expire a session when the browser is closed, as most browsers keep running in the background and keep the session alive indefinitely, which would give a false sense of security, as the session would still be valid if the browser is reopened. For this reason, we recommend:
- setting a short
maxAge
- using a database session strategy that you can revoke server-side
- set an absolute
Date
for the session expiry
Default
2592000 // 30 days
seal()?
optional seal: (params) => Awaitable<string>;
Seals the session payload in the cookie, to obscure the data from the client.
By default, the cookie is sealed using an encrypted JWT. It uses the A256CBC-HS512 algorithm (JWE). AuthConfig.session.secret is used to derive a suitable encryption key.
Parameters
Parameter | Type |
---|---|
params | JWTEncodeParams <JWT > |
Returns
Awaitable
<string
>
strategy?
optional strategy: "jwt" | "database" | "cookie";
Choose how you want to save the user session.
The default is "cookie"
(Previously called “jwt”, but same behavior). This saves the session information as an encrypted JWT in cookies.
Note
Even if the persisted information would exceed the 4kb cookie limit most browsers impose, Auth.js will chunk the cookie into multiple cookies to avoid this limitation.
If you use an AuthConfig.adapter however, the default is set to "database"
instead.
Note, that you can still force a JWT session by explicitly defining "jwt"
.
Learn more about the different session strategies, their advantages and disadvantages.
unseal()?
optional unseal: (params) => Awaitable<null | JWT>;
Unseals the session payload from the cookie, to read the data on the server.
By default, the cookie is sealed using an encrypted JWT. It uses the A256CBC-HS512 algorithm (JWE). AuthConfig.session.secret is used to derive the encryption key.
If you passed an array of secrets, we will iterate over them from first-to-last, trying to unseal the data.
Parameters
Parameter | Type |
---|---|
params | JWTDecodeParams |
Returns
updateAge?
optional updateAge: number;
How often the session should be updated in seconds. If set to 0
, the session is updated every time.
Default
86400 // 1 day
skipCSRFCheck?
optional skipCSRFCheck: typeof skipCSRFCheck;
Auth.js ships its own CSRF protection. You can disable this, if your framework has built-in protection. Make sure your framework covers both server and client-side.
Inherited from
IntegrationAuthConfig
.skipCSRFCheck
theme?
optional theme: Theme;
Changes the theme of built-in AuthConfig.pages.
trustHost?
optional 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
explicitly.
Make sure that your deployment platform sets the host
header safely.
Note
Auth.js will attempt to set this value automatically for some cases, eg.: if it detects a trusted platform’s environment variable, or if the host value can be inferred from the environment, instead of the incoming request.
The following conditions will enable this automatically:
AUTH_URL ?? AUTH_TRUST_HOST ?? VERCEL ?? CF_PAGES ?? NODE_ENV !== "production"
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.
IntegrationAuthConfig
These options are meant for integrators who would like to use @auth/core
as the base for their library.
If you are a developer, you likely do not need these options.
Extended by
Properties
raw?
optional raw: typeof raw;
By default, the @auth/core
package returns a Response
object.
It might be easier though to not needing to re-parse the response if you are creating
a framework-specific package. This option will make the Auth.js core return
the internal response object instead.
skipCSRFCheck?
optional skipCSRFCheck: typeof skipCSRFCheck;
Auth.js ships its own CSRF protection. You can disable this, if your framework has built-in protection. Make sure your framework covers both server and client-side.
customFetch
const customFetch: typeof customFetch;
This option allows you to override the default fetch
function used by the provider
to make requests to the provider’s OAuth endpoints directly.
Used incorrectly, it can have security implications.
It can be used to support corporate proxies, custom fetch libraries, cache discovery endpoints, add mocks for testing, logging, set custom headers/params for non-spec compliant providers, etc.
Example
import { Auth, customFetch } from "@auth/core"
import GitHub from "@auth/core/providers/github"
const dispatcher = new ProxyAgent("my.proxy.server")
function proxy(...args: Parameters<typeof fetch>): ReturnType<typeof fetch> {
return undici(args[0], { ...(args[1] ?? {}), dispatcher })
}
const response = await Auth(request, {
providers: [GitHub({ [customFetch]: proxy })]
})
See
- https://undici.nodejs.org/#/docs/api/ProxyAgent?id=example-basic-proxy-request-with-local-agent-dispatcher
- https://authjs.dev/guides/corporate-proxy
raw
const raw: typeof raw;
This option is intended for framework authors.
Auth.js returns a web standard Response by default, but if you are implementing a framework you might want to get access to the raw internal response by passing this value to AuthConfig.raw.
skipCSRFCheck
const skipCSRFCheck: typeof skipCSRFCheck;
This option is intended for framework authors.
Auth.js comes with built-in CSRF protection, but if you are implementing a framework that is already protected against CSRF attacks, you can skip this check by passing this value to AuthConfig.skipCSRFCheck.
Auth()
Auth(request, config)
Auth(request, config): Promise<ResponseInternal>
Core functionality provided by Auth.js.
Receives a standard Request and returns a Response.
Parameters
Parameter | Type |
---|---|
request | Request |
config | AuthConfig & { raw : typeof raw ; } |
Returns
Example
import { Auth } from "@auth/core"
const request = new Request("https://example.com")
const response = await Auth(request, {
providers: [Google],
secret: "...",
trustHost: true,
})
See
Auth(request, config)
Auth(request, config): Promise<Response>
Core functionality provided by Auth.js.
Receives a standard Request and returns a Response.
Parameters
Parameter | Type |
---|---|
request | Request |
config | Omit <AuthConfig , "raw" > |
Returns
Example
import { Auth } from "@auth/core"
const request = new Request("https://example.com")
const response = await Auth(request, {
providers: [Google],
secret: "...",
trustHost: true,
})
See
createActionURL()
createActionURL(
action,
protocol,
headers,
envObject,
config): URL
Parameters
Parameter | Type |
---|---|
action | AuthAction |
protocol | string |
headers | Headers |
envObject | any |
config | Pick <AuthConfig , "logger" | "basePath" > |
Returns
isAuthAction()
isAuthAction(action): action is AuthAction
Parameters
Parameter | Type |
---|---|
action | string |
Returns
action is AuthAction
setEnvDefaults()
setEnvDefaults(
envObject,
config,
suppressBasePathWarning): void
Set default env variables on the config object
Parameters
Parameter | Type | Default value |
---|---|---|
envObject | any | undefined |
config | AuthConfig | undefined |
suppressBasePathWarning | boolean | false |
Returns
void