adapters
Auth.js can be integrated with any data layer (database, ORM, or backend API, HTTP client) in order to automatically create users, handle account linking automatically, support passwordless login, and to store session information.
This module contains utility functions and types to create an Auth.js compatible adapter.
Auth.js supports 2 session strategies to persist the login state of a user.
The default is to use a cookie + JWT
based session store (strategy: "jwt"
),
but you can also use a database adapter to store the session in a database.
Before you continue, Auth.js has a list of official database adapters. If your database is listed there, you probably do not need to create your own. If you are using a data solution that cannot be integrated with an official adapter, this module will help you create a compatible adapter.
Although @auth/core
is framework/runtime agnostic, an adapter might rely on a client/ORM package,
that is not yet compatible with your framework/runtime (e.g. it might rely on Node.js APIs).
Related issues should be reported to the corresponding package maintainers.
Installationβ
- npm
- Yarn
- pnpm
npm install @auth/core
yarn add @auth/core
pnpm add @auth/core
Then, you can import this submodule from @auth/core/adapters
.
Usageβ
Each adapter method and its function signature is documented in the Adapter interface.
import { type Adapter } from "@auth/core/adapters"
// 1. Simplest form, a plain object.
export const MyAdapter: Adapter {
// implement the adapter methods here
}
// or
// 2. A function that returns an object. Official adapters use this pattern.
export function MyAdapter(config: any): Adapter {
// Instantiate a client/ORM here with the provided config, or pass it in as a parameter.
// Usually, you might already have a client instance elsewhere in your application,
// so you should only create a new instance if you need to or you don't have one.
return {
// implement the adapter methods
}
}
Then, you can pass your adapter to Auth.js as the adapter
option.
import { MyAdapter } from "./my-adapter"
const response = await Auth(..., {
adapter: MyAdapter, // 1.
// or
adapter: MyAdapter({ /* config */ }), // 2.
...
})
Note, you might be able to tweak an existing adapter to work with your data layer, instead of creating one from scratch.
import { type Adapter } from "@auth/core/adapters"
import { PrismaAdapter } from "@auth/prisma-adapter"
import { PrismaClient } from "@prisma/client"
const prisma = new PrismaClient()
const adapter: Adapter = {
...PrismaAdapter(prisma),
// Add your custom methods here
}
const request = new Request("https://example.com")
const response = await Auth(request, { adapter, ... })
Modelsβ
Auth.js can be used with any database. Models tell you what structures Auth.js expects from your database. Models will vary slightly depending on which adapter you use, but in general, will have a similar structure to the graph below. Each model can be extended with additional fields.
Auth.js / NextAuth.js uses camelCase
for its database rows while respecting the conventional snake_case
formatting for OAuth-related values. If the mixed casing is an issue for you, most adapters have a dedicated documentation section on how to force a casing convention.
Testingβ
There is a test suite available to ensure that your adapter is compatible with Auth.js.
Known issuesβ
The following are missing built-in features in Auth.js but can be solved in user land. If you would like to help implement these features, please reach out.
Token rotationβ
Auth.js currently does not support access_token
rotation out of the box.
The necessary information (refresh_token
, expiry, etc.) is being stored in the database, but the logic to rotate the token is not implemented
in the core library.
This guide should provide the necessary steps to do this in user land.
Federated logoutβ
Auth.js currently does not support federated logout out of the box. This means that even if an active session is deleted from the database, the user will still be signed in to the identity provider, they will only be signed out of the application. Eg. if you use Google as an identity provider, and you delete the session from the database, the user will still be signed in to Google, but they will be signed out of your application.
If your users might be using the application from a publicly shared computer (eg: library), you might want to implement federated logout. This guide should provide the necessary steps.
Adapterβ
An adapter is an object with function properties (methods) that read and write data from a data source. Think of these methods as a way to normalize the data layer to common interfaces that Auth.js can understand.
This is what makes Auth.js very flexible and allows it to be used with any data layer.
The adapter methods are used to perform the following operations:
- Create/update/delete a user
- Link/unlink an account to/from a user
- Handle active sessions
- Support passwordless authentication across multiple devices
If any of the methods are not implemented, but are called by Auth.js, an error will be shown to the user and the operation will fail.
Methodsβ
createAuthenticator()β
optional createAuthenticator(authenticator): Awaitable< AdapterAuthenticator >
Create a new authenticator.
If the creation fails, the adapter must throw an error.
Parametersβ
βͺ authenticator: AdapterAuthenticator
Returnsβ
Awaitable
< AdapterAuthenticator
>
createSession()β
optional createSession(session): Awaitable< AdapterSession >
Creates a session for the user and returns it.
See also Database Session management
Parametersβ
βͺ session: {
expires
: Date
;
sessionToken
: string
;
userId
: string
;
}
βͺ session.expires: Date
βͺ session.sessionToken: string
βͺ session.userId: string
Returnsβ
Awaitable
< AdapterSession
>
createUser()β
optional createUser(user): Awaitable< AdapterUser >
Creates a user in the database and returns it.
See also User management
Parametersβ
βͺ user: AdapterUser
Returnsβ
Awaitable
< AdapterUser
>
createVerificationToken()β
optional createVerificationToken(verificationToken): Awaitable< undefined | null | VerificationToken >
Creates a verification token and returns it.
See also Verification tokens
Parametersβ
βͺ verificationToken: VerificationToken
Returnsβ
Awaitable
< undefined
| null
| VerificationToken
>
deleteSession()β
optional deleteSession(sessionToken): Promise< void > | Awaitable< undefined | null | AdapterSession >
Deletes a session from the database. It is preferred that this method also returns the session that is being deleted for logging purposes.
See also Database Session management
Parametersβ
βͺ sessionToken: string
Returnsβ
Promise
< void
> | Awaitable
< undefined
| null
| AdapterSession
>
deleteUser()β
optional deleteUser(userId): Promise< void > | Awaitable< undefined | null | AdapterUser >
Parametersβ
βͺ userId: string
Returnsβ
Promise
< void
> | Awaitable
< undefined
| null
| AdapterUser
>
Todoβ
This method is currently not invoked yet.
See also User management
getAccount()β
optional getAccount(providerAccountId, provider): Awaitable< null | AdapterAccount >
Get account by provider account id and provider.
If an account is not found, the adapter must return null
.
Parametersβ
βͺ providerAccountId: string
βͺ provider: string
Returnsβ
Awaitable
< null
| AdapterAccount
>
getAuthenticator()β
optional getAuthenticator(credentialID): Awaitable< null | AdapterAuthenticator >
Returns an authenticator from its credentialID.
If an authenticator is not found, the adapter must return null
.
Parametersβ
βͺ credentialID: string
Returnsβ
Awaitable
< null
| AdapterAuthenticator
>
getSessionAndUser()β
optional getSessionAndUser(sessionToken): Awaitable< null | {
session: AdapterSession;
user: AdapterUser;
} >
Returns a session and a userfrom the database in one go.
If the database supports joins, it's recommended to reduce the number of database queries.
See also Database Session management
Parametersβ
βͺ sessionToken: string
Returnsβ
Awaitable
< null
| { session
: AdapterSession
; user
: AdapterUser
; } >
getUser()β
optional getUser(id): Awaitable< null | AdapterUser >
Returns a user from the database via the user id.
See also User management
Parametersβ
βͺ id: string
Returnsβ
Awaitable
< null
| AdapterUser
>
getUserByAccount()β
optional getUserByAccount(providerAccountId): Awaitable< null | AdapterUser >
Using the provider id and the id of the user for a specific account, get the user.
See also User management
Parametersβ
βͺ providerAccountId: Pick
< AdapterAccount
, "provider"
| "providerAccountId"
>
Returnsβ
Awaitable
< null
| AdapterUser
>
getUserByEmail()β
optional getUserByEmail(email): Awaitable< null | AdapterUser >
Returns a user from the database via the user's email address.
See also Verification tokens
Parametersβ
βͺ email: string
Returnsβ
Awaitable
< null
| AdapterUser
>
linkAccount()β
optional linkAccount(account): Promise< void > | Awaitable< undefined | null | AdapterAccount >
This method is invoked internally (but optionally can be used for manual linking). It creates an Account in the database.
See also User management
Parametersβ
βͺ account: AdapterAccount
Returnsβ
Promise
< void
> | Awaitable
< undefined
| null
| AdapterAccount
>
listAuthenticatorsByUserId()β
optional listAuthenticatorsByUserId(userId): Awaitable< AdapterAuthenticator[] >
Returns all authenticators from a user.
If a user is not found, the adapter should still return an empty array. If the retrieval fails for some other reason, the adapter must throw an error.
Parametersβ
βͺ userId: string
Returnsβ
Awaitable
< AdapterAuthenticator
[] >
unlinkAccount()β
optional unlinkAccount(providerAccountId): Promise< void > | Awaitable< undefined | AdapterAccount >
Parametersβ
βͺ providerAccountId: Pick
< AdapterAccount
, "provider"
| "providerAccountId"
>
Returnsβ
Promise
< void
> | Awaitable
< undefined
| AdapterAccount
>
Todoβ
This method is currently not invoked yet.
updateAuthenticatorCounter()β
optional updateAuthenticatorCounter(credentialID, newCounter): Awaitable< AdapterAuthenticator >
Updates an authenticator's counter.
If the update fails, the adapter must throw an error.
Parametersβ
βͺ credentialID: string
βͺ newCounter: number
Returnsβ
Awaitable
< AdapterAuthenticator
>
updateSession()β
optional updateSession(session): Awaitable< undefined | null | AdapterSession >
Updates a session in the database and returns it.
See also Database Session management
Parametersβ
βͺ session: Partial
< AdapterSession
> & Pick
< AdapterSession
, "sessionToken"
>
Returnsβ
Awaitable
< undefined
| null
| AdapterSession
>
updateUser()β
optional updateUser(user): Awaitable< AdapterUser >
Updates a user in the database and returns it.
See also User management
Parametersβ
βͺ user: Partial
< AdapterUser
> & Pick
< AdapterUser
, "id"
>
Returnsβ
Awaitable
< AdapterUser
>
useVerificationToken()β
optional useVerificationToken(params): Awaitable< null | VerificationToken >
Return verification token from the database and deletes it so it can only be used once.
See also Verification tokens
Parametersβ
βͺ params: {
identifier
: string
;
token
: string
;
}
βͺ params.identifier: string
βͺ params.token: string
Returnsβ
Awaitable
< null
| VerificationToken
>
AdapterAccountβ
An account is a connection between a user and a provider.
There are two types of accounts:
- OAuth/OIDC accounts, which are created when a user signs in with an OAuth provider.
- Email accounts, which are created when a user signs in with an Email provider.
One user can have multiple accounts.
Extendsβ
Propertiesβ
providerβ
provider: string;
Provider's id for this account. Eg.: "google"
Inherited fromβ
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
Inherited fromβ
types.Account.providerAccountId
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
Inherited fromβ
AdapterAuthenticatorβ
An authenticator represents a credential authenticator assigned to a user.
Extendsβ
Propertiesβ
counterβ
counter: number;
Number of times the authenticator has been used.
Inherited fromβ
credentialBackedUpβ
credentialBackedUp: boolean;
Whether the client authenticator backed up the credential.
Inherited fromβ
types.Authenticator.credentialBackedUp
credentialDeviceTypeβ
credentialDeviceType: string;
Device type of the authenticator.
Inherited fromβ
types.Authenticator.credentialDeviceType
credentialIDβ
credentialID: string;
Base64 encoded credential ID.
Inherited fromβ
types.Authenticator.credentialID
credentialPublicKeyβ
credentialPublicKey: string;
Base64 encoded credential public key.
Inherited fromβ
types.Authenticator.credentialPublicKey
providerAccountIdβ
providerAccountId: string;
The provider account ID connected to the authenticator.
Inherited fromβ
types.Authenticator.providerAccountId
userIdβ
userId: string;
User ID of the authenticator.
Overridesβ
transportsβ
transports?: string;
Concatenated transport flags.
Inherited fromβ
types.Authenticator.transports
AdapterSessionβ
A session holds information about a user's current signin state.
Propertiesβ
expiresβ
expires: Date;
The absolute date when the session expires.
If a session is accessed prior to its expiry date,
it will be extended based on the maxAge
option as defined in by SessionOptions.maxAge
.
It is never extended more than once in a period defined by SessionOptions.updateAge
.
If a session is accessed past its expiry date, it will be removed from the database to clean up inactive sessions.
sessionTokenβ
sessionToken: string;
A randomly generated value that is used to look up the session in the database
when using "database"
AuthConfig.strategy
option.
This value is saved in a secure, HTTP-Only cookie on the client.
userIdβ
userId: string;
Connects the active session to a user in the database
AdapterUserβ
A user represents a person who can sign in to the application. If a user does not exist yet, it will be created when they sign in for the first time, using the information (profile data) returned by the identity provider. A corresponding account is also created and linked to the user.
Extendsβ
Propertiesβ
emailβ
email: string;
The user's email address.
Overridesβ
User.email
emailVerifiedβ
emailVerified: null | Date;
Whether the user has verified their email address via an Email provider.
It is null
if the user has not signed in with the Email provider yet, or the date of the first successful signin.
idβ
id: string;
A unique identifier for the user.
Overridesβ
User.id
VerificationTokenβ
A verification token is a temporary token that is used to sign in a user via their email address. It is created when a user signs in with an Email provider. When the user clicks the link in the email, the token and email is sent back to the server where it is hashed and compared to the value in the database. If the tokens and emails match, and the token hasn't expired yet, the user is signed in. The token is then deleted from the database.
Propertiesβ
expiresβ
expires: Date;
The absolute date when the token expires.
identifierβ
identifier: string;
The user's email address.
tokenβ
token: string;
A hashed token, using the AuthConfig.secret
value.