server
Configuration and helpers for using Convex Auth on your Convex backend.
Call convexAuth to configure your authentication methods and use the helpers it returns.
Include authTables in your schema.
convexAuth()
Configure the Convex Auth library. Returns an object with
functions and auth
helper. You must export the functions
from convex/auth.ts
to make them callable:
import { convexAuth } from "@convex-dev/auth/server";
export const { auth, signIn, signOut, store } = convexAuth({
providers: [],
});
Parameters
Parameter | Type |
---|---|
|
Returns
object
An object with fields you should reexport from your
convex/auth.ts
file.
auth
Helper for configuring HTTP actions.
auth.addHttpRoutes()
Add HTTP actions for JWT verification and OAuth sign-in.
import { httpRouter } from "convex/server";
import { auth } from "./auth.js";
const http = httpRouter();
auth.addHttpRoutes(http);
export default http;
The following routes are handled always:
/.well-known/openid-configuration
/.well-known/jwks.json
The following routes are handled if OAuth is configured:
/api/auth/signin/*
/api/auth/callback/*
Parameters
Parameter | Type | Description |
---|---|---|
|
| your HTTP router |
Returns
void
signIn
Action called by the client to sign the user in.
Also used for refreshing the session.
signOut
Action called by the client to invalidate the current session.
store
Internal mutation used by the library to read and write to the database during signin and signout.
Defined in
src/server/implementation/index.ts:82 (opens in a new tab)
getAuthUserId()
Return the currently signed-in user's ID.
import { mutation } from "./_generated/server";
import { getAuthUserId } from "@convex-dev/auth/server";
export const doSomething = mutation({
args: {/* ... */},
handler: async (ctx, args) => {
const userId = await getAuthUserId(ctx);
if (userId === null) {
throw new Error("Client is not authenticated!")
}
const user = await ctx.db.get(userId);
// ...
},
});
Parameters
Parameter | Type | Description |
---|---|---|
|
| query, mutation or action |
|
| ‐ |
Returns
Promise
<null
| Id
<"users"
>>
the user ID or null
if the client isn't authenticated
Defined in
src/server/implementation/index.ts:440 (opens in a new tab)
createAccount()
Use this function from a
ConvexCredentials
provider to create an account and a user with a unique account "id" (OAuth
provider ID, email address, phone number, username etc.).
Parameters
Parameter | Type | Description |
---|---|---|
|
| ‐ |
|
| ‐ |
|
| The provider ID (like "password"), used to disambiguate accounts. It is also used to configure account secret hashing via the provider's
|
|
| ‐ |
|
| The unique external ID for the account, for example email address. |
|
| The secret credential to store for this account, if given. |
|
| The profile data to store for the user.
These must fit the |
|
| If |
|
| If |
Returns
Promise
<object
>
user ID if it successfully creates the account or throws an error.
account
user
Defined in
src/server/implementation/index.ts:458 (opens in a new tab)
retrieveAccount()
Use this function from a
ConvexCredentials
provider to retrieve a user given the account provider ID and
the provider-specific account ID.
Parameters
Parameter | Type | Description |
---|---|---|
|
| ‐ |
|
| ‐ |
|
| The provider ID (like "password"), used to disambiguate accounts. It is also used to configure account secret hashing via the provider's
|
|
| ‐ |
|
| The unique external ID for the account, for example email address. |
|
| The secret that should match the stored credential, if given. |
Returns
Promise
<object
>
the retrieved user document, or null
if there is no account
for given account ID or throws if the provided
secret does not match.
account
user
Defined in
src/server/implementation/index.ts:518 (opens in a new tab)
modifyAccountCredentials()
Use this function to modify the account credentials
from a ConvexCredentials
provider.
Parameters
Parameter | Type | Description |
---|---|---|
|
| ‐ |
|
| ‐ |
|
| The provider ID (like "password"), used to disambiguate accounts. It is also used to configure account secret hashing via the |
|
| ‐ |
|
| The unique external ID for the account, for example email address. |
|
| The new secret credential to store for this account. |
Returns
Promise
<void
>
Defined in
src/server/implementation/index.ts:558 (opens in a new tab)
invalidateSessions()
Use this function to invalidate existing sessions.
Parameters
Parameter | Type |
---|---|
|
|
|
|
|
|
|
|
Returns
Promise
<void
>
Defined in
src/server/implementation/index.ts:588 (opens in a new tab)
signInViaProvider()
Use this function from a
ConvexCredentials
provider to sign in the user via another provider (usually
for email verification on sign up or password reset).
Returns the user ID if the sign can proceed,
or null
.
Parameters
Parameter | Type |
---|---|
|
|
| |
|
|
|
|
|
|
Returns
Promise
<null
| object
>
Defined in
src/server/implementation/index.ts:610 (opens in a new tab)
getAuthSessionId()
Return the current session ID.
import { mutation } from "./_generated/server";
import { getAuthSessionId } from "@convex-dev/auth/server";
export const doSomething = mutation({
args: {/* ... */},
handler: async (ctx, args) => {
const sessionId = await getAuthSessionId(ctx);
if (sessionId === null) {
throw new Error("Client is not authenticated!")
}
const session = await ctx.db.get(sessionId);
// ...
},
});
Parameters
Parameter | Type | Description |
---|---|---|
|
| query, mutation or action |
|
| ‐ |
Returns
Promise
<null
| Id
<"authSessions"
>>
the session ID or null
if the client isn't authenticated
Defined in
src/server/implementation/sessions.ts:131 (opens in a new tab)
authTables
The table definitions required by the library.
Your schema must include these so that the indexes are set up:
import { defineSchema } from "convex/server";
import { authTables } from "@convex-dev/auth/server";
const schema = defineSchema({
...authTables,
});
export default schema;
You can inline the table definitions into your schema and extend them with additional optional and required fields. See /setup/schema for more details.
Type declaration
users
Users.
authSessions
Sessions. A single user can have multiple active sessions. See Session document lifecycle.
authAccounts
Accounts. An account corresponds to a single authentication provider. A single user can have multiple accounts linked.
authRefreshTokens
Refresh tokens. Refresh tokens are generally meant to be used once, to be exchanged for another refresh token and a JWT access token, but with a few exceptions:
- The "active refresh token" is the most recently created refresh token that has not been used yet. The parent of the active refresh token can always be used to obtain the active refresh token.
- A refresh token can be used within a 10 second window ("reuse window") to obtain a new refresh token.
- On any invalid use of a refresh token, the token itself and all its descendants are invalidated.
authVerificationCodes
Verification codes:
- OTP tokens
- magic link tokens
- OAuth codes
authVerifiers
PKCE verifiers for OAuth.
authRateLimits
Rate limits for OTP and password sign-in.
Defined in
src/server/implementation/types.ts:36 (opens in a new tab)
ConvexAuthConfig
The config for the Convex Auth library, passed to convexAuth
.
Type declaration
providers
A list of authentication provider configs.
You can import existing configs from
@auth/core/providers/<provider-name>
@convex-dev/auth/providers/<provider-name>
theme?
optional
theme:Theme
Theme used for emails. See Auth.js theme docs (opens in a new tab).
session?
Session configuration.
session.totalDurationMs?
optional
totalDurationMs:number
How long can a user session last without the user reauthenticating.
Defaults to 30 days.
session.inactiveDurationMs?
optional
inactiveDurationMs:number
How long can a user session last without the user being active.
Defaults to 30 days.
jwt?
JWT configuration.
jwt.durationMs?
optional
durationMs:number
How long is the JWT valid for after it is signed initially.
Defaults to 1 hour.
signIn?
Sign-in configuration.
signIn.maxFailedAttempsPerHour?
optional
maxFailedAttempsPerHour:number
How many times can the user fail to provide the correct credentials (password, OTP) per hour.
Defaults to 10 times per hour (that is 10 failed attempts, and then allow another one every 6 minutes).
callbacks?
callbacks.redirect()?
Control which URLs are allowed as a destination after OAuth sign-in and for magic links:
import GitHub from "@auth/core/providers/github";
import { convexAuth } from "@convex-dev/auth/server";
export const { auth, signIn, signOut, store } = convexAuth({
providers: [GitHub],
callbacks: {
async redirect({ redirectTo }) {
// Check that `redirectTo` is valid
// and return the relative or absolute URL
// to redirect to.
},
},
});
Convex Auth performs redirect only during OAuth sign-in. By default,
it redirects back to the URL specified via the SITE_URL
environment
variable. Similarly magic links link to SITE_URL
.
You can customize that behavior by providing a redirectTo
param
to the signIn
function:
signIn("google", { redirectTo: "/dashboard" })
You can even redirect to a different site.
This callback, if specified, is then called with the provided
redirectTo
param. Otherwise, only query params, relative paths
and URLs starting with SITE_URL
are allowed.
Parameters
Parameter | Type | Description |
---|---|---|
|
| ‐ |
|
| The param value passed to the |
Returns
Promise
<string
>
callbacks.createOrUpdateUser()?
Completely control account linking via this callback.
This callback is called during the sign-in process, before account creation and token generation. If specified, this callback is responsible for creating or updating the user document.
For "credentials" providers, the callback is only called
when createAccount
is called.
Parameters
Parameter | Type | Description |
---|---|---|
|
| ‐ |
|
| ‐ |
|
| If this is a sign-in to an existing account, this is the existing user ID linked to that account. |
|
| The provider type or "verification" if this callback is called after an email or phone token verification. |
| The provider used for the sign-in, or the provider tied to the account which is having the email or phone verified. | |
|
|
|
|
| The |
Returns
Promise
<GenericId
<"users"
>>
callbacks.afterUserCreatedOrUpdated()?
Perform additional writes after a user is created.
This callback is called during the sign-in process, after the user is created or updated, before account creation and token generation.
This callback is only called if createOrUpdateUser
is not specified. If createOrUpdateUser
is specified,
you can perform any additional writes in that callback.
For "credentials" providers, the callback is only called
when createAccount
is called.
Parameters
Parameter | Type | Description |
---|---|---|
|
| ‐ |
|
| ‐ |
|
| The ID of the user that is being signed in. |
|
| If this is a sign-in to an existing account, this is the existing user ID linked to that account. |
|
| The provider type or "verification" if this callback is called after an email or phone token verification. |
| The provider used for the sign-in, or the provider tied to the account which is having the email or phone verified. | |
|
|
|
|
| The |
Returns
Promise
<void
>
Defined in
src/server/types.ts:22 (opens in a new tab)
AuthProviderConfig
Same as Auth.js provider configs, but adds phone provider for verification via SMS or another phone-number-connected messaging service.
Defined in
src/server/types.ts:232 (opens in a new tab)
EmailConfig<DataModel>
Extends the standard Auth.js email provider config to allow additional checks during token verification.
Extends
EmailConfig
Properties
id
id:
string
Uniquely identifies the provider in AuthConfig.providers It's also part of the URL
Inherited from
AuthjsEmailConfig.id
Defined in
node_modules/@auth/core/providers/email.d.ts:14 (opens in a new tab)
type
See ProviderType
Inherited from
AuthjsEmailConfig.type
Defined in
node_modules/@auth/core/providers/email.d.ts:15 (opens in a new tab)
name
name:
string
The provider name used on the default sign-in page's sign-in button. For example if it's "Google", the corresponding button will say: "Sign in with Google"
Inherited from
AuthjsEmailConfig.name
Defined in
node_modules/@auth/core/providers/email.d.ts:16 (opens in a new tab)
from?
optional
from:string
Inherited from
AuthjsEmailConfig.from
Defined in
node_modules/@auth/core/providers/email.d.ts:17 (opens in a new tab)
maxAge?
optional
maxAge:number
Inherited from
AuthjsEmailConfig.maxAge
Defined in
node_modules/@auth/core/providers/email.d.ts:18 (opens in a new tab)
sendVerificationRequest()
Parameters
Parameter | Type |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Returns
Awaitable
<void
>
Inherited from
AuthjsEmailConfig.sendVerificationRequest
Defined in
node_modules/@auth/core/providers/email.d.ts:19 (opens in a new tab)
secret?
optional
secret:string
Used to hash the verification token.
Inherited from
AuthjsEmailConfig.secret
Defined in
node_modules/@auth/core/providers/email.d.ts:29 (opens in a new tab)
apiKey?
optional
apiKey:string
Used with HTTP-based email providers.
Inherited from
AuthjsEmailConfig.apiKey
Defined in
node_modules/@auth/core/providers/email.d.ts:31 (opens in a new tab)
server?
optional
server:any
Used with SMTP-based email providers.
Inherited from
AuthjsEmailConfig.server
Defined in
node_modules/@auth/core/providers/email.d.ts:33 (opens in a new tab)
generateVerificationToken()?
Returns
Awaitable
<string
>
Inherited from
AuthjsEmailConfig.generateVerificationToken
Defined in
node_modules/@auth/core/providers/email.d.ts:34 (opens in a new tab)
normalizeIdentifier()?
Parameters
Parameter | Type |
---|---|
|
|
Returns
string
Inherited from
AuthjsEmailConfig.normalizeIdentifier
Defined in
node_modules/@auth/core/providers/email.d.ts:35 (opens in a new tab)
options?
optional
options:EmailUserConfig
Inherited from
AuthjsEmailConfig.options
Defined in
node_modules/@auth/core/providers/email.d.ts:36 (opens in a new tab)
authorize()?
Before the token is verified, check other provided parameters.
Used to make sure tha OTPs are accompanied with the correct email address.
Parameters
Parameter | Type | Description |
---|---|---|
|
| The values passed to the |
|
| ‐ |
Returns
Promise
<void
>
Defined in
src/server/types.ts:256 (opens in a new tab)
EmailUserConfig<DataModel>
Configurable options for an email provider config.
Defined in
src/server/types.ts:268 (opens in a new tab)
PhoneConfig<DataModel>
Same as email provider config, but verifies phone number instead of the email address.
Properties
id
id:
string
Defined in
src/server/types.ts:279 (opens in a new tab)
type
Defined in
src/server/types.ts:280 (opens in a new tab)
maxAge
maxAge:
number
Token expiration in seconds.
Defined in
src/server/types.ts:284 (opens in a new tab)
sendVerificationRequest()
Send the phone number verification request.
Parameters
Parameter | Type |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Returns
Promise
<void
>
Defined in
src/server/types.ts:288 (opens in a new tab)
apiKey?
optional
apiKey:string
Defaults to process.env.AUTH_<PROVIDER_ID>_KEY
.
Defined in
src/server/types.ts:301 (opens in a new tab)
generateVerificationToken()?
Returns
Promise
<string
>
Defined in
src/server/types.ts:310 (opens in a new tab)
normalizeIdentifier()?
Parameters
Parameter | Type | Description |
---|---|---|
|
| Passed as |
Returns
string
The phone number used in sendVerificationRequest
.
Defined in
src/server/types.ts:316 (opens in a new tab)
authorize()?
Before the token is verified, check other provided parameters.
Used to make sure tha OTPs are accompanied with the correct phone number.
Parameters
Parameter | Type | Description |
---|---|---|
|
| The values passed to the |
|
| ‐ |
Returns
Promise
<void
>
Defined in
src/server/types.ts:324 (opens in a new tab)
options
Defined in
src/server/types.ts:331 (opens in a new tab)
PhoneUserConfig<DataModel>
Configurable options for a phone provider config.
Defined in
src/server/types.ts:337 (opens in a new tab)
ConvexCredentialsConfig
Similar to Auth.js Credentials config.
Type declaration
type
id
id:
string
Defined in
src/server/types.ts:344 (opens in a new tab)
GenericActionCtxWithAuthConfig<DataModel>
Your ActionCtx
enriched with ctx.auth.config
field with
the config passed to convexAuth
.
Type declaration
auth
auth.config
Defined in
src/server/types.ts:353 (opens in a new tab)
ConvexAuthMaterializedConfig
The config for the Convex Auth library, passed to convexAuth
,
with defaults and initialized providers.
See ConvexAuthConfig
Type declaration
providers
theme
theme:
Theme
Defined in
src/server/types.ts:364 (opens in a new tab)
AuthProviderMaterializedConfig
Materialized Auth.js provider config.