### Install Convex Auth NPM Packages Source: https://labs.convex.dev/auth/setup Install the necessary Convex Auth library and its core dependency. This command also installs `@auth/core` for provider configuration. ```bash npm install @convex-dev/auth @auth/core@0.37.0 ``` -------------------------------- ### Password Provider Initialization Source: https://labs.convex.dev/auth/api_reference/providers/Password How to initialize the Password provider within your Convex Auth setup. ```APIDOC ## Password() Email and password authentication provider. Passwords are by default hashed using Scrypt from Lucia. You can customize the hashing via the `crypto` option. Email verification is not required unless you pass an email provider to the `verify` option. ### Parameters - `config` (PasswordConfig) - Configuration object for the Password provider. ### Returns ConvexCredentialsConfig ### Defined in src/providers/Password.ts:115 ``` ```javascript import Password from "@convex-dev/auth/providers/Password"; import { convexAuth } from "@convex-dev/auth/server"; export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({ providers: [Password], }); ``` -------------------------------- ### Create New Convex Project Source: https://labs.convex.dev/auth/setup Use this command to start a new project with Convex and Convex Auth. Choose 'React (Vite)' and 'Convex Auth' when prompted. ```bash npm create convex@latest ``` -------------------------------- ### Example GitHub Callback URL Source: https://labs.convex.dev/auth/config/oauth This is an example of a callback URL for GitHub OAuth, which should be configured in your third-party developer account. The origin is your Convex backend's HTTP Actions URL. ```text https://fast-horse-123.convex.site/api/auth/callback/github ``` -------------------------------- ### Configure Convex Auth Providers Source: https://labs.convex.dev/auth/setup/manual Set up the authentication providers in your Convex project's auth.config.ts file. This example uses the CONVEX_SITE_URL environment variable for the domain. ```typescript export default { providers: [ { domain: process.env.CONVEX_SITE_URL, applicationID: "convex", }, ], }; ``` -------------------------------- ### Initialize Convex Auth with Password Provider Source: https://labs.convex.dev/auth/api_reference/providers/Password Set up Convex Auth by importing and configuring the Password provider. This snippet shows the basic setup for integrating password-based authentication. ```typescript import Password from "@convex-dev/auth/providers/Password"; import { convexAuth } from "@convex-dev/auth/server"; export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({ providers: [Password], }); ``` -------------------------------- ### Convex Auth Provider Setup Source: https://labs.convex.dev/auth/api_reference/react Wrap your application with `ConvexAuthProvider` to enable authentication features. This component requires your `ConvexReactClient` instance and can optionally accept custom storage or URL handling configurations. ```javascript import { ConvexAuthProvider } from "@convex-dev/auth/react"; import { ConvexReactClient } from "convex/react"; import { ReactNode } from "react"; const convex = new ConvexReactClient(/* ... */); function RootComponent({ children }: { children: ReactNode }) { return {children}; } ``` -------------------------------- ### Configure Convex Auth Source: https://labs.convex.dev/auth/api_reference/server Configure the Convex Auth library by providing an array of authentication providers. This setup returns essential functions and an `auth` helper that must be re-exported. ```typescript import { convexAuth } from "@convex-dev/auth/server"; export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({ providers: [], }); ``` -------------------------------- ### Phone Provider Configuration Source: https://labs.convex.dev/auth/api_reference/providers/Phone Configure the Phone provider for authentication. This setup simplifies the creation of phone providers and includes a default check to ensure the 'phone' field used during token verification matches the 'phone' provided during the initial sign-in. ```APIDOC ## Phone() ### Description Phone providers send a token to the user's phone number for sign-in. When you use this function to create your config, it checks that there is a `phone` field during token verification that matches the `phone` used during the initial `signIn` call. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters Parameter| Type ---|--- `config`| `PhoneUserConfig` & `Pick`<`PhoneConfig`<`GenericDataModel`>, `"sendVerificationRequest"`> ### Returns `PhoneConfig`<`DataModel`> ### Request Example ```json { "example": "No request body example available for this function" } ``` ### Response #### Success Response (200) - None explicitly defined, returns `PhoneConfig`<`DataModel`> #### Response Example ```json { "example": "No response body example available for this function" } ``` ### Defined in src/providers/Phone.ts:23 ``` -------------------------------- ### Anonymous Provider Configuration Source: https://labs.convex.dev/auth/api_reference/providers/Anonymous This snippet demonstrates how to import and configure the Anonymous provider within your Convex Auth setup. ```APIDOC ## POST /api/auth/anonymous ### Description Configures the Anonymous authentication provider for Convex Auth. ### Method POST ### Endpoint /api/auth/anonymous ### Parameters #### Request Body - **config** (AnonymousConfig) - Required - Configuration options for the Anonymous provider. ### Request Example ```json { "config": { "id": "optional_anonymous_id", "profile": (params, ctx) => { /* custom profile logic */ } } } ``` ### Response #### Success Response (200) - **auth** (Function) - The authenticated Convex Auth object. - **signIn** (Function) - Function to sign in a user. - **signOut** (Function) - Function to sign out a user. - **store** (Function) - Function to store user data. - **isAuthenticated** (Function) - Function to check if a user is authenticated. #### Response Example ```json { "auth": "", "signIn": "", "signOut": "", "store": "", "isAuthenticated": "" } ``` ``` -------------------------------- ### Configure GitHub Provider in convex/auth.ts Source: https://labs.convex.dev/auth/config/oauth/github Integrate the GitHub OAuth provider into your Convex authentication setup by adding it to the `providers` array in `convex/auth.ts`. This configuration reads the environment variables set previously. ```typescript import GitHub from "@auth/core/providers/github"; import { convexAuth } from "@convex-dev/auth/server"; export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({ providers: [GitHub], }); ``` -------------------------------- ### Customize GitHub Profile with Custom Field Source: https://labs.convex.dev/auth/config/oauth This example shows how to add a `githubId` field to the user profile by customizing the `profile` method for the GitHub OAuth provider. Remember to update your Convex schema to include this new field. ```typescript import GitHub from "@auth/core/providers/github"; import { convexAuth } from "@convex-dev/auth/server"; export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({ providers: [ GitHub({ profile(githubProfile, tokens) { return { id: githubProfile.id, name: githubProfile.name, email: githubProfile.email, image: githubProfile.picture, githubId: githubProfile.id, }; }, }), ], }); ``` -------------------------------- ### Implement Email Sign-in Form with Convex Auth Source: https://labs.convex.dev/auth/config/otps Use this React component to create a two-step sign-in form. The first step collects an email address to send a verification code, and the second step collects the code itself. Ensure the 'resend-otp' provider is configured in your Convex Auth setup. ```tsx import { useAuthActions } from "@convex-dev/auth/react"; import { useState } from "react"; export function SignIn() { const { signIn } = useAuthActions(); const [step, setStep] = useState<"signIn" | { email: string }>("signIn"); return step === "signIn" ? (
{ event.preventDefault(); const formData = new FormData(event.currentTarget); void signIn("resend-otp", formData).then(() => setStep({ email: formData.get("email") as string }) ); }} >
) : (
{ event.preventDefault(); const formData = new FormData(event.currentTarget); void signIn("resend-otp", formData); }} >
); } ``` -------------------------------- ### Run Convex Auth Initialization Source: https://labs.convex.dev/auth/setup Execute this command to automatically set up your project for authentication using the Convex Auth library. ```bash npx @convex-dev/auth ``` -------------------------------- ### Initialize Production Environment Variables Source: https://labs.convex.dev/auth/production Use this command to set up the minimal required environment variables for your production Convex deployment. Run this from your project directory. ```bash npx @convex-dev/auth --prod ``` -------------------------------- ### ConvexAuthNextjsMiddleware Implementation Source: https://labs.convex.dev/auth/api_reference/nextjs/server Implement convexAuthNextjsMiddleware in your middleware.ts to protect routes. This example redirects unauthenticated users to '/login'. ```typescript import { convexAuthNextjsMiddleware } from "convex-auth/nextjs/server"; import { nextjsMiddlewareRedirect } from "convex-auth/nextjs/server"; export default convexAuthNextjsMiddleware(async (request, event, convexAuth) => { if (!(await convexAuth.isAuthenticated())) { return nextjsMiddlewareRedirect(request, "/login"); } }); ``` -------------------------------- ### Configure Resend Provider in convex/auth.ts Source: https://labs.convex.dev/auth/config/email Integrate the Resend email provider into your Convex authentication setup. Ensure you import necessary modules from Auth.js and Convex Auth. ```typescript import Resend from "@auth/core/providers/resend"; import { convexAuth } from "@convex-dev/auth/server"; export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({ providers: [Resend], }); ``` -------------------------------- ### Get Auth Token with useAuthToken Hook Source: https://labs.convex.dev/auth/api_reference/react Use the useAuthToken hook to retrieve the JWT token for authenticating Convex HTTP actions. The token should not be shared with other servers. ```javascript import { useAuthToken } from "@convex-dev/auth/react"; function SomeComponent() { const token = useAuthToken(); const onClick = async () => { await fetch(`${CONVEX_SITE_URL}/someEndpoint`, { headers: { Authorization: `Bearer ${token}`, }, }); }; // ... } ``` -------------------------------- ### Validate Email Format with Zod Source: https://labs.convex.dev/auth/config/passwords Use the `profile` option with `Password` to invoke email validation. This example uses Zod to ensure the email format is valid before proceeding. ```typescript import { ConvexError } from "convex/values"; import { Password } from "@convex-dev/auth/providers/Password"; import { z } from "zod"; const ParamsSchema = z.object({ email: z.string().email(), }); export default Password({ profile(params) { const { error, data } = ParamsSchema.safeParse(params); if (error) { throw new ConvexError(error.format()); } return { email: data.email }; }, }); ``` -------------------------------- ### createAccount() Source: https://labs.convex.dev/auth/api_reference/server Creates a new user account with the provided profile information and links it to an authentication provider. ```APIDOC ## createAccount() ### Description Creates a new user account with the provided profile information and links it to an authentication provider. ### Method Not specified (assumed to be an action or mutation) ### Endpoint Not specified ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ctx** (GenericActionCtx) - Required - The Convex context. - **args** (object) - Required - - **provider** (string) - Required - The provider ID (like "password"), used to disambiguate accounts. It is also used to configure account secret hashing via the provider's `crypto` option. - **account** (object) - Required - - **id** (string) - Required - The unique external ID for the account, for example email address. - **secret**? (string) - Optional - The secret credential to store for this account, if given. - **profile** (WithoutSystemFields>) - Required - The profile data to store for the user. These must fit the `users` table schema. - **shouldLinkViaEmail**? (boolean) - Optional - If `true`, the account will be linked to an existing user with the same verified email address. This is only safe if the returned account's email is verified before the user is allowed to sign in with it. - **shouldLinkViaPhone**? (boolean) - Optional - If `true`, the account will be linked to an existing user with the same verified phone number. This is only safe if the returned account's phone is verified before the user is allowed to sign in with it. ### Request Example ```json { "ctx": ">", "args": { "provider": "password", "account": { "id": "user@example.com", "secret": "hashed_password" }, "profile": { "name": "John Doe" }, "shouldLinkViaEmail": true } } ``` ### Response #### Success Response (200) - **userId** (string) - The ID of the created user. - **account** (object) - Details about the created account. - **user** (object) - Details about the created user. #### Response Example ```json { "userId": "user123", "account": { ... }, "user": { ... } } ``` ### Error Handling Throws an error if account creation fails. ``` -------------------------------- ### ConvexAuth Configuration Source: https://labs.convex.dev/auth/api_reference/server Configure the Convex Auth library by calling `convexAuth` and exporting the returned functions. Include `authTables` in your schema. ```APIDOC ## convexAuth() Configure the Convex Auth library. Returns an object with functions and `auth` helper. ### Parameters Parameter| Type ---|--- `config_`| `ConvexAuthConfig` ### 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. ```typescript 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 ---|---|--- `http`| `HttpRouter`| 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. #### isAuthenticated Utility function for frameworks to use to get the current auth state based on credentials that they've supplied separately. ### Defined in src/server/implementation/index.ts:103 (opens in a new tab) ``` -------------------------------- ### ConvexAuthActionsContext signIn Method Source: https://labs.convex.dev/auth/api_reference/react Use the `signIn` method from the `ConvexAuthActionsContext` to initiate the sign-in process with a specified provider. It accepts provider details and optional parameters, returning a promise that indicates if the sign-in was immediate. ```typescript signIn(provider: string, params?: FormData | Record & object): Promise<{ signingIn: boolean }> ``` -------------------------------- ### Configure Authentication Cookie Expiration in Next.js Source: https://labs.convex.dev/auth/authz/nextjs Set the expiration time for the authentication cookie using the `cookieConfig` option in `convexAuthNextjsMiddleware`. This example sets the cookie to expire in 30 days. ```typescript export default convexAuthNextjsMiddleware( (request, { convexAuth }) => { // ... }, { cookieConfig: { maxAge: 60 * 60 * 24 * 30 } }, ); // 30 days ``` -------------------------------- ### Configure Convex Auth with Password Provider Source: https://labs.convex.dev/auth/config/passwords Integrates the custom ResendOTP provider into the Convex Auth configuration. This sets up the authentication system to use the password flow with email verification. ```typescript import { Password } from "@convex-dev/auth/providers/Password"; import { convexAuth } from "@convex-dev/auth/server"; import { ResendOTP } from "./ResendOTP"; export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({ providers: [Password({ verify: ResendOTP })], }); ``` -------------------------------- ### Get Auth Session ID in Convex Source: https://labs.convex.dev/auth/api_reference/server Retrieves the current authentication session ID from the Convex context. Throws an error if the client is not authenticated. Requires the `getAuthSessionId` function from `@convex-dev/auth/server`. ```typescript 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); // ... }, }); ``` -------------------------------- ### Get Authenticated User ID Source: https://labs.convex.dev/auth/api_reference/server Retrieve the ID of the currently signed-in user within a Convex mutation or action. Throws an error if the client is not authenticated. Requires the `ctx` object. ```typescript 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); // ... }, }); ``` -------------------------------- ### callbacks.beforeSessionCreation() Source: https://labs.convex.dev/auth/api_reference/server Called before a new session is created for a user. This callback runs during every sign-in flow right before the session is persisted. Throw an error to reject the sign-in. ```APIDOC ## POST /callbacks/beforeSessionCreation ### Description Callback executed before a new user session is created. Useful for implementing checks like user bans. ### Method POST ### Endpoint /callbacks/beforeSessionCreation ### Parameters #### Request Body - **args** (object) - Required - Arguments for the callback. - **userId** (GenericId<"users">) - Required - The ID of the user about to be signed in. ### Request Example ```json { "args": { "userId": "user_abc123" } } ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful execution (no specific return value needed). #### Response Example ```json { "message": "Session creation check passed." } ``` ``` -------------------------------- ### Configure Anonymous Provider with Convex Auth Source: https://labs.convex.dev/auth/api_reference/providers/Anonymous Use this snippet to set up the Anonymous authentication provider. It requires importing the Anonymous provider and initializing convexAuth with it. ```typescript import { Anonymous } from "@convex-dev/auth/providers/Anonymous"; import { convexAuth } from "@convex-dev/auth/server"; export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({ providers: [Anonymous], }); ``` -------------------------------- ### Set GitHub Environment Variables Source: https://labs.convex.dev/auth/config/oauth Configure your GitHub OAuth client ID and secret as environment variables on your Convex backend. Replace 'yourgithubclientid' and 'yourgithubsecret' with your actual credentials. ```bash npx convex env set AUTH_GITHUB_ID yourgithubclientid npx convex env set AUTH_GITHUB_SECRET yourgithubsecret ``` -------------------------------- ### Use Auth Actions Hook Source: https://labs.convex.dev/auth/api_reference/react Use the `useAuthActions` hook to get access to the `signIn` and `signOut` methods. This hook is essential for managing user authentication state within your React components. ```javascript import { useAuthActions } from "@convex-dev/auth/react"; function SomeComponent() { const { signIn, signOut } = useAuthActions(); // ... } ``` -------------------------------- ### Set Resend API Key Environment Variable Source: https://labs.convex.dev/auth/config/email Configure the Resend API key for your Convex backend using the Convex CLI. Replace 'yourresendkey' with your actual API key. ```bash npx convex env set AUTH_RESEND_KEY yourresendkey ``` -------------------------------- ### Custom Resend OTP Provider Configuration Source: https://labs.convex.dev/auth/config/otps Implement a custom email provider for sending One-Time Passwords (OTPs) using Resend and OsloJS crypto. Ensure you have installed the 'resend' and '@oslojs/crypto' packages. ```typescript import { Email } from "@convex-dev/auth/providers/Email"; import { Resend as ResendAPI } from "resend"; import { RandomReader, generateRandomString } from "@oslojs/crypto/random"; export const ResendOTP = Email({ id: "resend-otp", apiKey: process.env.AUTH_RESEND_KEY, maxAge: 60 * 15, // 15 minutes async generateVerificationToken() { const random: RandomReader = { read(bytes) { crypto.getRandomValues(bytes); }, }; const alphabet = "0123456789"; const length = 8; return generateRandomString(random, alphabet, length); }, async sendVerificationRequest({ identifier: email, provider, token }) { const resend = new ResendAPI(provider.apiKey); const { error } = await resend.emails.send({ from: "My App ", to: [email], subject: `Sign in to My App`, text: "Your code is " + token, }); if (error) { throw new Error(JSON.stringify(error)); } }, }); ``` -------------------------------- ### Configure Apple Provider in auth.ts Source: https://labs.convex.dev/auth/config/oauth/apple Add the Apple provider to your Convex authentication configuration. This setup handles cases where the user's name is shared, ensuring it's added to the user profile. ```typescript import Apple from "@auth/core/providers/apple"; import { convexAuth } from "@convex-dev/auth/server"; export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({ providers: [ Apple({ profile: (appleInfo) => { const name = appleInfo.user ? `${appleInfo.user.name.firstName} ${appleInfo.user.name.lastName}` : undefined; // Apple's built-in profile callback returns `image: null`, so omit it here. return { id: appleInfo.sub, name: name, email: appleInfo.email, }; }, }), ], }); ``` -------------------------------- ### ConvexAuthNextjsServerProvider Configuration Source: https://labs.convex.dev/auth/api_reference/nextjs/server Wrap your root layout with ConvexAuthNextjsProvider to enable Convex Auth. Customize the API route, storage method, and storage namespace. ```typescript import { ConvexAuthNextjsServerProvider } from "convex-auth/nextjs/server"; export default function RootLayout({ children }) { return ( {children} ); } ``` -------------------------------- ### Prevent Sign-in Based on User Status Source: https://labs.convex.dev/auth/api_reference/server Use the `beforeSessionCreation` callback to enforce policies before a new session is created. Throw an error within this callback to reject the sign-in attempt, for example, if a user is banned. ```typescript callbacks: { async beforeSessionCreation(ctx, { userId }) { const user = await ctx.db.get(userId); if (user?.banned) { throw new Error("Account is banned"); } }, } ``` -------------------------------- ### Implement Custom User Creation and Account Linking Source: https://labs.convex.dev/auth/advanced Provide a `createOrUpdateUser` callback to implement custom logic for user creation and account linking, handling existing users or creating new ones. ```typescript import GitHub from "@auth/core/providers/github"; import Password from "@convex-dev/auth/providers/Password"; import { MutationCtx } from "./_generated/server"; export const { auth, signIn, signOut, store, isAuthenticated } = { providers: [GitHub, Password], callbacks: { // `args.type` is one of "oauth" | "email" | "phone" | "credentials" | "verification" // `args.provider` is the currently used provider config async createOrUpdateUser(ctx: MutationCtx, args) { if (args.existingUserId) { // Optionally merge updated fields into the existing user object here return args.existingUserId; } // Implement your own account linking logic: const existingUser = await findUserByEmail(ctx, args.profile.email); if (existingUser) return existingUser._id; // Implement your own user creation: return ctx.db.insert("users", { /* ... */ }); }, }, }; ``` -------------------------------- ### callbacks.redirect() Source: https://labs.convex.dev/auth/api_reference/server Controls which URLs are allowed as a destination after OAuth sign-in and for magic links. By default, it redirects back to the SITE_URL environment variable. You can customize this behavior by providing a `redirectTo` parameter to the `signIn` function. ```APIDOC ## POST /callbacks/redirect ### Description Controls which URLs are allowed as a destination after OAuth sign-in and for magic links. ### Method POST ### Endpoint /callbacks/redirect ### Parameters #### Query Parameters - **redirectTo** (string) - Optional - The relative or absolute URL to redirect to. If not provided, defaults to SITE_URL. ### Request Example ```json { "redirectTo": "/dashboard" } ``` ### Response #### Success Response (200) - **redirectUrl** (string) - The URL to redirect to. #### Response Example ```json { "redirectUrl": "https://your-site.com/dashboard" } ``` ``` -------------------------------- ### Initialize ConvexAuthNextjsProvider in Next.js Source: https://labs.convex.dev/auth/api_reference/nextjs Replace your ConvexProvider with ConvexAuthNextjsProvider in a Client Component to enable authentication in your Next.js app. Ensure NEXT_PUBLIC_CONVEX_URL is set in your environment variables. ```javascript "use client"; import { ConvexAuthNextjsProvider } from "@convex-dev/auth/nextjs"; import { ConvexReactClient } from "convex/react"; import { ReactNode } from "react"; const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!); export default function ConvexClientProvider({ children, }: { children: ReactNode; }) { return ( {children} ); } ``` -------------------------------- ### Get current session ID in Convex functions Source: https://labs.convex.dev/auth/authz Use the `getAuthSessionId` helper function from `@convex-dev/auth/server` to retrieve the ID of the current authentication session within Convex backend functions. It returns the session document ID or null if not authenticated. ```typescript import { getAuthSessionId } from "@convex-dev/auth/server"; import { query } from "./_generated/server"; export const currentSession = query({ args: {}, handler: async (ctx) => { const sessionId = await getAuthSessionId(ctx); if (sessionId === null) { return null; } return await ctx.db.get(sessionId); }, }); ``` -------------------------------- ### Set SITE_URL Environment Variable Source: https://labs.convex.dev/auth/setup/manual Configure the SITE_URL environment variable for OAuth redirects and magic links. This is essential for local development. ```bash npx convex env set SITE_URL http://localhost:5173 ``` -------------------------------- ### Get currently signed-in user ID in Convex functions Source: https://labs.convex.dev/auth/authz Use the `getAuthUserId` helper function from `@convex-dev/auth/server` to retrieve the ID of the currently authenticated user within Convex backend functions. It returns the user's document ID or null if not authenticated. ```typescript import { getAuthUserId } from "@convex-dev/auth/server"; import { query } from "./_generated/server"; export const currentUser = query({ args: {}, handler: async (ctx) => { const userId = await getAuthUserId(ctx); if (userId === null) { return null; } return await ctx.db.get(userId); }, }); ``` -------------------------------- ### Configure Email Provider with Magic Link Behavior Source: https://labs.convex.dev/auth/api_reference/providers/Email Use this configuration to enable magic link behavior for email sign-in, where only the token is required. Ensure the token has sufficient entropy for security. ```javascript import Email from "@convex-dev/auth/providers/Email"; import { convexAuth } from "@convex-dev/auth/server"; export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({ providers: [ Email({ authorize: undefined }), ], }); ``` -------------------------------- ### ConvexAuthNextjsServerProvider Source: https://labs.convex.dev/auth/api_reference/nextjs/server Wrap your application with this provider in your root `layout.tsx` to enable Convex Auth functionality for server components. ```APIDOC ## ConvexAuthNextjsServerProvider() ### Description Wrap your app with this provider in your root `layout.tsx`. ### Parameters #### Path Parameters - **props** (object) - Required - - **props.apiRoute** (string) - Optional - You can customize the route path that handles authentication actions via this prop and the `apiRoute` option to `convexAuthNextjsMiddleWare`.Defaults to `/api/auth`. - **props.storage** (string) - Optional - Choose how the auth information will be stored on the client.Defaults to `"localStorage"`.If you choose `"inMemory"`, different browser tabs will not have a synchronized authentication state. Possible values: `"localStorage"`, `"inMemory"`. - **props.storageNamespace** (string) - Optional - Optional namespace for keys used to store tokens. The keys determine whether the tokens are shared or not.Any non-alphanumeric characters will be ignored.Defaults to `process.env.NEXT_PUBLIC_CONVEX_URL`. - **props.shouldHandleCode** (boolean | () => boolean) - Optional - Callback to determine whether Convex Auth should handle the code parameter for a given request. If not provided, Convex Auth will handle all code parameters. If provided, Convex Auth will only handle code parameters when the callback returns true. - **props.verbose** (boolean) - Optional - Turn on debugging logs. - **props.children** (ReactNode) - Required - Children components can call Convex hooks and useAuthActions. ### Returns `Promise` ### Defined in src/nextjs/server/index.tsx:30 ``` -------------------------------- ### createAccount() Source: https://labs.convex.dev/auth/api_reference/server 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.). ```APIDOC ## 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.). ``` -------------------------------- ### ConvexAuthProvider() Source: https://labs.convex.dev/auth/api_reference/react Component to wrap your application, enabling authentication features. It requires a `ConvexReactClient` and optionally accepts custom storage and configuration options. ```APIDOC ## ConvexAuthProvider() ### Description Replace your `ConvexProvider` with this component to enable authentication. ### Usage ```javascript import { ConvexAuthProvider } from "@convex-dev/auth/react"; import { ConvexReactClient } from "convex/react"; import { ReactNode } from "react"; const convex = new ConvexReactClient(/* ... */); function RootComponent({ children }: { children: ReactNode }) { return {children}; } ``` ### Parameters Parameter| Type| Description ---|---|--- `props`| `object`| Props for the provider. `props.client`| `ConvexReactClient`| Your `ConvexReactClient`. `props.storage`?| `TokenStorage`| Optional custom storage object. Defaults to `localStorage`. `props.storageNamespace`?| `string`| Optional namespace for token storage keys. `props.replaceURL`?| (`relativeUrl`) => `void` | `Promise`<`void`>| Function to handle URL replacement after OAuth or magic link sign-in. `props.shouldHandleCode`?| `boolean` | () => `boolean`| Function to determine if the auth provider should handle the code param from the URL. `props.children`| `ReactNode`| Children components that can call Convex hooks. ### Returns `Element` > The wrapped application component. ``` -------------------------------- ### Enable Convex Function Verbose Logging Source: https://labs.convex.dev/auth/debugging Enable verbose logging for Convex functions by setting the `AUTH_LOG_LEVEL` environment variable to `DEBUG`. This logs sensitive information and should only be used for debugging. Logs appear in the Convex dashboard. ```bash npx convex env set AUTH_LOG_LEVEL DEBUG ``` -------------------------------- ### Configure Password Provider in Convex Source: https://labs.convex.dev/auth/config/passwords Import and add the Password provider to your Convex authentication configuration. This sets up the backend for email/password authentication. ```typescript import { Password } from "@convex-dev/auth/providers/Password"; import { convexAuth } from "@convex-dev/auth/server"; export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({ providers: [Password], }); ``` -------------------------------- ### signInViaProvider() Source: https://labs.convex.dev/auth/api_reference/server Facilitates signing in a user via a specified authentication provider, often used for email verification or password resets. ```APIDOC ## signInViaProvider() ### Description Facilitates signing in a user via a specified authentication provider. This is commonly used for email verification during sign-up or for password reset flows. ### Method Not specified (assumed to be an action or mutation) ### Endpoint Not specified ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ctx** (GenericActionCtxWithAuthConfig) - Required - The Convex context with authentication configuration. - **provider** (AuthProviderConfig) - Required - Configuration for the authentication provider. - **args** (object) - Optional - - **accountId**? (Id<"authAccounts">) - Optional - The ID of the account to sign in with. - **params**? (Record) - Optional - Additional parameters for the sign-in process. ### Request Example ```json { "ctx": ">", "provider": { ... }, // AuthProviderConfig object "args": { "accountId": "account789", "params": { "email": "user@example.com" } } } ``` ### Response #### Success Response (200) - **userId** (string | null) - The ID of the signed-in user, or `null` if the sign-in cannot proceed. - **object** - Additional details about the sign-in process (structure not fully defined). ### Error Handling Returns `null` if the sign-in cannot proceed. Throws an error if other issues occur. ``` -------------------------------- ### ConvexAuthNextjsMiddlewareOptions Source: https://labs.convex.dev/auth/api_reference/nextjs/server Configuration options for the `convexAuthNextjsMiddleware` function. ```APIDOC ## ConvexAuthNextjsMiddlewareOptions Options for the `convexAuthNextjsMiddleware` function. ### Type declaration #### convexUrl? > `optional` **convexUrl** : `string` The URL of the Convex deployment to use for authentication. Defaults to `process.env.NEXT_PUBLIC_CONVEX_URL`. #### apiRoute? > `optional` **apiRoute** : `string` You can customize the route path that handles authentication actions via this option and the `apiRoute` prop of `ConvexAuthNextjsProvider`. Defaults to `/api/auth`. #### cookieConfig? The cookie config to use for the auth cookies. `maxAge` is the number of seconds the cookie will be valid for. If this is not set, the cookie will be a session cookie. See MDN Web Docs (opens in a new tab) for more information. #### cookieConfig.maxAge #### verbose? > `optional` **verbose** : `boolean` Turn on debugging logs. #### shouldHandleCode? Callback to determine whether Convex Auth should handle the code parameter for a given request. If not provided, Convex Auth will handle all code parameters. If provided, Convex Auth will only handle code parameters when the callback returns true. ### Defined in src/nextjs/server/index.tsx:143 ``` -------------------------------- ### Initialize Convex Auth Server Source: https://labs.convex.dev/auth/setup/manual Initialize the Convex authentication module in your server-side code (e.g., convex/auth.ts). This exports essential auth functions. ```typescript import { convexAuth } from "@convex-dev/auth/server"; export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({ providers: [], }); ``` -------------------------------- ### Implement Sign-in Form with Resend Provider Source: https://labs.convex.dev/auth/config/email Create a React form to capture user email and trigger the Magic Links sign-in process using the Convex Auth `signIn` function. The provider ID 'resend' is used here. ```typescript import { useAuthActions } from "@convex-dev/auth/react"; export function SignIn() { const { signIn } = useAuthActions(); return (
{ event.preventDefault(); const formData = new FormData(event.currentTarget); void signIn("resend", formData); }}>
); } ``` -------------------------------- ### Call Convex Mutations and Actions from Next.js Server Components Source: https://labs.convex.dev/auth/authz/nextjs Use `fetchQuery` to call Convex queries and `fetchMutation` to call mutations within Next.js Server Components. Ensure you obtain an authentication token using `convexAuthNextjsToken` for mutations and revalidate paths after mutations. ```typescript import { convexAuthNextjsToken } from "@convex-dev/auth/nextjs/server"; import { api } from "@/convex/_generated/api"; import { fetchMutation, fetchQuery } from "convex/nextjs"; import { revalidatePath } from "next/cache"; export default async function PureServerPage() { const tasks = await fetchQuery(api.tasks.list, { list: "default" }); async function createTask(formData: FormData) { "use server"; await fetchMutation( api.tasks.create, { text: formData.get("text") as string, }, { token: await convexAuthNextjsToken() }, ); revalidatePath("/example"); } // render tasks and task creation form return
...
; } ``` -------------------------------- ### ConvexAuthActionsContext.signIn() Source: https://labs.convex.dev/auth/api_reference/react Signs in a user via a configured authentication provider. It can accept parameters for the sign-in process, such as redirect URLs or verification codes. ```APIDOC #### signIn() ### Description Sign in via one of your configured authentication providers. ### Parameters Parameter| Type| Description ---|---|--- `this`| `void`| - `provider`| `string`| The ID of the provider. `params`?| `FormData` | `Record`<`string`, `Value`> & `object`| Sign-in parameters, which can be a `FormData` object or a plain object. Special fields include `redirectTo` and `code`. ### Returns `Promise`<`object`> > Whether the user was immediately signed in. ``` -------------------------------- ### useConvexAuth() Source: https://labs.convex.dev/auth/api_reference/react Hook to access authentication status and fetch access tokens. It returns an object with `isLoading`, `isAuthenticated`, and a `fetchAccessToken` function. ```APIDOC ## useConvexAuth() ### Description Hook to access authentication status and fetch access tokens. ### Returns `object` #### isLoading > **isLoading** : `boolean` > Indicates if the authentication state is currently being loaded. #### isAuthenticated > **isAuthenticated** : `boolean` > Indicates if the user is currently authenticated. #### fetchAccessToken() ##### Description Fetches the current access token. ##### Parameters Parameter| Type ---|--- `__namedParameters`| `object` `__namedParameters.forceRefreshToken`| `boolean` ##### Returns `Promise` > A promise that resolves to the access token string, or null if not available. ``` -------------------------------- ### Anonymous() Function Source: https://labs.convex.dev/auth/api_reference/providers/Anonymous The Anonymous() function initializes an anonymous authentication provider. ```APIDOC ## Anonymous() ### Description An anonymous authentication provider. This provider doesn't require any user-provided information. ### Parameters - **config** (AnonymousConfig) - Required - The configuration object for the Anonymous provider. ### Returns - `ConvexCredentialsConfig` - The configuration for the Convex credentials. ``` -------------------------------- ### User Sign-in Mutation Source: https://labs.convex.dev/auth/api_reference/server This section describes the mutation for signing in users, handling various authentication methods and provider integrations. ```APIDOC ## POST /api/auth/signin ### Description Handles user sign-in using various methods including OAuth, credentials, email, phone, or after verification. ### Method POST ### Endpoint /api/auth/signin ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ctx** (GenericMutationCtx) - Required - The mutation context. - **args** (object) - Required - The arguments for the sign-in mutation. - **args.userId** (GenericId<"users">) - Required - The ID of the user being signed in. - **args.existingUserId** (GenericId<"users">) - Optional - The ID of an existing user account if linking or signing into an existing account. - **args.type** ("oauth" | "credentials" | "email" | "phone" | "verification") - Required - The type of authentication provider or action. - **args.provider** (AuthProviderMaterializedConfig) - Required - The authentication provider configuration. - **args.profile** (Record & object) - Required - Profile information, which varies by provider (OAuth profile, email address, phone number, or credentials config profile). - **args.shouldLink** (boolean) - Optional - Indicates whether to link the new sign-in to an existing account. ### Request Example ```json { "ctx": { ... }, "args": { "userId": "user_123", "type": "oauth", "provider": { ... }, "profile": { "email": "user@example.com", "name": "John Doe" }, "shouldLink": false } } ``` ### Response #### Success Response (200) - **void** - The mutation does not return a value upon successful completion. #### Response Example (No response body for void return type) ``` -------------------------------- ### callbacks.createOrUpdateUser() Source: https://labs.convex.dev/auth/api_reference/server 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. ```APIDOC ## POST /callbacks/createOrUpdateUser ### Description Callback to create or update a user document during the sign-in process. ### Method POST ### Endpoint /callbacks/createOrUpdateUser ### Parameters #### Request Body - **args** (object) - Required - Arguments for the callback. - **existingUserId** (GenericId<"users"> | null) - Optional - The existing user ID if signing into an existing account. - **type** (string) - Required - The provider type (e.g., "oauth", "credentials", "email", "phone", "verification"). - **provider** (AuthProviderMaterializedConfig) - Required - The provider used for sign-in. - **profile** (Record & object) - Required - The profile returned by the OAuth provider, passed to `createAccount`, or the email/phone number. - **shouldLink** (boolean) - Optional - The `shouldLink` argument passed to `createAccount`. ### Request Example ```json { "args": { "existingUserId": null, "type": "oauth", "provider": {"id": "github", "name": "GitHub"}, "profile": {"id": "12345", "name": "John Doe", "email": "john.doe@example.com"}, "shouldLink": false } } ``` ### Response #### Success Response (200) - **userId** (GenericId<"users">) - The ID of the created or updated user. #### Response Example ```json { "userId": "user_abc123" } ``` ``` -------------------------------- ### Set Up ConvexAuthProvider in React App Source: https://labs.convex.dev/auth/setup Replace the default `ConvexProvider` with `ConvexAuthProvider` from `@convex-dev/auth/react` to enable Convex Auth in your React application. ```typescript import { ConvexAuthProvider } from "@convex-dev/auth/react"; import React from "react"; import ReactDOM from "react-dom/client"; import { ConvexReactClient } from "convex/react"; import App from "./App.tsx"; import "./index.css"; const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string); ReactDOM.createRoot(document.getElementById("root")!).render( , ); ``` -------------------------------- ### Integrate ResendOTP Provider in Convex Auth Source: https://labs.convex.dev/auth/config/otps Integrate the custom ResendOTP provider into your Convex authentication configuration. This sets up the necessary auth, signIn, signOut, store, and isAuthenticated functions. ```typescript import { convexAuth } from "@convex-dev/auth/server"; import { ResendOTP } from "./ResendOTP"; export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({ providers: [ResendOTP], }); ```