afterbuild/ops
Supabase production-fix runbook

Supabase production fixes — RLS, auth, magic links, realtime, migrations

This is the concrete fix work for a Supabase backend in production: enable row level security with correct per-role policies, repair auth callbacks, magic links, and session refresh, secure realtime subscriptions, tune query performance, and run safe migrations to Supabase. The exact patches, code, and sequence we apply — triage from $299.

By Hyder ShahFounder · Afterbuild LabsLast updated 2026-11-04

What actually breaks in a Supabase backend

Supabase is the default Postgres backend for apps scaffolded by Lovable, Bolt, v0, Cursor, and Claude Code. The tools generate a schema, wire the client, and produce something that runs in a preview. None of that work is wrong per se, but almost all of it is incomplete. The fix concentrates on the five surfaces the code generator skips: row level security, key management, auth configuration, realtime permissions, and migration discipline. This page walks each one with the exact patch.

The pattern is consistent across the Supabase fixes we ship. The scaffolded code speaks SQL, but it does not speak production. Tables are created with RLS off. Service role keys make their way into React components. Auth callbacks point at localhost. Realtime channels subscribe without cleanup and leak rows across users. Edge functions get called on every render. The app looks finished and the founder ships it to paying customers. Then an ordinary bug tips over into a data exposure, and the fix queue starts here.

The symptom that brings most founders here first is the quietest one: insert succeeds but no row appears — a 200 back from the client, an empty array where the row should be, and nothing in the Table Editor. It reads as a broken write and is almost always a policy problem on the read side, which is why it belongs at the top of this list rather than in the debugging section.

AI coding tools are optimizing for a demo that works, not a backend that survives. The remediation tightens the parts the generator never saw — policies that encode who can see what, keys that stay on the right side of the network, and a migrations directory that lets you replay the schema into a new environment without guesswork. Want someone to do the work for you instead of running the runbook yourself? Hire the Supabase expert for AI-built apps.

The 8 RLS mistakes we see in AI-generated Supabase code

Row level security is the Supabase feature that most commonly goes wrong. Here are the eight failure modes to fix first, each with the policy that closes it, ranked by how often they appear in our audits. To write the policies for your own tables, paste your schema into the free Supabase RLS policy generator.

  1. 01
    RLS disabled on tables that hold user data

    Lovable and Bolt create tables and forget to enable row level security. With RLS off, the anon key reads every row from every user. This is the single most common finding in our Supabase audits. It is also the issue behind CVE-2025-48757: Matt Palmer's 2025 scan found inadequate RLS in 170 of 1,645 Lovable projects.

  2. 02
    RLS enabled with no INSERT policy

    The generator enables RLS and writes a select policy, then the app starts throwing error 42501 on every create action. With RLS on and no insert policy, every insert is denied by default. The fix is a three-line insert policy keyed on auth.uid().

  3. 03
    Policies reference the wrong user column

    AI tools pick column names inconsistently: user_id, author_id, owner, created_by. A policy keyed on user_id against a table with author_id silently filters every row. The symptom is an empty array with no error, which is the hardest failure mode to debug.

  4. 04
    Service role key in the client bundle

    The service role key bypasses RLS entirely and must never reach the browser. It turns up regularly in Bolt and Lovable audits, usually inside a component that calls a privileged query. The remediation is rotate, relocate to a server route, and audit git history.

  5. 05
    Policies that evaluate subqueries on every row

    A policy like using (exists (select 1 from memberships where ...)) is correct but slow. Without a matching index, Postgres runs the subquery per row and the endpoint times out at 1000 rows. Add the compound index during the fix.

  6. 06
    Public tables masquerading as private

    A table named public_profiles with RLS off for convenience ends up holding email addresses and tokens because a later prompt added the columns. The fix is a strict partition between public and private schemas, enforced at the column level.

  7. 07
    Storage buckets with no policies

    Supabase Storage has its own RLS layer that AI tools rarely configure. Buckets default to public read in prototypes and leak private file URLs. Write bucket policies per role and confirm signed URLs expire.

  8. 08
    Anon key with INSERT grants on system tables

    Legacy Supabase projects granted the anon role broader SQL privileges than needed. Audit the role with pg_roles and revoke any grant that is not explicitly required for the app.

Broken — RLS off
-- Lovable-generated schema, RLS never enabled
create table todos (
  id uuid primary key default gen_random_uuid(),
  user_id uuid references auth.users(id),
  title text not null,
  done boolean default false
);
-- anon key can select every row
Fixed — RLS plus row-owner policies
alter table todos enable row level security;

