Developer cleaning up spaghetti code in an editor

Soft Delete, Audit Logs, and Admin Actions: Prompts for Safer Backends

Soft delete, audit logs, and admin actions are the backend hygiene layer AI codegen skips because they do not show up in a demo screenshot. Hard deletes lose customer support data. Missing audit trails make “who changed this subscription?” unanswerable. Admin panels without guardrails let any logged-in user impersonate god mode. Below are numbered prompts for Cursor, Claude Code, and Aider that add safer patterns in merge-sized chunks — schema first, queries second, UI last. Updated December 2026.

Database schema diagram showing soft delete columns and audit log tables for a vibe-coded SaaS backend
Soft delete and audit logs belong in the schema before the admin UI — not as a Friday panic patch.

Pair these prompts with security checklist for AI-generated apps and multi-tenant basics for vibe-coded SaaS. If you use Prisma or Supabase migrations, read database migrations with AI before running destructive schema prompts.

Table of contents

  1. Why safer backends matter after vibe coding
  2. How to use these prompts
  3. Soft delete prompts (1–6)
  4. Audit log prompts (7–12)
  5. Admin action prompts (13–18)
  6. Hardening and testing (19–22)
  7. Anti-patterns every prompt should forbid
  8. FAQ

Why safer backends matter after vibe coding

AI agents optimize for “make the delete button work.” They add DELETE FROM users and move on. In production, support needs to restore a mistaken deletion. Compliance asks who exported a customer list. A curious user discovers /admin because middleware only checked login, not role. These are not edge cases — they are week-two incidents for any SaaS that got real users.

Soft delete keeps rows with deleted_at timestamps so queries filter active records while history remains recoverable. Audit logs append immutable events: actor, action, target, metadata, timestamp. Admin actions wrap dangerous operations in role checks, confirmation, and logging. Together they turn a vibe-coded CRUD app into something you can operate without fear.

PatternWhat breaks without itMinimum viable fix
Soft deleteAccidental data loss; broken foreign keysdeleted_at column + default scope
Audit logNo accountability; support blindAppend-only audit_events table
Admin RBACAny user hits admin routesRole enum + middleware guard
Impersonation auditSupport abuse untrackedLog start/stop with reason

How to use these prompts

Run one prompt per branch. Replace bracketed placeholders with your table names and paths. Append this block to every prompt:

Do not hard-delete user-owned rows in application code. Do not expose admin routes without role checks. Write audit events in the same transaction as the mutation when possible. Never log passwords, tokens, or full payment objects.

Stack assumed: Next.js App Router, TypeScript, Postgres via Prisma or Supabase, existing auth with user id available server-side.

Soft delete prompts (1–6)

1. Add deleted_at TIMESTAMPTZ nullable column to [projects, tasks, documents] tables via migration. Index deleted_at where null for active-row queries. Document that hard DELETE is forbidden in app layer.

2. Create shared query helper or Prisma middleware that automatically adds WHERE deleted_at IS NULL to findMany/findFirst for soft-deletable models. Expose explicit withDeleted() for admin-only queries.

3. Replace DELETE API routes for [resource] with PATCH setting deleted_at = now() and updated_at = now(). Return 204. Verify RLS or auth checks still apply to soft-deleted rows (owner cannot read deleted unless restore flow exists).

4. Add POST /api/[resource]/[id]/restore admin-only route that sets deleted_at = null when row exists and caller has admin role. Audit log entry action=restore.

5. Add scheduled job or Supabase cron placeholder that hard-purges rows where deleted_at older than 90 days — configurable retention env. Exclude tables with legal hold flag.

6. Update all list endpoints and React queries to exclude soft-deleted by default. Add integration test: delete resource, assert 404 on GET, assert row still exists in DB with deleted_at set.
Code editor showing soft delete middleware and audit log insert in a TypeScript API route
Prompts 1–6 establish schema and query defaults — run them before building admin restore UI.

