#how do i delete a user via convex-auth
5 messages · Page 1 of 1 (latest)
Hi @sturdy haven. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To delete a user when using Convex Auth (the Convex authentication component), you need to remove the user from your users table and also clean up related authentication data such as sessions and accounts. Convex Auth does not provide a single built-in function to cascade these deletions, so you must implement this logic yourself.
A typical approach is:
- Delete the user document from your users table.
- Delete all related auth data (sessions, accounts, etc.) that reference the user.
Here’s an example pattern, as shared by Convex support, for deleting a user and all related authentication data:
const [authSessions, authAccounts] = await Promise.all([
ctx.db
.query('authSessions')
.withIndex('userId', (q) => q.eq('userId', user._id))
.collect(),
ctx.db
.query('authAccounts')
.withIndex('userId', (q) => q.eq('userId', user._id))
.collect(),
]);
const [authRefreshTokens, authVerificationCodes, authVerifiers] =
await Promise.all([
(
await asyncMap(authSessions, async (session) => {
return ctx.db
.query('authRefreshTokens')
.withIndex('sessionId', (q) => q.eq('sessionId', session._id))
.collect();
})
).flat(),
(
await asyncMap(authAccounts, async (account) => {
return ctx.db
.query('authVerificationCodes')
.withIndex('accountId', (q) => q.eq('accountId', account._id))
.collect();
})
).flat(),
(
await asyncMap(authSessions, async (session) => {
return ctx.db
.query('authVerifiers')
.withIndex('sessionId', (q) => q.eq('sessionId', session._id))
.collect();
})
).flat(),
]);
await Promise.all([
asyncMap(authSessions, (session) => ctx.db.delete(session._id)),
asyncMap(authAccounts, (account) => ctx.db.delete(account._id)),
asyncMap(authRefreshTokens, (token) => ctx.db.delete(token._id)),
asyncMap(authVerificationCodes, (code) => ctx.db.delete(code._id)),
asyncMap(authVerifiers, (verifier) => ctx.db.delete(verifier._id)),
ctx.db.delete(user._id),
]);
This code:
- Queries for all sessions and accounts related to the user.
- Finds all refresh tokens, verification codes, and verifiers related to those sessions/accounts.
- Deletes all these documents, then finally deletes the user.
Note: You may need to adjust table and index names to match your schema. Also, ensure you have the necessary indexes (e.g., on userId and sessionId) for efficient queries.
This approach is necessary because Convex Auth does not automatically cascade deletions for you—you are responsible for cleaning up all related data when deleting a user. If you use a different auth integration (like NextAuth or Better Auth), the pattern is similar: delete the user and all related records in your Convex tables.