create policy "todos_select_own" on todos
  for select using (auth.uid() = user_id);

create policy "todos_insert_own" on todos
  for insert with check (auth.uid() = user_id);

create policy "todos_update_own" on todos
  for update using (auth.uid() = user_id)
  with check (auth.uid() = user_id);

create policy "todos_delete_own" on todos
  for delete using (auth.uid() = user_id);

Auth patterns AI tools miss: callbacks, session refresh, MFA

A Supabase auth fix usually comes down to three gaps. First, OAuth callbacks point at localhost after deploy because the AI tool configured the client redirect but never updated Supabase Site URL or the Google Cloud authorized redirect URIs. Second, session refresh silently fails because the generated client never enables persistSession or handles the TOKEN_REFRESHED event. Third, multi-factor auth, which Supabase supports, is almost never scaffolded because the code generator treats it as optional.

We test a full sign-up, sign-in, sign-out, password reset, and refresh sequence against a staging project before marking auth as fixed. We also add a regression test for the token refresh path, because it is the auth failure that shows up two weeks later when tokens start expiring in production. Our auth specialist covers the same territory for apps built on Clerk or Auth.js.

The other common finding is a broken email flow. Lovable defaults to the built-in Supabase SMTP, which is unauthenticated and lands in spam. Swap in Resend, Postmark, or SendGrid, verify DKIM, SPF, and DMARC, and confirm the password reset email lands in a fresh inbox before closing the ticket.

Supabase magic link not working: symptom, cause, fix

A Supabase magic link fails for one of four reasons: the redirect URL is not on the allow list, the Site URL still points at localhost, an email scanner opened the link first, or the app runs the PKCE flow while the email template still sends the default link. Supabase magic links expire after 1 hour by default, work once, and can be requested once every 60 seconds, so a link that was already opened fails even when it is minutes old.

Start in Authentication, URL Configuration. The Site URL is the default redirect when the code passes no redirectTo, and Supabase calls it critical for email confirmations and password resets. Every redirectTo the app sends has to match an entry in Redirect URLs. Wildcards cover Vercel previews, for example https://*-your-team.vercel.app/**, but Supabase recommends the exact path for production.

Email scanners are the cause founders find last. Some providers prefetch links in incoming mail, which uses up the one-time link before the user clicks and leaves them with "Token has expired or is invalid". Supabase documents two ways out: send a code with {{ .Token }} and verify it with verifyOtp, or link to your own page with a button that confirms the sign-in.

SymptomLikely causeFix
Link lands on localhost:3000 after deploySite URL never changed from the local defaultSet Site URL to the production domain in URL Configuration
Link lands on the home page, not the callbackredirectTo is not on the Redirect URLs allow listAdd the exact callback path, plus a wildcard for preview deploys
"Token has expired or is invalid" on first clickAn email scanner prefetched the one-time linkSend a {{ .Token }} code, or link to a confirm page with a button
Link fails after an hourDefault 1 hour expiryRequest a new link; keep the expiry under one day
Session missing after the link on Next.jsPKCE flow, but the template sends the default ConfirmationURLSend {{ .TokenHash }} to a server route that calls verifyOtp
Users signed out at randomRefresh token reused outside the 10 second windowLet one client own the refresh; refresh in middleware

PKCE flow vs implicit flow

In the implicit flow the session arrives in the URL fragment and the browser client picks it up. Server-rendered Next.js apps built with @supabase/ssr use PKCE, and there Supabase tells you to edit the Magic Link email template to send a token hash. The link goes to your own route, which reads token_hash and type and calls verifyOtp to set the session cookie.

Magic Link email template (PKCE)
<h2>Your sign-in link</h2>
<p>
  <a href="{{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=email">
    Log in
  </a>
</p>
<!-- fallback for inboxes that prefetch links -->
<p>Or enter this code: {{ .Token }}</p>
app/auth/confirm/route.ts
import { type EmailOtpType } from '@supabase/supabase-js';
import { NextResponse, type NextRequest } from 'next/server';
import { createClient } from '@/utils/supabase/server';

export async function GET(request: NextRequest) {
  const url = new URL(request.url);
  const token_hash = url.searchParams.get('token_hash');
  const type = url.searchParams.get('type') as EmailOtpType | null;
  const next = url.searchParams.get('next') ?? '/';
  // only same-site paths, never //evil.com
  const safeNext = next.startsWith('/') && !next.startsWith('//') ? next : '/';

  if (token_hash && type) {
    const supabase = await createClient();
    const { error } = await supabase.auth.verifyOtp({ type, token_hash });
    if (!error) return NextResponse.redirect(new URL(safeNext, url.origin));
  }
  return NextResponse.redirect(new URL('/auth/error', url.origin));
}

