types
This module contains public types and interfaces of the core package.
Installation
npm install @auth/core
You can then import this submodule from @auth/core/types
.
Usage
Even if you don’t use TypeScript, IDEs like VSCode will pick up types to provide you with a better developer experience. While you are typing, you will get suggestions about what certain objects/functions look like, and sometimes links to documentation, examples, and other valuable resources.
Generally, you will not need to import types from this module.
Mostly when using the Auth
function and optionally the AuthConfig
interface,
everything inside there will already be typed.
Inside the Auth
function, you won’t need to use a single type from this module.
Example
import { Auth } from "@auth/core"
const request = new Request("https://example.com")
const response = await Auth(request, {
callbacks: {
jwt(): JWT { // <-- This is unnecessary!
return { foo: "bar" }
},
session(
{ session, token }: { session: Session; token: JWT } // <-- This is unnecessary!
) {
return session
},
}
})
Resources
AuthConfig
Re-exports AuthConfig
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
access_token?
optional readonly access_token: string;
Inherited from
Partial.access_token
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
- https://authjs.dev/guides/refresh-token-rotation#database-strategy
- https://www.rfc-editor.org/rfc/rfc6749#section-5.1
expires_in?
optional readonly expires_in: number;
Inherited from
Partial.expires_in
id_token?
optional readonly id_token: string;
Inherited from
Partial.id_token
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
refresh_token?
optional readonly refresh_token: string;
Inherited from
Partial.refresh_token
scope?
optional readonly scope: string;
Inherited from
Partial.scope
token_type?
optional readonly token_type: "bearer" | "dpop" | Lowercase<string>;
NOTE: because the value is case insensitive it is always returned lowercased
Inherited from
Partial.token_type
type
type: ProviderType;
Provider’s type for this account
userId?
optional userId: string;
id of the user this account belongs to
See
https://authjs.dev/reference/core/adapters#adapteruser
Authenticator
A webauthn authenticator. Represents an entity capable of authenticating the account it references, and contains the auhtenticator’s credentials and related information.
See
https://www.w3.org/TR/webauthn/#authenticator
Extended by
Properties
counter
counter: number;
Number of times the authenticator has been used.
credentialBackedUp
credentialBackedUp: boolean;
Whether the client authenticator backed up the credential.
credentialDeviceType
credentialDeviceType: string;
Device type of the authenticator.
credentialID
credentialID: string;
Base64 encoded credential ID.
credentialPublicKey
credentialPublicKey: string;
Base64 encoded credential public key.
providerAccountId
providerAccountId: string;
The provider account ID connected to the authenticator.
transports?
optional transports: string;
Concatenated transport flags.
userId?
optional userId: string;
ID of the user this authenticator belongs to.
CallbacksOptions<P, A>
Override the default session creation flow of Auth.js
Type parameters
Type parameter | Value |
---|---|
P | Profile |
A | Account |
Properties
jwt()
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 | A | 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 ? | P | 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()
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()
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()
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 | A | - |
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 ? | P | If OAuth provider is used, it contains the full OAuth profile returned by your provider. |
params.user | User | AdapterUser | - |
Returns
Awaitable
<string
| boolean
>
CookieOption
Properties
name
name: string;
options
options: CookieSerializeOptions;
CookiesOptions
Properties
callbackUrl
callbackUrl: Partial<CookieOption>;
csrfToken
csrfToken: Partial<CookieOption>;
nonce
nonce: Partial<CookieOption>;
pkceCodeVerifier
pkceCodeVerifier: Partial<CookieOption>;
sessionToken
sessionToken: Partial<CookieOption>;
state
state: Partial<CookieOption>;
webauthnChallenge
webauthnChallenge: Partial<CookieOption>;
DefaultSession
Extended by
Properties
expires
expires: string;
user?
optional user: User;
EventCallbacks
The various event callbacks you can register for from next-auth
Properties
createUser()
createUser: (message) => Awaitable<void>;
Parameters
Parameter | Type |
---|---|
message | Object |
message.user | User |
Returns
Awaitable
<void
>
linkAccount()
linkAccount: (message) => Awaitable<void>;
Parameters
Parameter | Type |
---|---|
message | Object |
message.account | Account |
message.profile | User | AdapterUser |
message.user | User | AdapterUser |
Returns
Awaitable
<void
>
session()
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()
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()
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 : void | Awaitable <undefined | null | AdapterSession >; } | { token : Awaitable <null | JWT >; } |
Returns
Awaitable
<void
>
updateUser()
updateUser: (message) => Awaitable<void>;
Parameters
Parameter | Type |
---|---|
message | Object |
message.user | User |
Returns
Awaitable
<void
>
LoggerInstance
Override any of the methods, and the rest will use the default logger.
Extends
Record
<string
,Function
>
Properties
debug()
debug: (message, metadata?) => void;
Parameters
Parameter | Type |
---|---|
message | string |
metadata ? | unknown |
Returns
void
error()
error: (error) => void;
Parameters
Parameter | Type |
---|---|
error | Error |
Returns
void
warn()
warn: (code) => void;
Parameters
Parameter | Type |
---|---|
code | WarningCode |
Returns
void
PagesOptions
Properties
error
error: string;
The path to the error page.
The optional “error” query parameter is set to one of the available values.
Default
"/error"
newUser
newUser: string;
If set, new users will be directed here on first sign in
signIn
signIn: string;
The path to the sign in page.
The optional “error” query parameter is set to one of the available values.
Default
"/signin"
signOut
signOut: string;
verifyRequest
verifyRequest: string;
Profile
The user info returned from your OAuth provider.
See
https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims
Indexable
[claim
: string
]: unknown
Properties
address?
optional address: null | {
country: null | string;
formatted: null | string;
locality: null | string;
postal_code: null | string;
region: null | string;
street_address: null | string;
};
birthdate?
optional birthdate: null | string;
email?
optional email: null | string;
email_verified?
optional email_verified: null | boolean;
family_name?
optional family_name: null | string;
gender?
optional gender: null | string;
given_name?
optional given_name: null | string;
id?
optional id: null | string;
locale?
optional locale: null | string;
middle_name?
optional middle_name: null | string;
name?
optional name: null | string;
nickname?
optional nickname: null | string;
phone_number?
optional phone_number: null | string;
picture?
optional picture: any;
preferred_username?
optional preferred_username: null | string;
profile?
optional profile: null | string;
sub?
optional sub: null | string;
updated_at?
optional updated_at: null | string | number | Date;
website?
optional website: null | string;
zoneinfo?
optional zoneinfo: null | string;
PublicProvider
Properties
callbackUrl
callbackUrl: string;
id
id: string;
name
name: string;
signinUrl
signinUrl: string;
type
type: string;
ResponseInternal<Body>
Type parameters
Type parameter | Value |
---|---|
Body extends string | Record <string , any > | any [] | null | any |
Properties
body?
optional body: Body;
cookies?
optional cookies: Cookie[];
headers?
optional headers: HeadersInit;
redirect?
optional redirect: string;
status?
optional status: number;
Session
The active session of the logged in user.
Extends
Properties
expires
expires: string;
Inherited from
user?
optional user: User;
Inherited from
Theme
Change the theme of the built-in pages.
Properties
brandColor?
optional brandColor: string;
buttonText?
optional buttonText: string;
colorScheme?
optional colorScheme: "auto" | "dark" | "light";
logo?
optional logo: string;
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.
Extended by
Properties
email?
optional email: null | string;
id?
optional id: string;
image?
optional image: null | string;
name?
optional name: null | string;
AuthAction
type AuthAction:
| "callback"
| "csrf"
| "error"
| "providers"
| "session"
| "signin"
| "signout"
| "verify-request"
| "webauthn-options";
Supported actions by Auth.js. Each action map to a REST API endpoint.
Some actions have a GET
and POST
variant, depending on if the action
changes the state of the server.
"callback"
:GET
: Handles the callback from an OAuth provider.POST
: Handles the callback from a Credentials provider.
"csrf"
: Returns the raw CSRF token, which is saved in a cookie (encrypted). It is used for CSRF protection, implementing the double submit cookie technique.
Some frameworks have built-in CSRF protection and can therefore disable this action. In this case, the corresponding endpoint will return a 404 response. Read more at skipCSRFCheck
.
⚠ We don’t recommend manually disabling CSRF protection, unless you know what you’re doing.
"error"
: Renders the built-in error page."providers"
: Returns a client-safe list of all configured providers."session"
:- **
GET**
: Returns the user’s session if it exists, otherwisenull
. - **
POST**
: Updates the user’s session and returns the updated session.
- **
"signin"
:GET
: Renders the built-in sign-in page.POST
: Initiates the sign-in flow.
"signout"
:GET
: Renders the built-in sign-out page.POST
: Initiates the sign-out flow. This will invalidate the user’s session (deleting the cookie, and if there is a session in the database, it will be deleted as well).
"verify-request"
: Renders the built-in verification request page."webauthn-options"
:GET
: Returns the options for the WebAuthn authentication and registration flows.
Awaitable<T>
type Awaitable<T>: T | PromiseLike<T>;
Type parameters
Type parameter |
---|
T |
Awaited<T>
type Awaited<T>: T extends Promise<infer U> ? U : T;
Type parameters
Type parameter |
---|
T |
ErrorPageParam
type ErrorPageParam: "Configuration" | "AccessDenied" | "Verification";
TODO: Check if all these are used/correct
EventType
type EventType: keyof EventCallbacks;
SemverString
type SemverString: v${number} | v${number}.${number} | v${number}.${number}.${number};
SignInPageErrorParam
type SignInPageErrorParam:
| "Signin"
| "OAuthSignin"
| "OAuthCallbackError"
| "OAuthCreateAccount"
| "EmailCreateAccount"
| "Callback"
| "OAuthAccountNotLinked"
| "EmailSignin"
| "CredentialsSignin"
| "SessionRequired";
TODO: Check if all these are used/correct
TokenSet
type TokenSet: Partial<OAuth2TokenEndpointResponse | OpenIDTokenEndpointResponse> & {
expires_at: number;
};
Different tokens returned by OAuth Providers. Some of them are available with different casing, but they refer to the same value.
Type declaration
expires_at?
optional expires_at: number;
Date of when the access_token
expires in seconds.
This value is calculated from the expires_in
value.