Add authentication
Sign people in with a code sent by email, with Better Auth.
Add sign-in with Better Auth. A person enters an email address, gets a code, and enters the code. The same form creates the account on the first sign-in, so there is no separate sign-up and no password. Better Auth stores users and sessions in a Convex component, and Nuxt forwards /api/auth/* requests to it.
After this page:
/is the sign-in page./todosis the todo list.- Sign-out returns to
/.
Install Better Auth
pnpm add better-auth@1.7.16 @better-auth/core@1.7.16 @better-auth/oauth-provider@1.7.16All three packages must be exactly 1.7.16. The module does not work with other versions.
Generate the auth files
Keep pnpm dev running. In a second terminal, run:
pnpm exec better-convex-nuxt auth initIt works only with a development or local deployment, and it asks before each step:
- It shows the files it creates in
convex/and writes them. When all of them already exist, it keeps them. When some exist with other content and others are missing, it stops without changes. - It generates the auth database schema in
convex/betterAuth/. - It asks for the site URL. Press Enter to accept
http://localhost:3000. It writesSITE_URLto.env.localand sets it in Convex, so Nuxt and Convex use the same origin. - It sets the secrets:
BETTER_AUTH_SECRETSin Convex, andBCN_AUTH_PROXY_IP_SECRETin.env.localand in Convex. Nuxt signs each auth request with the proxy secret, and Convex checks the signature. - It creates the first key that signs session tokens.
In a script or CI, auth init --yes accepts every step without asking.
If step 5 fails, wait until the pnpm dev output shows [convex] ✔ Convex functions ready!, and run pnpm exec better-convex-nuxt auth init again. Running it again is safe.
auth init wrote these files:
| File | Purpose |
|---|---|
convex/auth.ts | The auth setup: sign-in methods and options |
convex/auth.config.ts | Lets Convex accept the session tokens |
convex/http.ts | Adds the /api/auth/* routes to Convex |
convex/convex.config.ts | Registers the auth component as betterAuth |
convex/betterAuth/ | The auth component; its schema files are generated, do not edit them |
Turn on email codes
auth init turns on password sign-in. Replace convex/auth.ts to use email codes instead:
import { createBetterConvexAuth } from '@lupinum/better-convex-nuxt/better-auth/server'
import { components } from './_generated/api'
import type { DataModel } from './_generated/dataModel'
export const auth = createBetterConvexAuth<DataModel>(components.betterAuth, {
// Sign-in with a code sent by email. Without an `email` hook, the code appears in the
// `pnpm dev` output while SITE_URL is http://localhost.
emailOTP: {},
// Put the email address in the session token, so pages can show it.
defineSessionClaims: ({ user }) => ({ email: user.email }),
})
export const createAuth = auth.createAuth
export const { ensureSigningKey, pruneSigningKeys, rotateSigningKey } = auth.jwksOperatorFunctions()
export const { onCreate, onUpdate, onDelete } = auth.triggerFunctions()No sign-in method is on until you name it. The file has no email hook yet, so codes are not mailed. On a local SITE_URL, they go to the Convex log (the dev outbox), which pnpm dev prints. Before you deploy, add the email hook. Locally, the codes still go to the log after you add it; see Transactional auth email.
The email in the session token is for display. Decide access from rows in Convex, not from this value. See Session claims.
Add the email-code methods to the browser auth client:
import { defineConvexAuthClient } from '@lupinum/better-convex-nuxt/better-auth/client'
import { emailOTPClient } from 'better-auth/client/plugins'
export default defineConvexAuthClient({
plugins: [emailOTPClient()],
})Turn on auth in Nuxt
Stop pnpm dev with Ctrl-C. Nuxt reads .env.local only when it starts, and the new configuration needs SITE_URL from that file. If you change nuxt.config.ts while pnpm dev still runs, Nuxt reports auth.origin is missing.
Check that .env.local contains SITE_URL. auth init writes it, unless the Convex deployment already had a SITE_URL. In that case, add the same value to .env.local.
Add the convex block to nuxt.config.ts. Keep your own compatibilityDate:
export default defineNuxtConfig({
compatibilityDate: '2025-07-15',
devtools: { enabled: true },
modules: ['@lupinum/better-convex-nuxt'],
convex: {
auth: {
origin: process.env.SITE_URL,
trustedClientIpHeader: process.env.BCN_AUTH_TRUSTED_CLIENT_IP_HEADER,
// Where a protected page sends anonymous visitors, and where the sign-in page sends
// people who are already signed in.
redirectTo: '/',
guestRedirectTo: '/todos',
},
},
})- The
authobject turns on auth.originmust be the exact public address of your Nuxt app. trustedClientIpHeadermay be empty only onlocalhost. On any other origin, Nuxt refuses to start without it. See deployment.
Start pnpm dev again.
Move the todo list to /todos
The sign-in page becomes /. Move the todo page:
mv app/pages/index.vue app/pages/todos.vueAdd the signed-in email and a sign-out button to it:
<script setup lang="ts">
import { api } from '#convex/api'
const { user, client } = useConvexAuth()
const text = ref('')
const { data: todos, status, error } = useConvexQuery(api.todos.list)
const {
mutate: createTodo,
pending: creating,
error: createError,
} = useConvexMutation(api.todos.create)
const { mutate: toggleTodo, error: toggleError } = useConvexMutation(api.todos.toggle)
const { mutate: removeTodo, error: removeError } = useConvexMutation(api.todos.remove)
const callError = computed(() => createError.value ?? toggleError.value ?? removeError.value)
async function add() {
try {
await createTodo({ text: text.value })
text.value = ''
} catch {
// createError holds the error. The template shows it.
}
}
async function signOut() {
await client.signOut()
await navigateTo('/')
}
</script>
<template>
<main>
<p v-if="user" class="muted">
Signed in as {{ user.email }}
<button @click="signOut">Sign out</button>
</p>
<h1>Todos</h1>
<form @submit.prevent="add">
<input v-model="text" maxlength="200" placeholder="What needs doing?" aria-label="Todo" />
<button :disabled="creating || !text.trim()">Add</button>
</form>
<p v-if="callError" class="error">{{ callError.message }}</p>
<p v-if="status === 'pending'" class="muted">Loading todos…</p>
<p v-else-if="error" class="error">Could not load the todos.</p>
<p v-else-if="todos?.length === 0" class="muted">No todos yet. Add the first one.</p>
<ul v-else>
<li v-for="todo in todos" :key="todo._id">
<input
type="checkbox"
:checked="todo.completed"
:aria-label="`Done: ${todo.text}`"
@change="toggleTodo({ todoId: todo._id }).catch(() => {})"
/>
<span :class="{ done: todo.completed }">{{ todo.text }}</span>
<button @click="removeTodo({ todoId: todo._id }).catch(() => {})">Delete</button>
</li>
</ul>
</main>
</template>useConvexAuth()returns the signed-inuser, the authstatus, andclient, the Better Auth client.user.emailcomes from the session claim inconvex/auth.ts. Without the claim, it isundefined.- Call
clientmethods only in the browser, for example in event handlers.
Add the sign-in page
<script setup lang="ts">
definePageMeta({ convexAuth: 'guest' })
const { client } = useConvexAuth()
const returnTo = useConvexAuthReturnTo()
const email = ref('')
const code = ref('')
const codeSent = ref(false)
const busy = ref(false)
const message = ref<string | null>(null)
// Better Auth reports each failure with a code. Show a clear sentence for the common ones.
const messages: Record<string, string> = {
INVALID_OTP: 'That code is not correct. Check it and try again.',
OTP_EXPIRED: 'That code has expired. Send a new one.',
TOO_MANY_ATTEMPTS: 'Too many wrong codes. Send a new one.',
}
function explain(error: { code?: string; message?: string }) {
return (error.code && messages[error.code]) || error.message || 'Something went wrong.'
}
async function sendCode() {
busy.value = true
message.value = null
const { error } = await client.emailOtp.sendVerificationOtp({
email: email.value,
type: 'sign-in',
})
busy.value = false
if (error) {
message.value = explain(error)
return
}
codeSent.value = true
}
async function signIn() {
busy.value = true
message.value = null
const { error } = await client.signIn.emailOtp({
email: email.value,
// A code copied from an email often has spaces around it.
otp: code.value.trim(),
})
busy.value = false
if (error) {
message.value = explain(error)
return
}
await navigateTo(returnTo.value ?? '/todos')
}
</script>
<template>
<main>
<h1>Sign in</h1>
<form v-if="!codeSent" @submit.prevent="sendCode">
<input
v-model="email"
type="email"
autocomplete="email"
placeholder="you@example.com"
aria-label="Email"
required
/>
<button :disabled="busy">Send code</button>
</form>
<template v-else>
<p class="muted">We sent a code to {{ email }}.</p>
<form @submit.prevent="signIn">
<input
v-model="code"
inputmode="numeric"
autocomplete="one-time-code"
placeholder="123456"
aria-label="Code"
required
/>
<button :disabled="busy">Sign in</button>
</form>
<button @click="codeSent = false">Use another email</button>
</template>
<p v-if="message" class="error">{{ message }}</p>
</main>
</template>convexAuth: 'guest'sends a signed-in person toguestRedirectTo(/todos).useConvexAuthReturnTo()returns the page a visitor came from before a protected page sent them here, ornull. It accepts only paths on your own site.sendVerificationOtpcreates a code.signIn.emailOtpchecks it, creates the account on the first sign-in, and starts the session.
Try it
- Open
http://localhost:3000. You see the sign-in page. - Enter an email address and click Send code.
Find the code in the
pnpm devoutput. The line looks like this:[convex] ... [LOG] '[better-convex-nuxt dev outbox] email-otp to you@example.com: code 123456'- Enter the code and click Sign in. The app opens
/todosand shows your email. - Reload the page. You are still signed in.
- Open
/. You go back to/todos, because you are signed in. - Click Sign out. You are back on the sign-in page.
The todo list is still public: anyone can call todos.list, signed in or not. Continue with Protect data.
Production
better-convex-nuxt auth init does not work with a production deployment. Set the production secrets and the first signing key as described in deployment. Before you deploy, add the email hook to convex/auth.ts. A deployment with a SITE_URL that is not localhost fails to start without it, because codes must be mailed. See Transactional auth email.
To sign in with a password instead, see Sign in and sign out.