Supabase custom domains and refresh token errors

A Supabase custom domain puts auth on your own subdomain, such as api.example.com, instead of the project's supabase.co host. It is a paid add-on for projects on a paid plan, and only subdomains are supported. The setup is a CNAME to the project host, an _acme-challenge TXT record to prove ownership, then supabase domains reverify and supabase domains activate. Certificate issuance can take up to 30 minutes. Supabase Auth uses the custom domain as soon as it is active, so add the new callback URL in each OAuth provider's console before you activate, and keep the old one.

Supabase refresh token errors usually come from reuse. Refresh tokens never expire but can only be used once, with a 10 second reuse window by default. Outside that window Supabase treats a second use as a stolen token, ends the session, and revokes every refresh token in it. The trigger in AI-built apps is two clients refreshing the same session: a browser client and a server client, several open tabs, or a retry loop. Let one place own the refresh, which in Next.js means the middleware that refreshes the session on each request, and keep the access token at the default 1 hour expiry.

Fixes inside Lovable, Bolt and Next.js apps

In Lovable and Bolt the auth settings live in the Supabase dashboard, not in the generated code, so the code can look right while the Site URL still points at the preview host. Check URL Configuration after every new domain. If the project was never linked properly, start with our guide on how to connect Supabase to Lovable. In Next.js, keep one server client helper, one browser client helper, and the confirm route above, and delete any second auth listener an AI prompt added.

When auth bugs point to a bigger security problem

A broken magic link is often the first visible sign of a backend nobody hardened. If the same app throws new row violates row-level security policy errors, or has tables with RLS off, fix the policies before the login screen. When the list keeps growing, that is a prototype-to-production job rather than a single bug. Auth still broken? Get Emergency Triage for $299.

Realtime subscription security

Supabase Realtime broadcasts Postgres changes over WebSockets. It respects RLS on the underlying table, which means a subscription without RLS is a data leak. The AI-generated pattern is predictable: a useEffect that calls supabase.channel(...).on(...).subscribe(), a table with RLS disabled for convenience, and no cleanup function. Every connected browser receives every insert across every user.

A Supabase realtime debugging pass does three things. First, confirm RLS is enabled on every table in the realtime publication. Second, scope the publication with alter publication supabase_realtime set table (...) to list only the tables the app actually needs. Third, audit every subscribe call and add a removeChannel cleanup in the effect return. We grep for .subscribe() during the audit and log any call without matching cleanup.

The cost of a missing cleanup compounds. After a few route changes the app holds dozens of dead WebSocket listeners, memory climbs, and Supabase throttles the connection. Users see a subtle slowdown followed by a hard reconnect storm. Fixing it is two lines, but the lines are never there.

Edge functions and server-side keys

A Supabase edge functions fix usually starts with a single question: why is the service role key in the browser? The honest answer, most of the time, is that the AI tool copied the Supabase docs example verbatim and pasted it into a client component. The service role key bypasses RLS. If it lands in a React file, every visitor has database-admin rights. We rotate the key, relocate the query, and audit the build output to confirm nothing leaked.

Edge functions are the right home for privileged database work. We wrap the operation in a Supabase edge function, authenticate the caller, validate input, and return a minimal payload. For anything that needs to persist across requests — Stripe webhooks, cron work, background jobs — we reach for a dedicated queue rather than relying on the edge runtime. See our Stripe integration developer hub for the webhook patterns that pair with edge functions.

A common anti-pattern is an edge function that reinvokes a chatty Supabase client on every call. The function spins up, connects, runs one query, and returns, which doubles the latency the client would have seen. We consolidate reads into a single query, cache where safe, and set sensible timeouts.

Broken — service role shipped to browser
// app/components/AdminPanel.tsx
'use client';
import { createClient } from '@supabase/supabase-js';

const supabase = createClient(
  process.env.NEXT_PUBLIC_SUPABASE_URL!,
  process.env.NEXT_PUBLIC_SERVICE_ROLE_KEY! // leaks to bundle
);

export function AdminPanel() {
  // any visitor has DB admin rights
  const run = () => supabase.from('users').delete().neq('id', '0');
  return <button onClick={run}>Purge</button>;
}
Fixed — service role confined to server route
// app/api/admin/purge/route.ts (server only)
import { createClient } from '@supabase/supabase-js';

