---
title: "Export and delete an account"
description: "Give a person one export of everything the app keeps of them, files included, and delete their account after a grace period they can cancel, erasing it everywhere: the backend's tables, the billing customer, the email contact and your own tables."
canonical_url: "https://nuxt-backend.dev/docs/build/auth/accounts/data"
---
# Export and delete an account

> Give a person one export of everything the app keeps of them, files included, and delete their account after a grace period they can cancel, erasing it everywhere: the backend's tables, the billing customer, the email contact and your own tables.

Version: nuxt-backend 0.6.x · Tab: Build · Kind: how-to · Status: stable

Every page: [llms.txt](https://nuxt-backend.dev/llms.txt) · Skill for coding agents: [nuxt-backend](https://nuxt-backend.dev/.well-known/skills/nuxt-backend/SKILL.md)

Commands use npm; use your project's package manager.

- [Try it live in the playground](https://nuxt-backend.dev/playground/security)
- [API reference](https://nuxt-backend.dev/docs/reference/api/account)
- [Source](https://github.com/qruto/nuxt-backend/blob/main/src/convex/integrations/account.ts)

People have a right to a copy of their data and to leave for good, and your app owes both within weeks of being asked. `setupAccount` answers both requests with one button each on `/security`. An export is one file of everything the app keeps of the person. A deletion waits out a grace period the person can cancel, then erases them at every provider.

Better Auth deletes the account record. The package adds the export, the grace period, and an erasure that reaches the billing provider, the email provider and your own tables.

## Set it up

The scaffold writes `backend/account.ts`, and passes the instance to `setupAuth` as `account`:

```ts [backend/account.ts]
import { setupAccount } from 'nuxt-backend/account'
import { DAY } from 'nuxt-backend/rate-limit'
import { components } from './_generated/api'
import { audit } from './audit'
import { billing } from './billing'
import { email } from './email'
import { paths } from './paths.generated'

export const account = setupAccount(components, { audit, billing, email, paths, graceMs: 30 * DAY })

// The functions behind useAccount and <AccountData>, and the erasure.
export const {
  exportAccountData,
  getAccountExport,
  eraseAccountData,
  getAccountDeletion,
  cancelAccountDeletion,
} = account.api
```

`graceMs` is how long a deletion waits. It is 30 days when you leave it out, and `0` erases as soon as the scheduled call runs. `eraseAccountData` is internal: it runs the providers' and your sources' part of an erasure, and the end of every grace period, by this name, so `backend/account.ts` must export it. Pass `email` so the notice of a scheduled deletion and its confirmation go out, and set `SITE_URL` for the link in them. The link opens `/account/keep`. Move that page with `backend.pages.keepAccount` and the link follows: the scaffold passes the generated `paths` to `setupAccount` ([The paths file](https://nuxt-backend.dev/docs/reference/configuration/module-options#the-paths-file)).

## Export an account's data

`useAccount().exportData()`, the button on `/security`, writes one JSON file. It holds everything the package keeps of the account. That is the account itself, its sessions, sign-in methods and passkeys, its workspaces and invitations, the gifts it bought and was sent, its billing cache, its [consents](https://nuxt-backend.dev/docs/build/auth/accounts/consents), its own activity, and how the [growth funnel](https://nuxt-backend.dev/docs/build/growth/measure) counts it (its attribution, its answer to "How did you hear about us?", the steps it reached and the experiment variants it saw). It adds the subscriptions and orders of its billing entities at the provider, and what your [own sources](#join-your-own-tables) export. Codes, tokens and keys never go in.

```vue [app/components/ExportData.vue]
<script setup lang="ts">
const { latestExport, exportsLeft, exportData, isPending } = useAccount()
</script>

<template>
  <a v-if="latestExport" :href="latestExport.url">Download your data</a>
  <button type="button" :aria-disabled="isPending || undefined" @click="exportData()">
    Export my data ({{ exportsLeft }} left today)
  </button>
</template>
```

- **Files come with it.** With [storage](https://nuxt-backend.dev/docs/build/data/files/checked-uploads) set up, the export bundles the person's files as zip parts (about 16 MB of files each, stored as they are), behind links that end with the export's own, an hour after it was made. `latestExport.parts` lists them, and each file in the export names its part and entry. A file over 32 MB keeps its own link only.
- **The link works for an hour.** Then the file is deleted, and `latestExport` turns `null` on its own.
- **Three a day.** A fourth is `rate_limited` (limit `accountExport`), with the wait.
- **Only the person.** An administrator's visit is refused (`forbidden`, reason `impersonating`).
- **Recorded.** Each export lands on the activity trail as `account.data_exported`.

## Delete an account

The person types their address to confirm, and the request takes a sign-in from the last ten minutes. `<AccountData>` asks for it with `<ReauthenticateDialog>`. On a page of yours, wrap the call in `withReauthentication`:

```vue [app/components/DeleteAccount.vue]
<script setup lang="ts">
const { deleteAccount, confirmation, error } = useAccount()
const { withReauthentication } = useReauthentication()
const typed = ref('')
</script>

<template>
  <form @submit.prevent="withReauthentication(() => deleteAccount(typed))">
    <label>Type {{ confirmation }} to delete your account</label>
    <input v-model="typed" type="email" autocomplete="off">
    <button type="submit">Delete my account</button>
    <p v-if="error" role="alert">{{ error.message }}</p>
  </form>
</template>
```

Then the grace period runs:

1. **The deletion is scheduled.** The account works as before, and an email tells the person when it will be deleted, with a "Keep my account" link. The link opens the `keepAccount` page (`/account/keep`, [Pages](https://nuxt-backend.dev/docs/build/ui/pages)) and needs no sign-in. Opening it changes nothing, so a mail scanner that follows links cancels nobody's deletion: the person presses the button.
2. **The app says so.** `<BackendNotices>` shows the date and a **Keep my account** button on every page ([Show app-wide notices](https://nuxt-backend.dev/docs/build/ui/notices)). `useAccount().deletion` holds `{ requestedAt, deletesAt }`, or `null`.
3. **The person can change their mind.** The email's link, the notice's button or `useAccount().cancelDeletion()` cancels it, and a second email confirms.
4. **When it ends, the account is erased** everywhere ([What an erasure removes](#what-an-erasure-removes)). An account that became the only owner of a workspace others belong to during the grace period waits instead, a day at a time, until another member becomes an owner or the others leave, so no workspace is left without one.

<table>
<thead>
  <tr>
    <th>
      Refused with
    </th>
    
    <th>
      When
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        invalid_input
      </code>
      
      , field <code>
        confirmation
      </code>
    </td>
    
    <td>
      The address typed is not the account's. <code>
        confirmation
      </code>
      
       holds the address the person should type.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        forbidden
      </code>
      
      , reason <code>
        sole_owner
      </code>
    </td>
    
    <td>
      The account is the only owner of a workspace others belong to. Another member becomes an owner first, or the others leave.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        reauthentication_required
      </code>
    </td>
    
    <td>
      The sign-in is older than ten minutes.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        forbidden
      </code>
      
      , reason <code>
        impersonating
      </code>
    </td>
    
    <td>
      An administrator is visiting the account.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        rate_limited
      </code>
      
      , limit <code>
        accountDelete
      </code>
    </td>
    
    <td>
      Three tries in the hour.
    </td>
  </tr>
</tbody>
</table>

Asking again keeps the date, and sends a new link that replaces the old one. An administrator who removes an account from the [admin console](https://nuxt-backend.dev/docs/build/auth/admin) skips the grace period: that is moderation, and it erases at once. So does `account.forget` from server code. From server code, `account.scheduleDeletion(ctx, userId)` and `account.cancelDeletion(ctx, userId)` do what the buttons do, after you have checked `account.soleOwnerships`.

## What an erasure removes

The erasure runs every participant in order, in batches of at most 200 rows, each batch scheduling the next. It cascades from your Convex tables out to every provider the account touched:

<table>
<thead>
  <tr>
    <th>
      Where
    </th>
    
    <th>
      What goes
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      The <code>
        backend
      </code>
      
       component
    </td>
    
    <td>
      The account, its sessions, sign-in methods, passkeys, its recovery code and the codes waiting for its address.
    </td>
  </tr>
  
  <tr>
    <td>
      
    </td>
    
    <td>
      Its memberships, and the invitations it sent or was sent. Its personal workspace, and every workspace it was the only member of, go with it, with their members, invitations, activity and billing cache.
    </td>
  </tr>
  
  <tr>
    <td>
      
    </td>
    
    <td>
      Its own activity. In the rows that stay, such as a workspace's trail or what an administrator did, its id becomes one random pseudonym.
    </td>
  </tr>
  
  <tr>
    <td>
      
    </td>
    
    <td>
      Its consents, its id in the feature flags' targets, its metered AI requests, its export files and mail held for its address.
    </td>
  </tr>
  
  <tr>
    <td>
      Convex file storage
    </td>
    
    <td>
      Every file it uploaded and claimed, and the share links to them (<a href="https://nuxt-backend.dev/docs/build/data/files/cleanup">
        Keep storage clean
      </a>
      
      ).
    </td>
  </tr>
  
  <tr>
    <td>
      Your tables
    </td>
    
    <td>
      What each of your <a href="#join-your-own-tables">
        sources
      </a>
      
       erases.
    </td>
  </tr>
  
  <tr>
    <td>
      The billing provider
    </td>
    
    <td>
      The customer of every billing entity that goes with it, deleted with <code>
        anonymize=true
      </code>
      
      . The provider keeps the orders, anonymized, for its books and taxes as merchant of record (<a href="https://nuxt-backend.dev/docs/services/polar">
        Polar
      </a>
      
      ).
    </td>
  </tr>
  
  <tr>
    <td>
      The email provider
    </td>
    
    <td>
      Its contact, with its topics and segments (<a href="https://nuxt-backend.dev/docs/services/resend">
        Resend
      </a>
      
      ).
    </td>
  </tr>
  
  <tr>
    <td>
      The monitoring provider
    </td>
    
    <td>
      Its name in reported errors: errors stop naming the account. Errors already reported keep their scrubbed contents until Sentry's retention removes them (<a href="https://nuxt-backend.dev/docs/services/sentry#data-and-compliance">
        Sentry
      </a>
      
      ).
    </td>
  </tr>
</tbody>
</table>

The cascade runs in that order, the providers last, so a provider that is down holds up only its own step ([When an erasure fails](#when-an-erasure-fails)).

A gift stays as a record of a payment, with the purchaser's or the recipient's address replaced. The [Privacy and data inventory](https://nuxt-backend.dev/docs/ship/compliance/privacy) lists every participant, what it holds and how long it is kept.

From server code, `account.forget(ctx, { userId })` deletes an account and erases it at once. Check `account.soleOwnerships(ctx, userId)` first.

## Someone without an account

A gift's recipient, an invitee or a person on the waitlist who never signed up may ask you to erase their address. Run `account.forgetEmail(ctx, email)` from an internal mutation of yours. It removes what the package and your sources keep of the address: invitations and gifts sent to it, mail held for it, its waitlist entry and its contact at the email provider. An address an account holds is refused (`invalid_input`, reason `has_account`): delete the account instead.

## Join your own tables

Each table of yours that keeps something of a person joins as a source. A source is two functions: an internal query that reads an account's rows for the export, and an internal mutation that erases a batch of them.

```ts [backend/account.ts]
import { setupAccount } from 'nuxt-backend/account'
import { components, internal } from './_generated/api'
import { audit } from './audit'
import { billing } from './billing'
import { email } from './email'

export const account = setupAccount(components, {
  audit,
  billing,
  email,
  sources: {
    strips: {
      description: 'The strips the account made.',
      export: internal.strips.exportFor,
      forget: internal.strips.forgetFor,
    },
  },
})
```

```ts [backend/strips.ts]
import { v } from 'convex/values'
import { internalMutation, internalQuery } from './_generated/server'

export const exportFor = internalQuery({
  args: { userId: v.string() },
  handler: async (ctx, { userId }) => ctx.db.query('strips')
    .withIndex('authorId', q => q.eq('authorId', userId)).take(1000),
})

export const forgetFor = internalMutation({
  args: { userId: v.optional(v.string()), email: v.optional(v.string()) },
  handler: async (ctx, { userId }) => {
    if (!userId) return { done: true }
    const rows = await ctx.db.query('strips')
      .withIndex('authorId', q => q.eq('authorId', userId)).take(200)
    for (const row of rows) await ctx.db.delete('strips', row._id)
    return { done: rows.length < 200 }
  },
})
```

`forget` runs again while it answers `{ done: false }`. It may run more than once for the same account, so keep it idempotent. The export carries a source's rows under its key in `app`. Erasing data belongs in a source rather than in `onUserDeleted`, since a source also runs for a deletion from server code and is retried.

## When an erasure fails

A participant that throws runs again after a wait, five times, each wait twice the last (`account.erasure_retried` in the log). Then the erasure stops at it:

- the log has `account.erasure_failed`, naming the participant, never the account or its address;
- administrators read `account.erasure_failed` in all activity, with the participant and its tries;
- `components.backend.account.failedErasures` lists the erasures waiting, and the participant each stopped at.

Fix what the error names, then run `account.forget(ctx, { userId })` again. An erasure that stopped resumes where it stopped. One left stopped for 30 days is dropped, with the address it held ([Respond to incidents](https://nuxt-backend.dev/docs/ship/operate/runbooks#an-erasure-stopped)).

A participant of your app's part (the billing customer, the email contact, a source of yours) that gives up keeps the plan it ran in `components.backend.erasures.failures`, the workspaces it was to erase included, and runs again an hour, four and sixteen hours later. Once the cause is fixed, `npx convex run account:eraseAccountData '{"retryFailed": true}'` runs every kept plan again, and running `account.forget` for the account does too. A kept plan is dropped after 30 days.

## Limits

- **Providers keep what the law makes them keep.** The billing provider keeps anonymized orders as merchant of record. The email provider's sending logs age out on its own schedule.
- **Backups.** A Convex backup taken before the erasure still holds the account until it expires. Restoring one brings the account back, so run the erasure again after a restore ([Back up, restore and roll back](https://nuxt-backend.dev/docs/ship/operate/backup)).
- **Exports** run three a day per account, and each file and zip part lives an hour.
- **The grace period** runs on a call scheduled for its end. A deletion that was asked for stays visible, and its link keeps working, until then; restoring a backup taken during it restores the deletion and its date.
- **Batches** of 200 rows keep each step inside Convex's transaction limits, so a large account takes several scheduled runs.

## Test it

The request itself goes through Better Auth's `/delete-user` route, which the packaged tests of the `auth` capability cover. Your app's tests schedule a deletion from server code:

```ts [backend/account.test.ts]
import { asUser, defineBackendTestApp } from 'nuxt-backend/test'
import { expect, test } from 'vitest'
import { account } from './account'
import { api } from './_generated/api'
import schema from './schema'

const testApp = defineBackendTestApp(schema, import.meta.glob('./**/*.ts'))

test('a deletion waits out the grace period, and the person can keep the account', async () => {
  const t = testApp()
  const ada = await asUser(t, { email: 'ada@example.com' })
  await t.run(ctx => account.scheduleDeletion(ctx, ada.userId))
  const deletion = await ada.query(api.account.getAccountDeletion, {})
  expect(deletion?.deletesAt).toBeGreaterThan(Date.now())
  expect(await ada.mutation(api.account.cancelAccountDeletion, {})).toBe(true)
  expect(await ada.query(api.account.getAccountDeletion, {})).toBeNull()
})
```

## Coming from the current API

Deleting used to erase at once. Now `useAccount().deleteAccount(confirmation)` and `<AccountData>` schedule the deletion, and the erasure runs when the grace period ends. The call, its checks and its refusals are the same, so a page of yours needs no change beyond showing `deletion` and a **Keep my account** button. `<AccountData>`'s `deleted` event is now `scheduled`, and its `kept` event fires when the person keeps the account. Add `getAccountDeletion` and `cancelAccountDeletion` to the exports of `backend/account.ts` (`npx nuxt-backend doctor` names the ones missing; `upgrade` rewrites no code of yours), and for an immediate deletion, as before, call `account.forget` yourself.

## Related

- [Record consents](https://nuxt-backend.dev/docs/build/auth/accounts/consents): the consents the export and the erasure include.
- [Privacy and data inventory](https://nuxt-backend.dev/docs/ship/compliance/privacy): every participant, what it holds and for how long.
- [Manage passkeys and sessions](https://nuxt-backend.dev/docs/build/auth/accounts/security): the rest of `/security`.
- [Require a recent sign-in](https://nuxt-backend.dev/docs/build/auth/access/step-up): the dialog a deletion opens.


## Sitemap

See the full [sitemap](https://nuxt-backend.dev/sitemap.md) for all pages.