Audit log prompts (7–12)

7. Create audit_events table: id uuid, actor_user_id uuid FK, action text, target_type text, target_id text, metadata jsonb, ip inet nullable, created_at timestamptz default now(). No UPDATE or DELETE policies for app roles — append only.

8. Implement logAuditEvent({ actorId, action, targetType, targetId, metadata }) server helper using service role or privileged DB connection. Call from API routes after successful mutations.

9. Log these actions minimum: user.login, user.role_change, subscription.change, project.delete, project.restore, admin.impersonation_start, admin.impersonation_end, export.csv_download.

10. Add GET /api/admin/audit-events paginated with filters action, actor, date range. Admin role only. Return metadata redacted — no raw Stripe objects or emails in list view unless admin policy allows.

11. Wire audit log insert into existing Stripe webhook handlers when subscription status changes — metadata includes stripe_event_id and previous_status, new_status.

12. Add test: perform role change as admin, assert audit_events row exists with correct actor and target. Perform same as non-admin, assert 403 and no audit row for failed attempt (optional failed_attempt log).

Admin action prompts (13–18)

13. Add users.role enum column values user, admin, support. Migration default user. Seed one admin via script documented in README — not in client bundle.

14. Create requireAdmin() server helper and apply to all /api/admin/* routes and server actions. Return 403 JSON consistent shape. Do not rely on hiding sidebar links alone.

15. Build /admin/users page listing users with search by email, role badge, last login. Admin only. Actions: change role (dropdown), soft-disable account (deleted_at or banned_at column). Confirm modal before destructive admin actions.

16. Implement support impersonation: POST /api/admin/impersonate/[userId] sets httpOnly session flag or short-lived JWT claim impersonated_by_admin_id. Banner in UI "Viewing as [email] — Exit". logAuditEvent on start and exit.

17. Add admin bulk export CSV for [resource] with rate limit 1 per hour per admin. Stream response; log export in audit_events with row count in metadata.

18. Admin dashboard cards: active users 7d, failed payments 24h, recent audit events 10 rows. Read-only aggregates — no raw SQL console in production UI.

Hardening and testing (19–22)

19. Security pass: grep codebase for .delete( and DELETE FROM — replace with soft delete pattern or document exceptions in SECURITY.md. List findings in PR description.

20. Add Playwright or API test: non-admin GET /api/admin/audit-events returns 403. Admin returns 200 with pagination shape.

21. Document runbook ADMIN.md: how to restore deleted project, how to rotate admin, how to investigate audit trail for billing dispute. AI-generated runbooks welcome — human review required.

22. Align with rate limiting guide: apply stricter limits on /api/admin/* and impersonation routes. Reference rate-limiting-abuse-protection-ai-apis patterns in comments.

Anti-patterns every prompt should forbid

  • Client-side role checks without server enforcement
  • Audit logs stored in CloudWatch only with no query UI for support
  • Soft delete without unique constraint strategy — emails reusable while old row exists
  • Admin routes under predictable /admin with no MFA for production operators
  • Logging PII in metadata jsonb without retention policy

Soft delete plus audit logs do not replace backups. Schedule Postgres backups in Supabase or your host before you trust restore prompts. Admin actions without MFA on the operator account are theater — add MFA to admin Google or GitHub login at minimum.

Operating soft-deleted data in support workflows

Support will ask to “undo delete” within minutes. Train the restore flow before launch: admin searches user email, opens deleted projects tab (add this view in prompt 15 extension), clicks restore, verifies audit row. Without UI, support runs SQL — that does not scale and bypasses audit if not careful.

Unique fields like email need strategy: either block re-registration while soft-deleted row holds email, or anonymize email on delete (deleted+{id}@invalid.local) while retaining row for FK integrity. Prompt your agent explicitly — AI picks hard delete to “free the email” and breaks orders history.

Prisma middleware for soft delete defaults

If you use Prisma, middleware can enforce soft delete at the ORM layer so agents cannot accidentally call hard delete without bypassing the client. Prompt: “Add Prisma middleware on User, Project, Task models: convert delete to update deleted_at; convert findMany/findFirst to filter deleted_at null unless ctx.withDeleted.” Document bypass for admin scripts only via raw query flag in CLAUDE.md.

Middleware pitfalls: raw prisma.$executeRaw skips middleware — grep for raw SQL after agent sessions. Cascade behavior: soft-deleting parent should soft-delete children or block with FK — AI often hard-deletes children. Define policy in prompt before migration.

Supabase RLS for audit_events

audit_events should be INSERT-only for application role. Example policy pattern: authenticated users cannot SELECT audit_events unless role admin in profiles table. Service role inserts from API routes. Never expose audit insert to client SDK — attackers flood logs or hide actions.

For Supabase Edge Functions handling admin tasks, use service role key in function env only. Log from function after mutation succeeds. Cross-reference rate limiting on admin export endpoints — CSV export is a data exfiltration vector when RBAC is loose.

Support playbooks tied to audit data

Train support to search audit_events by target_id when user disputes billing change. UI filter by action type reduces noise. Retention: keep audit rows 1–2 years minimum for B2B; archive to cold storage if table grows past comfort. Prompt for monthly aggregate job: count admin actions per operator — anomaly detection for compromised admin account.

Recommended merge order for prompts 1–22

  1. Week 1: prompts 1, 7, 13 — schema foundation
  2. Week 2: prompts 2–5, 8–9 — query behavior and core logging
  3. Week 3: prompts 14–18 — admin UI and impersonation
  4. Week 4: prompts 19–22 — tests, docs, rate limits

Skipping straight to admin dashboard before soft delete exists invites restore bugs — users “delete” projects that hard-delete because API predates middleware.

Additional admin prompts (23–26)

23. Add banned_at TIMESTAMPTZ nullable on users. Admin can ban without delete. Banned users get 403 on all API routes with message account_suspended. Audit log action=user.ban.

24. Create admin_notes table: id, target_user_id, author_admin_id, body text, created_at. Admin-only CRUD. Display on admin user detail page — support context without editing user row.

25. Add two-person rule placeholder for role elevation: admin cannot self-promote; second admin approval stored as pending_role_changes table — implement UI stub and audit log only if full flow too large for one PR.

26. Generate SECURITY-ADMIN.md documenting all /api/admin routes, required roles, and audit actions — update when new admin endpoints added.

These four prompts close common gaps after the core 22 — ban flow, support notes, elevation guardrails, and living documentation agents forget to maintain.

FAQ

Should I soft delete everything?

User-generated content and billing-related rows: yes. High-churn telemetry or session tokens: hard delete with retention job. Junction tables can hard delete if parent soft delete cascades logically in queries.

Prisma or Supabase for audit logs?

Either works. Supabase RLS can deny UPDATE/DELETE on audit_events for anon/authenticated roles while service role inserts. Prisma: use raw SQL or separate DB user with INSERT-only grants for paranoia.

How long keep soft-deleted rows?

30–90 days default for B2B SaaS; legal may require longer. Document in privacy policy. Purge job must also remove associated storage files.

Is impersonation safe?

Only for support with audit trail, time limits, and visible banner. Never impersonate for casual debugging. Some teams ban impersonation and use read-only support views instead.

Do audit logs need GDPR consideration?

Yes — actor and target ids are personal data. Define retention, allow export on user request where applicable, and restrict access to admin roles with logged access to the audit UI itself for sensitive deployments.

Soft CTA: Run prompts 1, 7, and 13 on your main entity this week — soft delete column, audit_events table, admin role enum. Ship the migration before the admin UI. Safer backends are a sequence, not a single heroic prompt. Continue with Sentry error monitoring so you see what breaks after operators start clicking restore.

Leave a Reply

Your email address will not be published. Required fields are marked *