All jobs

Add Account Deletion to a Next.js and Prisma App

Yes. An agent adds a DELETE route and a confirm dialog that remove a user's posts, accounts, sessions and Stripe subscription in one transaction, then opens a PR.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent reads what a user owns before writing the route that removes them, because the schema and the database disagree about what happens on delete. In an app laid out like shadcn-ui/taxonomy, prisma/schema.prisma gives User relations to Account and Session with onDelete: Cascade, and Post points at its author with no action, which the first migration turned into ON DELETE RESTRICT. But prisma/migrations/20221118173244_add_stripe_columns/migration.sql then drops all three foreign keys for PlanetScale, so in the database nothing cascades and nothing restricts: db.user.delete would succeed and leave orphaned posts, OAuth rows holding GitHub tokens, and sessions. The user also carries stripeCustomerId, stripeSubscriptionId, stripePriceId and stripeCurrentPeriodEnd, kept current by app/api/webhooks/stripe/route.ts on checkout.session.completed and invoice.payment_succeeded, and VerificationToken rows are keyed by the email as identifier.

Today there is no way to delete anything but a post. app/api/users/[userId]/route.ts exports only PATCH, which reads the session with getServerSession(authOptions), returns 403 unless params.userId equals session.user.id, and updates name. app/(dashboard)/dashboard/settings/page.tsx renders one card, UserNameForm, and components/user-account-nav.tsx offers Sign out through signOut({ callbackUrl }). components/post-operations.tsx already shows the shape of a destructive action in this codebase: a fetch with method: "DELETE", an AlertDialog from components/ui/, a toast on failure and router.refresh() on success.

The agent adds DELETE to the users route with the same 403 check, and a deleteAccount(userId) function in lib/ that does the work in db.$transaction: delete posts where authorId is the user, accounts and sessions where userId is the user, verification tokens where identifier is the user's email, then the user. Before the transaction, if stripeSubscriptionId is set, it cancels the subscription through the Stripe client in lib/stripe.ts so the customer is not billed for a user who no longer exists, and it does that first because a cancelled subscription with a deleted user is recoverable and the reverse is not. A DeleteAccountCard on the settings page, built from the dialog pieces post-operations.tsx uses, asks for confirmation, calls the route, and on 204 calls signOut with the login page as callbackUrl, since sessions are JWTs (session.strategy: "jwt" in lib/auth.ts) and the cookie outlives the row.

Proof is a database and a script, since the repository has no test suite. In its sandbox the agent starts MySQL in a container, runs pnpm install and prisma migrate deploy, seeds one user with two posts, an account, a session and a verification token, calls deleteAccount and counts every table before and after, quoting both. It runs pnpm lint and the TypeScript compiler with --noEmit, the two checks the repository has, and leaves the Stripe call behind a check for the id so a user who never subscribed makes no API call.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Add account deletion to this Next.js and Prisma app. Read prisma/schema.prisma, every file under prisma/migrations, app/api/users/[userId]/route.ts, app/api/posts/[postId]/route.ts, components/post-operations.tsx, app/(dashboard)/dashboard/settings/page.tsx, lib/auth.ts, lib/stripe.ts, lib/subscription.ts and app/api/webhooks/stripe/route.ts first. Add a DELETE handler to the users route with the same session check PATCH has. Put the work in a lib function that runs one db.$transaction deleting the user's posts, accounts, sessions, verification tokens by email, then the user; do not rely on cascades, because the second migration dropped the foreign keys. Cancel the user's Stripe subscription first when stripeSubscriptionId is set. Add a confirm card to the settings page built from the AlertDialog pattern in post-operations.tsx that calls the route and then signs out. Start a MySQL container, run pnpm install and prisma migrate deploy, seed a user with posts, an account, a session and a verification token, run the function and quote the row counts before and after. Run pnpm lint and tsc --noEmit. Open a pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
  1. Get an API key. In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
  2. Send the request. POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
  3. Read what came back. Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

What comes back

What comes back is a pull request that adds a DELETE export to app/api/users/[userId]/route.ts, a lib/ function with the transaction, a settings card component, and one line in the settings page that renders it; prisma/schema.prisma is untouched. The description lists the five tables the transaction touches in order, quotes the row counts from the seeded run going to zero for that user and unchanged for every other row, and quotes pnpm lint and the type check.

The run's record keeps the seed, the deletion and the counts, so a reviewer can see that a second user's posts survived and that the Stripe call was skipped for a user with no subscription id.

Before merging, a reviewer decides what the product promises: whether deletion is immediate or scheduled with a grace period, and whether the Stripe customer object should be deleted as well as the subscription cancelled, which the pull request leaves to a one-line change beside the cancel.

Run it on every deletion request

Once the route exists, requests still arrive by email and support ticket rather than by button. A handler on the reader's server that receives those tickets, from a help desk webhook or a form, calls POST /o/{org}/sessions with a prompt asking the agent to find the user by the email in the ticket, confirm it matches one row, call deleteAccount through a maintenance script in the repository, and report the counts. The handler sends a request_id that is a UUID v5 of the ticket id, so a redelivered webhook returns the run already started instead of running the deletion twice.

Each run reads the database through a connection the Project names, never a credential pasted into the prompt, and ends with a short report the support agent pastes back into the ticket: the email, the number of posts removed, and whether a subscription was cancelled. A ticket that names an email with no row produces a report saying so and no deletion.

The use case this job follows, with its automation and trigger: Hand off a long task.

Why run it on Rush?

Account deletion is where a schema's assumptions get tested: the model says cascade, the database says nothing of the kind, and a route written from the schema alone would leave tokens behind. In a Rush sandbox the agent reads the migrations as well as the schema, writes the transaction the database actually needs, and proves it on a seeded MySQL with counts before and after, all in the record.

The pull request carries the proof script, the lint and type check output, and the open product decisions named, so the reviewer spends their time on policy rather than on checking whether sessions were deleted. Across every Prisma app a team keeps, the job runs in parallel, one sandbox and one pull request each, each transaction shaped by that app's own models.

Frequently asked questions

Why not rely on onDelete: Cascade?

Because the database no longer has the constraints. The second migration dropped the foreign keys on accounts, posts and sessions, and the schema does not set relationMode = "prisma", so the client does not emulate the cascade either. Explicit deletes in one transaction are the only path that removes everything.

Does the signed-in user stay signed in after deleting?

The JWT cookie survives the row, which is why the card calls signOut right after a 204. The jwt callback in lib/auth.ts already returns the token unchanged when no user row matches its email, so a stale cookie that reaches the server again carries no database identity.

What happens to the Stripe customer?

The subscription is cancelled so billing stops; the customer object stays in Stripe with its invoice history, which most teams want to keep for accounting. Deleting the customer too is one more call beside the cancel, and the pull request names it as the reviewer's choice.

Can another user delete someone's account?

No. The DELETE handler keeps the check PATCH already has: the session's user id must equal the route's userId, or the answer is 403 before anything is read.

More Prisma jobs

The same job on other stacks

Keep reading