export async function POST(req: Request) {
  const auth = req.headers.get('authorization');
  if (!isAdmin(auth)) return new Response('forbidden', { status: 403 });

  const admin = createClient(
    process.env.SUPABASE_URL!,
    process.env.SUPABASE_SERVICE_ROLE_KEY! // server env, no NEXT_PUBLIC
  );
  await admin.from('users').delete().neq('id', '0');
  return new Response('ok');
}

Migration safety and schema management

AI-generated apps rarely have a migrations directory. Changes are made in the Supabase dashboard, captured nowhere, and impossible to replay. The first time something breaks in production, there is no way to reproduce the schema in staging. A Supabase rescue therefore always includes a migrations pass: pull the current schema with supabase db diff, commit the output into migrations/, and run supabase db reset against a branch project to prove the migrations replay cleanly.

From that point forward, schema changes go through pull requests. Supabase branching lets you spin up per-PR databases that run the new migrations automatically, which means reviewers can exercise the schema before it touches production. We also wire a GitHub Action that runs supabase db lint and blocks merges that introduce destructive changes without a down migration. This is the baseline every production Supabase app needs.

The Supabase production-fix runbook, in order

Every Supabase fix follows the same six-step sequence. Run it yourself from the steps below, or have us run it — we reply within 24 business hours and the written diagnostic lands in 48.

  1. 01
    Enable RLS on every user-data table

    Run alter table <name> enable row level security on every table that holds anything a user owns. Without RLS, policies do not apply and the anon key grants broad access to every row.

  2. 02
    Write select, insert, update, and delete policies

    Author per-role policies keyed on auth.uid(). Test them with a signed-in user, a different signed-in user, and an unauthenticated session before merging.

  3. 03
    Move service role calls behind a server route

    Grep the codebase for SUPABASE_SERVICE_ROLE_KEY and relocate every hit into an API route or edge function. Rotate the key once the client side is clean.

  4. 04
    Harden the auth configuration

    Turn on email confirmation, set JWT expiry to one hour, enable refresh token rotation, and lock the redirect URL allowlist to production domains.

  5. 05
    Audit realtime subscriptions and edge functions

    Confirm RLS covers realtime publications, add removeChannel cleanup to every subscribe, and set function timeouts and retry limits for edge functions.

  6. 06
    Commit migrations and run a staging replay

    Capture the current schema with supabase migration new, commit to git, and run supabase db reset on a branch project to prove the schema reproduces.

When to migrate off Supabase (rare)

Most Supabase problems are configuration problems, not platform problems. The right move is almost always to fix the RLS, relocate the service role key, and ship a migrations directory — not to migrate off. That said, there are three cases where a migration makes sense. First, a regulated workload (HIPAA, strict PCI) where a dedicated, audited Postgres cluster is required. Second, a mature product whose auth, storage, and realtime needs have grown beyond the Supabase defaults. Third, a team whose DBA expertise is the bottleneck and a managed Postgres with pgbouncer is a better fit.

If a migration is warranted we plan the cutover with care — Supabase Auth user export, RLS rewritten as middleware, storage relocated, and realtime rebuilt on your own WebSockets or on Ably or Pusher. See our app migration service for the full process. In most of the Supabase conversations we have, the right answer is a rescue, not a migration.

DIY vs Afterbuild Labs vs hiring a Supabase specialist

Three paths to a hardened Supabase stack. Pick based on budget, timeline, and how much risk you can carry.

DimensionDIY with AI toolAfterbuild LabsHire Supabase specialist
TurnaroundIndefinite — regression loops48h diagnostic, 2-5 days fix2-6 weeks to start
Fixed priceNo — per-credit billingYes — from $299Hourly, varies by contractor
RLS policy coveragePartial, often wrongEvery table auditedDepends on contractor
Service role key auditUsually missedGrep plus rotationIncluded if requested
Production deploy checklistNot provided10-point passCustom, variable
Migration history in gitRareCaptured and committedUsually included
Post-delivery supportNoneWarranty plus retainerContractor-dependent
FAQ

Supabase production fixes — FAQs

Should I turn Supabase Row Level Security on or off?+

Always on for any table that holds user data. Supabase creates new tables with RLS available but disabled by default, and the anon key ships with broad access. With RLS off, every browser can read and write every row. Turn RLS on with a single alter table command, then write per-role policies for select, insert, update, and delete. A focused fix can harden a typical schema in under a day.

When should I use the anon key versus the service role key?+

