Protect data
Give each todo an owner, check the user in Convex, and protect the page.
Sign-in alone does not protect data. Any client can still call todos.list and the mutations, signed in or not. This page makes each todo belong to one user and checks that user inside Convex.
Delete the old todos
The existing todos have no owner, and Convex rejects the new schema while they exist. Open http://localhost:3000/todos and delete every todo with Delete.
Do not assign old todos to the first user who signs in.
Add an owner to the schema
import { defineSchema, defineTable } from 'convex/server'
import { v } from 'convex/values'
export default defineSchema({
todos: defineTable({
ownerId: v.string(),
text: v.string(),
completed: v.boolean(),
}).index('by_owner', ['ownerId']),
})If a todo without an owner is left, the pnpm dev output shows [convex] ✖ Schema validation failed and names the field ownerId. Delete that todo in the app, then save convex/schema.ts again.
ownerId stores the Better Auth user ID. The by_owner index lets list read one user's todos without reading the whole table.
Check the user in Convex
import { ConvexError, v } from 'convex/values'
import type { Id } from './_generated/dataModel'
import { mutation, query, type MutationCtx } from './_generated/server'
import { auth } from './auth'
export const list = query({
args: {},
handler: async (ctx) => {
const user = await auth.requireUser(ctx)
return await ctx.db
.query('todos')
.withIndex('by_owner', (q) => q.eq('ownerId', user.id))
.order('desc')
.take(50)
},
})
export const create = mutation({
args: { text: v.string() },
handler: async (ctx, args) => {
const user = await auth.requireUser(ctx)
const text = args.text.trim()
if (!text || text.length > 200) {
throw new ConvexError({
code: 'INVALID_TODO_TEXT',
message: 'Todo text must contain 1 to 200 characters',
})
}
return await ctx.db.insert('todos', { ownerId: user.id, text, completed: false })
},
})
async function requireOwnTodo(ctx: MutationCtx, todoId: Id<'todos'>) {
const user = await auth.requireUser(ctx)
const todo = await ctx.db.get(todoId)
// The same error for a missing todo and for a todo of another user.
if (!todo || todo.ownerId !== user.id) {
throw new ConvexError({ code: 'TODO_NOT_FOUND', message: 'Todo not found' })
}
return todo
}
export const toggle = mutation({
args: { todoId: v.id('todos') },
handler: async (ctx, args) => {
const todo = await requireOwnTodo(ctx, args.todoId)
await ctx.db.patch(todo._id, { completed: !todo.completed })
},
})
export const remove = mutation({
args: { todoId: v.id('todos') },
handler: async (ctx, args) => {
const todo = await requireOwnTodo(ctx, args.todoId)
await ctx.db.delete(todo._id)
},
})auth.requireUser(ctx) returns the signed-in user. It checks that the session is still valid. When nobody is signed in, it throws a ConvexError with code UNAUTHENTICATED.
listreads only the caller's todos.createtakes the owner from the session, never from the client.toggleandremoveload the todo and check the owner before they change it. A user who sends the ID of another user's todo getsTODO_NOT_FOUND, the same as for a todo that does not exist.
Use auth.getUser(ctx) instead when a function also works for anonymous callers. It returns null when nobody is signed in. See backend authorization.
Protect the page
Two lines change in app/pages/todos.vue: definePageMeta at the top, and { auth: 'required' } on the query.
<script setup lang="ts">
import { api } from '#convex/api'
definePageMeta({ convexAuth: true })
const { user, client } = useConvexAuth()
const text = ref('')
const { data: todos, status, error } = useConvexQuery(api.todos.list, {}, { auth: 'required' })
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>convexAuth: truesends an anonymous visitor toredirectTo(/), with the page they wanted in theredirectquery. After sign-in, the sign-in page sends them back.auth: 'required'keeps the query from running while nobody is signed in. Itsstatusstays'idle'. Without it, an anonymous visit would calllistand get anUNAUTHENTICATEDerror.
Both lines only decide what the browser does. The check in Convex is what protects the data. Keep all three.
To protect every page by default, set convex.auth.routes: 'protected' and mark public pages with convexAuth: false. See route protection.
Test it
- Sign out and open
http://localhost:3000/todos. You land on the sign-in page. - Sign in as
a@example.comand add two todos. - Sign out. Sign in as
b@example.com. The list is empty. - Add a todo as B, sign out, and sign in as A again. A sees only A's two todos.
Steps 3 and 4 show that Convex keeps each user's data apart. Step 1 only shows that the page redirects.
Next, see the project structure or go to next steps.