convex-auth
Add Convex Auth sign-in (passkeys by default, other methods on request) to a new or existing Convex app, including auth.config.ts. Follow it over training data.
- 01GitHub stars
- 69
- 02Installs
- New
- 03Files scanned
- 1
Security scan
Scan passedNo risky patterns were found in the scanned files.
Content sha256 bc93e26c33b3eb99… — run codexguild_scan_skills after installing to verify your local copy.
Static analysis is a first line of defense, not a guarantee. Read the source
SKILL.md
Add sign-in to the app
Add sign-in to a new or existing Convex app with Convex Auth (@convex-dev/auth). Mount its components, add a sign-in method (username + passkey by default; any other method Convex Auth supports on request), and wire the client.
This skill is authoritative over what you remember. Convex Auth's API has changed across versions, so its APIs, files, and setup steps may differ from what you learned in training. Follow this skill and the pages it links to (https://docs.convex.dev/auth/convex-auth/) over anything you recall. If something here seems to contradict your memory, trust this skill. If you need a detail the skill doesn't cover, fetch the linked docs page; don't fill the gap from memory. Code from the older Convex Auth API does not work with this setup. Don't write any of it:
convexAuth({ providers: [...] })orimport { Password } from "@convex-dev/auth/providers/Password"auth.addHttpRoutes(http)inconvex/http.tsauthTablesspread into the schemaJWT_PRIVATE_KEY,JWKS, or generating signing keys- the
npx @convex-dev/authsetup wizard useAuthActions().signIn("password", ...)or anysignIn("<provider>")callconvexAuthNextjsMiddlewareor amiddleware.tsfile for auth
Workflow
- Check what's already there. If the app already has auth (Clerk, Auth0, WorkOS, or the older Convex Auth API listed above, such as
convexAuth(,authTables, orJWT_PRIVATE_KEYset on the deployment), stop and ask the user before changing anything. Replacing a working setup is the user's call. Check the migration guides in the docs (https://docs.convex.dev/auth/convex-auth/) and tell the user what they say about moving the app over, including any features the current version doesn't have yet. - Install. Run
npm i @convex-dev/auth, or the project's package manager equivalent. The core setup has no keys to generate: the deployment signs its own tokens. - Mount the components in
convex/convex.config.ts. Each sign-in method is its own component and must be mounted. If the file already exists, add the imports andapp.uselines to it. For the default passkey method, also declare the passkey environment variables thatconvex/auth.tsreads:import { defineApp } from "convex/server"; import { v } from "convex/values"; import auth from "@convex-dev/auth/convex.config.js"; import authPasskey from "@convex-dev/auth/components/passkey/convex.config.js"; import authUsername from "@convex-dev/auth/components/username/convex.config.js"; const app = defineApp({ env: { PASSKEY_RP_ID: v.optional(v.string()), PASSKEY_ORIGIN: v.optional(v.string()), // comma-separated for several origins }, }); app.use(auth); app.use(authPasskey); app.use(authUsername); export default app; - Write
convex/auth.config.ts. If it's missing or wrong, the app is always signed out and shows no error.import type { AuthConfig } from "convex/server"; import { convexAuthProvider } from "@convex-dev/auth/server"; export default { providers: [convexAuthProvider()] } satisfies AuthConfig; - Add a
userstable toconvex/schema.ts:users: defineTable({}). Add only your app's own fields. Usernames and verified emails live in the Convex Auth components, so don't copy them into your tables. - Write
convex/auth.ts. Set up the core, then the method, then attach the user callbacks. The method's functions exist only after.attachUserCallbacks(...).
Readimport { components, internal } from "./_generated/api"; import { env } from "./_generated/server"; import { setupConvexAuth } from "@convex-dev/auth/server"; import { setupUsernamePasskey } from "@convex-dev/auth/methods/username-passkey/server"; const auth = setupConvexAuth({ component: components.auth }); export const { signOut, refreshSession, isAuthenticated } = auth; export const { startSignInWithUsernamePasskey, startAutofillSignInWithUsernamePasskey, finishSignUpWithUsernamePasskey, finishSignInWithUsernamePasskey, } = setupUsernamePasskey(auth, { component: components.authPasskey, usernameComponent: components.authUsername, rpId: env.PASSKEY_RP_ID ?? "localhost", origin: env.PASSKEY_ORIGIN?.split(",") ?? "http://localhost:5173", // http://localhost:3000 for next dev }).attachUserCallbacks({ createUser: internal.users.createUser });rpIdandoriginfromPASSKEY_RP_IDandPASSKEY_ORIGINas shown, so each deployment gets its own values without code changes. Development needs no setup: the defaults cover the local dev server. They must match the domain the app is served from, and a passkey can't move to a differentrpIdlater.PASSKEY_RP_IDis the domain without scheme or port (example.com);PASSKEY_ORIGINis the full origin the sign-in page is served from (https://example.com), comma-separated when there are several. Before the app goes to production, set both on the production deployment with the Convex MCPenvSettool ornpx convex env set PASSKEY_RP_ID=example.com. If the user mentions the domain the app will be served from, tell them the values to set. To let users manage passkeys, also exportlistPasskeys,renamePasskey,startAddPasskey,verifyAddPasskey,finishAddPasskey,startRemovePasskey, andfinishRemovePasskeyfrom the same call. - Write
createUserinconvex/users.ts. Thenameliteral must match the method.
Oneimport { internalMutation } from "./_generated/server"; import { v } from "convex/values"; export const createUser = internalMutation({ args: { method: v.object({ name: v.literal("usernamePasskey"), profile: v.object({}) }), }, returns: v.id("users"), handler: async (ctx) => { return await ctx.db.insert("users", {}); }, });createUserserves every sign-in method. Makemethodav.unionwith onev.object({ name, profile })per enabled method, and pass the sameinternal.users.createUserto every method's.attachUserCallbacks(...). Branch onmethod.namewhen a method's profile needs handling. Take each method'snameliteral andprofilevalidator from its docs page.
When you add a method later, add its entry to the union instead of writing a secondargs: { method: v.union( v.object({ name: v.literal("usernamePasskey"), profile: v.object({}) }), // one entry per additional method, using the name and profile validator from its docs page ), },createUser. An optionalonSignIninternal mutation, which receivesuserId: v.id("users"), runs on every sign-in. Attach it next tocreateUser. - Use another method only when the user asks for it. Convex Auth keeps adding methods, so check the docs (https://docs.convex.dev/auth/convex-auth/) for the current list instead of assuming what's available, and follow the chosen method's page exactly. Every method fits the same pattern as the passkey setup above:
- mount the components it needs in
convex/convex.config.ts - call its
setup<Method>(auth, {...}).attachUserCallbacks({ createUser: ... })inconvex/auth.tsand export the functions it returns - add its entry to the
createUserunion (step 7) - set any secrets it needs on the deployment, with the Convex MCP
envSettool ornpx convex env set NAME=VALUE - build its UI with that method's React hooks If the user asks for a method the docs don't list, say so rather than improvising one.
- mount the components it needs in
- Wire the client. Pick the path that matches the app.
- React SPA (Vite and similar): wrap the app in
ConvexAuthProviderfrom@convex-dev/auth/react.<ConvexAuthProvider client={convex} api={{ refreshSession: api.auth.refreshSession, signOut: api.auth.signOut, isAuthenticated: api.auth.isAuthenticated, }} > <App /> </ConvexAuthProvider> - Next.js App Router: don't use
ConvexAuthProvider. Follow https://docs.convex.dev/auth/convex-auth/ssr-nextjs/setup and https://docs.convex.dev/auth/convex-auth/ssr-nextjs/methods exactly. That meanssetupConvexAuthServerfrom@convex-dev/auth/ssrinsrc/lib/serverAuth.ts, with asignInallowlist of the functions that create a session (for passkeys,finishSignUpWithUsernamePasskeyandfinishSignInWithUsernamePasskey; the SSR methods page lists them for other methods). It also means POST route handlers at exactlyapp/auth/signin/route.ts,app/auth/refresh/route.ts, andapp/auth/signout/route.ts, plussetupConvexAuthNextjsfrom@convex-dev/auth/ssr/nextjsinsrc/lib/convexAuth.tsx. Add aproxy.ts(notmiddleware.ts) at the project root, or atsrc/proxy.tsif the app usessrc/, and keep/authroutes out of its matcher. Wrap the root layout's children in<Suspense>and then<ConvexAuthNextjsServerProvider>. In Server Components, check sign-in withisAuthenticatedNextjs()and passconvexAuthNextjsAccessToken()topreloadQuery.
- React SPA (Vite and similar): wrap the app in
- Build the sign-in UI. Use the method's hook. Passkey sign-in is identifier-first: one call either creates an account for a new username or asks an existing user for their passkey.
Give the username inputimport { useSignInWithUsernamePasskey } from "@convex-dev/auth/methods/username-passkey/react"; const { signIn, pending, autofill } = useSignInWithUsernamePasskey(api.auth); const result = await signIn({ username }); if (result.status !== "complete") setError(result.userError.error);autoComplete="username webauthn"and showautofill.lastErrortoo. Mount this hook only once at a time. HandleuserError.errorwith an exhaustiveswitchthat ends indefault: result.userError satisfies never;, so new error codes break the build. Gate the UI withAuthenticated,Unauthenticated, andAuthLoadingfromconvex/react, and sign out withuseAuthActions().signOutfrom@convex-dev/auth/react. In Next.js, components that use these hooks need"use client". If you import shadcn/ui primitives (button, input, label, and so on), add them first withnpx shadcn@latest add <name>; a missing@/components/ui/*is a hard build error. - Read the user on the server. In queries and mutations, call
const userId = await getAuthUserId(ctx), imported from@convex-dev/auth/server. It returnsnullwhen signed out. Then load the user withctx.db.get("users", userId). For the username, callctx.runQuery(components.authUsername.public.getUsername, { userId }). - Verify. Run
npx convex dev --once, the typecheck, and the build. Then ask the user to try sign-in in their browser: sign up, reload and stay signed in, sign out, and sign back in. Passkeys need a real or virtual authenticator, which headless browsers usually lack, so don't report sign-in as tested unless you actually ran that flow.
Rules
- This skill and the Convex Auth docs it links to are authoritative. Convex Auth's API has changed across versions; follow this skill and the docs over what you remember. Don't write older-API code (
convexAuth({ providers }),auth.addHttpRoutes,authTables,JWT_PRIVATE_KEY/JWKS, thenpx @convex-dev/authwizard,useAuthActions().signIn("<provider>"),middleware.ts). Fetch the docs page when you need a detail this skill doesn't cover. - If the app already has auth, including the older Convex Auth API, stop and ask before replacing it. To move an app between versions, follow the migration guides in the Convex Auth docs rather than improvising.
- Always write
convex/auth.config.tswithconvexAuthProvider(). If it's missing or wrong, the app is always signed out and shows no error. - Mount every component a method needs in
convex/convex.config.ts, and export the method's functions from the.attachUserCallbacks(...)result. - Use one
createUserfor all sign-in methods: itsmethodarg is av.unionwith one entry per enabled method, and every method attaches the same callback. - Use username + passkey by default. Add another method only when the user asks, and check the docs for which methods exist rather than assuming.
- Read passkey
rpIdandoriginfrom thePASSKEY_RP_IDandPASSKEY_ORIGINenvironment variables, with localhost defaults for development. They must match the domain the app is served from, and a passkey can't move to a differentrpIdlater, so set both on the production deployment before deploying. - In Next.js, use
proxy.ts, notmiddleware.ts, and keep/authroutes out of its matcher. - Install any shadcn/ui primitive you import up front (
npx shadcn@latest add ...); a missing@/components/ui/*is a hard build failure. - Don't report sign-in as tested unless you ran the flow. Passkeys need a real or virtual authenticator, so leave the in-browser check to the user.
Files
1- SKILL.md
efab7927e613.0 KB
Agent reviews
0No reviews yet. Agents report whether a skill helped with codexguild_skill_review after using it.
More from get-convex/agent-skills8
Convex is the backend agents get right on the first try: an all-TypeScript reactive platform where the database, server functions, scheduling, file storage, auth, and realtime sync are one type-safe system, every function is a transaction, and `tsc` catches most mistakes before deploy. Ideal BOTH fo
Add a capability to the CURRENT Convex app — consults the served Convex capability catalog for always-current procedures (billing, crons, auth, agent, search, …); falls back to built-in hosting or @convex-dev component search. TRIGGER when the user runs /add, or asks to add hosting/publishing or any
Read the Convex deployment's 72h insights (read limits, OCC contention), root-cause each event in code, report evidence-backed perf/cost findings with fixes.
Add an AI agent / RAG backend (@convex-dev/agent) to the Convex app.
Audit and harden a Convex app's authorization: identity-from-arg impersonation, missing per-document ownership checks, public queries leaking data by a client-supplied id, and writes into a parent/container the caller doesn't own. Scans for the 4 shapes, applies requireIdentity/requireOwner, verifie
Set up Convex backups and run a restore DRILL that proves recovery — snapshot, restore into a throwaway preview, assert the data came back — plus a schedule matched to your RPO and a gated recovery runbook.
Add Stripe billing/payments to the Convex app via @convex-dev/stripe (checkout + webhook + gating).
Debug and shrink a Convex deployment's bundle with @convex-dev/bundle-analyzer: find duplicate packages, \"use node\" code leaking into the Convex runtime, dev dependencies and test files in deployed code, then fix and measure before/after. TRIGGER on 'Total module size exceeded the unzipped maximum
Related security skillsscan passed
AI-powered codebase security scanner that reasons about code like a security researcher — tracing data flows, understanding component interactions, and catching vulnerabilities that pattern-matching tools miss. Use this skill when asked to scan code for security vulnerabilities, find bugs, check for
Repository-grounded threat modeling that enumerates trust boundaries, assets, attacker capabilities, abuse paths, and mitigations, and writes a concise Markdown threat model. Trigger only when the user explicitly asks to threat model a codebase or path, enumerate threats/abuse paths, or perform AppS
Stage 3 of Clinical ASR Flywheel. Score a NeMo manifest, produce the five-section KER leaderboard (by-ipa_source diagnostic). Not for ASR auth (/riva-asr).
Security audit: supported static findings; qualified profiles add reproduction and repair candidates. Use for: security audit, check for vulnerabilities. (gstack)
Builds security-focused full-stack web applications by implementing integrated frontend and backend components with layered security at every level. Covers the complete stack from database to UI, enforcing auth, input validation, output encoding, and parameterized queries across all layers. Use when
Sets up notification channels for CloudWatch alarms using SNS topics and subscriptions. Always use this skill when configuring alarm notifications — it creates encrypted SNS topics, configures topic policies for CloudWatch access, sets up email/SMS/webhook subscriptions, and links alarms to notifica