Account deletion
Let people delete their own account, and erase the data your app holds about them.
People expect to delete their account. Two parts make that work:
- Better Auth deletes the sign-in data: the auth user, sessions and linked accounts. You turn this on with
deleteUser. - Your app erases its own data about the person. The user projection calls your erasure when the auth user is deleted.
Nothing is deletable until you turn it on. Without deleteUser, the delete route answers 404, and without an erase hook, no app data is touched.
Turn on account deletion
export const auth = createBetterConvexAuth<DataModel>(components.betterAuth, {
deleteUser: {
enabled: true,
beforeDelete: async (ctx, user) => {
const owns = await ctx.runQuery(internal.teams.ownsATeam, { authId: user.id })
if (owns)
throw new ConvexError({ message: 'Transfer your team before you delete your account.' })
},
},
})beforeDelete is the one place to refuse. It gets the same ctx as beforeUserCreate and the auth user (id, email, name). Throw to stop the deletion: nothing is deleted. The message of a ConvexError or Better Auth APIError reaches the person. Any other error is logged and the person sees AUTH_USER_DELETE_REFUSED.
Better Convex accepts only enabled and beforeDelete. The other Better Auth options for deleteUser are not available.
The auth user, its accounts, and up to 64 sessions are deleted in one
mutation. A user with more sessions, for example a test account that signs in
often, is deleted too: the other sessions stop working at once, because every
session check reads the user, and a scheduled function deletes them right
after, 128 per run. Session onDelete triggers do not run for these sessions,
the same as for sessions that expire.
How the person proves it is them
- Without an
emailhook, the session must be fresh (Better Authsession.freshAge, one day by default), or the request must carry the account password. A stale session without the password is refused withSESSION_EXPIRED. Ask the person to sign in again, then callauthClient.deleteUser(). - With an
emailhook, the first request sends adelete-accountemail with a link and deletes nothing. The account is deleted when the person opens the link while signed in. Handle thedelete-accounttype in your hook; it hasurl,tokenanduser, likereset-password. The link is valid for one day.
Erase the app's data
The projection deletes the app user row when the auth user is deleted. Give it an erase hook to erase everything else. With @lupinum/better-convex-functions:
import { eraseUser } from '@lupinum/better-convex-functions'
const userProjection = createUserProjectionTriggers({
table: 'users',
index: 'by_auth_user_id',
authIdField: 'authUserId',
createDoc: ({ user, now }) => ({ authUserId: user.id, createdAt: now }),
erase: async ({ ctx, existing }) => {
await eraseUser(ctx, existing._id, internal.erasure.eraseStep)
},
})erase runs once for each projection row, in the same transaction, just before the row is deleted. It runs only when an auth user is deleted, by deleteUser or by any other way. eraseUser deletes nothing itself. It schedules eraseStep, which works in batches and schedules itself until nothing is left.
Declare what happens to each table with erasure in defineFunctions, and export the step:
export const fns = defineFunctions({
// ...
schema,
erasure: {
drafts: { delete: 'authorId' },
comments: { anonymize: 'authorId' },
tasks: [{ delete: 'authorId' }, { anonymize: 'assigneeId' }],
projects: { keep: 'Team data stays with the team.' },
},
})import { fns } from './functions'
export const { eraseStep } = fns.erasure| Entry | What it does |
|---|---|
{ delete: 'field' } | Deletes the rows where field is the person's app user ID. |
{ anonymize: 'field' } | Keeps the rows and removes the field. The field must be v.optional(...) in the schema. |
{ keep: 'reason' } | Leaves the table alone. The reason is required and stays in your code. |
[entry, entry] | A table with more than one field that holds a user ID: one entry for each field. |
keep covers the whole table, so it cannot be in an array with other entries.
The library never guesses which rows belong to a person. A table that is not in the map is not touched. The launch check fails when a table has a user ID field that its entries do not cover, or when no module exports eraseStep, so a table or field added later is not forgotten. The check looks for v.id('users'), so the table of your users must be called users. These mistakes throw when defineFunctions runs, not when a person is erased:
- a table that is not in the schema, or an entry with more or less than one of
delete,anonymizeandkeep, orkeepin an array with other entries; - a field that the table does not have;
- a field that holds a list, object or record. Erasure finds rows whose field is the person's ID itself, so it cannot find an ID inside one. Store the ID in its own indexed field, or use
keep; - no index whose first field is that field. Add
.index('by_author', ['authorId']); anonymizeon a field that is not optional;keepwithout a reason;erasurewithoutschema.
What the library erases itself
Library tables are covered without any entry, when they are in your schema:
| Table | What happens |
|---|---|
activity, auditLog | Rows stay. actor.userId is removed and the actor key is replaced. |
approvals | A request the person made: still pending requests are cancelled, and the requester, user, session and grant IDs are replaced. A request that someone else decided keeps its row. Requests of other people are not changed. |
agentGrants, agentRuns, agentMessages | Deleted. |
rateLimits | Counters of the person are deleted. |
decidedBy on an activity or approval row of someone else is not changed: it names the person who decided, and the row belongs to the other person.
Cost and limits
Each step reads at most 100 rows or 4 MiB, deletes or patches them, and schedules the next step. A person with 10,000 rows needs about 100 steps, one transaction each. Running a step again is safe: rows that are gone are not found again. If an erasure stops half-way, call eraseUser again for the same person.
Erasure removes rows that your own tables hold. It does not reach files in storage, backups, logs, or other services. Remove those in beforeDelete, or in your own scheduled function.
Test it once with real data: create a person with rows in each mapped table, delete the account, run the scheduled steps, and check what is left. The starter's convex/account.test.ts shows how.
Delete another user from a Convex function
An admin removes a member, or you act on an erasure request that reached you by
email. Call auth.deleteUser(ctx, userId) from an internal mutation, after your
own check of who may delete whom.
import { ConvexError, v } from 'convex/values'
import { internal } from './_generated/api'
import { internalMutation, mutation } from './_generated/server'
import { auth } from './auth'
export const remove = mutation({
args: { authUserId: v.string() },
handler: async (ctx, args): Promise<null> => {
const caller = await auth.requireUser(ctx)
const me = await ctx.db
.query('users')
.withIndex('by_auth_id', (q) => q.eq('authId', caller.id))
.unique()
if (me?.role !== 'admin') throw new ConvexError({ code: 'FORBIDDEN' })
await ctx.runMutation(internal.members.deleteAuthUser, { authUserId: args.authUserId })
return null
},
})
export const deleteAuthUser = internalMutation({
args: { authUserId: v.string() },
handler: async (ctx, args): Promise<null> => {
await auth.deleteUser(ctx, args.authUserId)
return null
},
})The users table has a role field and the index by_auth_id on authId.
auth.deleteUser checks no permission. It deletes whichever user ID it gets, so
never pass an ID from the browser to it without a check like the one in remove.
It is the same deletion that authClient.deleteUser() does. The user's
sessions stop working at once. Better Auth then deletes the sessions, the
linked accounts and the auth user. Your onDelete triggers run for each of
these rows, so the user projection deletes the app user row and runs your
erase hook. The session limit above applies here too: sessions after the
first 64 are deleted later, without onDelete triggers. A user ID that does not
exist is not an error.
These steps belong to the person's own delete request and do not run here:
deleteUser.beforeDelete. Do the same checks before you calldeleteAuthUser.- The fresh session or password check, and the
delete-accountemail. - The
deleteUser.enabledswitch.auth.deleteUserworks without it.
In a mutation, the deletion is one transaction. From an action it also works,
but each step is its own transaction; if one fails, call auth.deleteUser
again to finish. A query cannot delete: the call throws
AUTH_DELETE_USER_REQUIRES_WRITABLE_CONTEXT.
Cost: it reads the user, its sessions and its accounts in the auth component,
updates the user once so that every session stops working, and deletes the
accounts, up to 64 sessions and the user. Each deleted row runs your onDelete
trigger in the same transaction. Queries that read these auth rows for the user,
such as getUser in that person's open tabs, and queries that read the rows
your triggers change, update.
Do not call the component mutation components.betterAuth.adapter.deleteOne
for the user. It deletes the sessions and accounts too, but it does not run your
onDelete triggers. The app user row and the data that erase removes stay
behind.