The anon key is safe in the browser only when every table has RLS enabled and correct policies. The service role key bypasses RLS entirely and must never reach client code. Use it only inside server routes, edge functions, or background workers. If an AI tool placed the service role key in a React component, rotate it immediately, move the logic behind an API route, and audit the git history for accidental commits.

Why is Supabase auth not verifying emails in my Lovable app?+

Lovable and Bolt frequently ship with email confirmation disabled and the default SMTP provider, which lands verification emails in spam. The fix is three settings: enable email confirmation in the Supabase auth config, plug in a real provider like Resend or Postmark, and verify DKIM, SPF, and DMARC on your sending domain. We also set the redirect URL allowlist so magic links only redirect to approved domains.

Why is my Supabase magic link not working?+

The usual causes are a redirectTo URL that is missing from the Redirect URLs allow list, a Site URL still set to localhost, an email security scanner that opens the link before the user does, or a PKCE app whose email template still sends the default confirmation link. A prefetched link fails with "Token has expired or is invalid". Fix the allow list first, then send a token hash or a six-digit code instead of the raw link.

How long is a Supabase magic link valid?+

Supabase magic links expire after 1 hour by default, and a user can request a new one once every 60 seconds. You can change the expiry in the email provider settings, but Supabase strongly discourages anything longer than 86,400 seconds (one day). Each link works once, so a link opened by a scanner or a second tab is already used.

How do I set a custom domain for Supabase auth?+

Custom domains are a paid add-on for projects on a paid plan, and only subdomains such as api.example.com are supported. Add a CNAME to your project's supabase.co host, add the _acme-challenge TXT record Supabase returns, then run supabase domains reverify and supabase domains activate. Auth switches to the custom domain at once, so add the new callback URL in each OAuth provider's console and keep the old one too.

Why does my Supabase refresh token keep failing?+

Supabase refresh tokens never expire but can only be used once, with a 10 second reuse window by default. When two tabs, a server component and a browser client, or a retry loop all refresh with the same token outside that window, Supabase treats it as reuse, ends the session and revokes every refresh token in it. Let one client own the refresh, and in Next.js refresh the session in middleware.

How do realtime subscription permissions work in Supabase?+

Realtime Postgres Changes respects RLS on the underlying table, but you still need to enable the realtime publication and confirm policies allow select for the subscribing role. AI tools often subscribe from the browser with the anon key and no RLS, which broadcasts every insert to every connected client. Add RLS, scope the publication to specific tables, and make sure each subscription unsubscribes on unmount.

How much do Supabase edge functions cost in production?+

Supabase edge functions bill on invocations. Per the Supabase edge function pricing page (checked 4 November 2026), the Free plan includes 500,000 invocations a month, the Pro plan includes 2 million, and usage beyond the quota costs $2 per 1 million invocations. The bigger cost risk is pairing edge functions with a chatty client that re-invokes on every render — we fix that pattern during the audit.

How do I migrate from Supabase to plain Postgres?+

Supabase runs on vanilla Postgres, so data migration is a pg_dump and pg_restore away. What you lose is auth, storage, realtime, and RLS enforced at the client boundary — those are Supabase services, not Postgres features. Before migrating, honestly answer why: most teams we talk to wanted a DBA, not a migration. If Supabase itself is the blocker we plan a cutover and rebuild auth on Auth.js or Clerk.

How do I configure Supabase environment variables on Vercel?+

Set NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY on Vercel for every environment — preview, production, and development. Set SUPABASE_SERVICE_ROLE_KEY as a plain server variable, never NEXT_PUBLIC. Preview deploys should use a separate Supabase project or a branch database so preview traffic does not mutate production data. A common failure is forgetting to set preview env vars and seeing silent nulls.

What is a typical timeline for a Supabase rescue?+

A scoped Supabase fix runs two to five business days from $299 for triage. Work includes enabling RLS on user-data tables, writing per-role policies, moving service_role calls off the client, hardening auth settings, and shipping a migrations directory checked into git. Larger rescues that cover realtime, edge functions, and Stripe webhooks scale to two weeks. We send a written diagnostic within 48 hours so you know the scope before you commit.

Next step

Ship the Supabase production fixes on your repo this week.

Send the repo and your Supabase project ref. A written diagnostic lands in 48 hours, the fixed-price fix ships in two to five days — every RLS policy, auth callback, and realtime subscription made production-safe. Prefer to scope a longer engagement and hire dedicated help? Start at the Supabase expert hub instead.

Sources

Prices and plans checked 4 November 2026.