← All guides

How to Gate Paid Features with Stripe Subscriptions Securely (Next.js and Supabase)

Updated 2026-11-10

Short answer: never decide whether someone has paid from client-side state, the ?success=true redirect after Checkout, localStorage, or a is_pro column users can update on their own profiles row. Store subscription status in a table that only your server writes, update it from verified Stripe webhooks (checkout.session.completed, customer.subscription.updated, customer.subscription.deleted), and check that status on the server or in RLS before returning premium data or running premium actions. Hiding a button in React is not a paywall.

This is one of the most common ways AI-built SaaS apps from Lovable, Bolt, v0, Cursor and Replit lose money. The upgrade flow works, Stripe charges the card, and the app shows the Pro badge. But the check that matters runs in the browser, so anyone who opens the developer console gets Pro for free.

Four ways paywalls get bypassed

1. Trusting the success redirect

Generated code often marks the user as paid when they land on the success page:

// VULNERABLE: anyone can visit /billing/success?session_id=anything
useEffect(() => {
  if (searchParams.get("success")) {
    supabase.from("profiles").update({ plan: "pro" }).eq("id", user.id);
  }
}, []);

Visiting that URL directly, without paying, upgrades the account. It also only works if the browser makes that call, so a closed tab means a paying customer who never gets upgraded.

2. A plan column users can write

Even without the redirect bug, if profiles.plan or profiles.is_pro is updatable by the row owner, the user can run this from the console with your public anon key:

await supabase.from("profiles").update({ is_pro: true }).eq("id", myId);

A typical "users can update their own profile" RLS policy allows exactly that. The same problem applies to roles, which we cover in admin roles and user_metadata.

3. Checking the plan only in the UI

{profile.plan === "pro" ? <ExportButton /> : <UpgradePrompt />}

If the /api/export route or the Supabase table behind it doesn't check the plan too, users just call it directly.

4. Trusting prices or plan IDs from the browser

If your checkout route accepts a price or amount from the request body, users can pay $1 for your $99 plan. See Stripe Checkout price tampering for the fix.

The secure pattern

  1. Checkout is created on the server with a fixed price ID and the signed-in user's ID attached.
  2. Stripe sends webhooks to your server, which verifies the signature.
  3. The webhook handler writes subscription status into a table users cannot write.
  4. Every premium API route, server action or RLS policy reads that table.

Step 1: A subscriptions table users can only read

create table public.subscriptions (
  user_id uuid primary key references auth.users(id) on delete cascade,
  stripe_customer_id text unique,
  stripe_subscription_id text unique,
  status text not null,            -- active, trialing, past_due, canceled, ...
  price_id text,
  current_period_end timestamptz,
  updated_at timestamptz default now()
);

alter table public.subscriptions enable row level security;

create policy "read own subscription"
  on public.subscriptions for select
  to authenticated
  using ((select auth.uid()) = user_id);

-- No insert, update or delete policies: only the service role writes here.

If you already have is_pro on profiles, move it here, or at least make sure the column is excluded from what users can update. Postgres column privileges can do that (revoke update (is_pro) on public.profiles from authenticated;), but a separate table is easier to reason about.

Step 2: Create Checkout on the server

// app/api/checkout/route.ts
import Stripe from "stripe";
import { createClient } from "@/lib/supabase/server";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

export async function POST() {
  const supabase = await createClient();
  const { data: { user } } = await supabase.auth.getUser();
  if (!user) return new Response("Unauthorized", { status: 401 });

  const session = await stripe.checkout.sessions.create({
    mode: "subscription",
    line_items: [{ price: process.env.STRIPE_PRO_PRICE_ID!, quantity: 1 }],
    client_reference_id: user.id,
    subscription_data: { metadata: { user_id: user.id } },
    success_url: `${process.env.APP_URL}/billing/success`,
    cancel_url: `${process.env.APP_URL}/pricing`,
  });

  return Response.json({ url: session.url });
}

The user ID comes from getUser() on the server, not from the request body. Here's why getUser and not getSession.

Step 3: Update status from verified webhooks

// app/api/stripe/webhook/route.ts
import Stripe from "stripe";
import { createClient } from "@supabase/supabase-js";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
const admin = createClient(
  process.env.NEXT_PUBLIC_SUPABASE_URL!,
  process.env.SUPABASE_SERVICE_ROLE_KEY!
);

export async function POST(req: Request) {
  const body = await req.text();
  let event: Stripe.Event;
  try {
    event = stripe.webhooks.constructEvent(
      body,
      req.headers.get("stripe-signature")!,
      process.env.STRIPE_WEBHOOK_SECRET!
    );
  } catch {
    return new Response("Invalid signature", { status: 400 });
  }

  if (event.type === "checkout.session.completed") {
    const s = event.data.object as Stripe.Checkout.Session;
    if (s.mode === "subscription" && s.client_reference_id) {
      const sub = await stripe.subscriptions.retrieve(s.subscription as string);
      await upsert(s.client_reference_id, sub);
    }
  }

  if (
    event.type === "customer.subscription.updated" ||
    event.type === "customer.subscription.deleted"
  ) {
    const sub = event.data.object as Stripe.Subscription;
    const userId = sub.metadata.user_id;
    if (userId) await upsert(userId, sub);
  }

  return new Response("ok");
}

async function upsert(userId: string, sub: Stripe.Subscription) {
  await admin.from("subscriptions").upsert({
    user_id: userId,
    stripe_customer_id: sub.customer as string,
    stripe_subscription_id: sub.id,
    status: sub.status,
    price_id: sub.items.data[0]?.price.id,
    current_period_end: new Date(
      (sub.items.data[0]?.current_period_end ?? 0) * 1000
    ).toISOString(),
    updated_at: new Date().toISOString(),
  });
}

Notes:

The success page should just show "Thanks, we're activating your plan" and read the subscriptions table, refreshing until the webhook has landed.

Step 4: Enforce on the server

In any premium API route or server action:

const { data: { user } } = await supabase.auth.getUser();
if (!user) return new Response("Unauthorized", { status: 401 });

const { data: sub } = await supabase
  .from("subscriptions")
  .select("status")
  .eq("user_id", user.id)
  .maybeSingle();

const isPaid = sub?.status === "active" || sub?.status === "trialing";
if (!isPaid) return new Response("Payment required", { status: 402 });

Put this in one helper (for example requirePaidUser()) and call it from every premium route so new routes don't forget. The same applies to server actions, which are public endpoints too.

Step 5: Enforce in RLS when the browser reads premium data directly

If your frontend queries a premium table straight from Supabase, the check has to live in RLS:

create policy "paid users read reports"
  on public.premium_reports for select
  to authenticated
  using (
    exists (
      select 1 from public.subscriptions s
      where s.user_id = (select auth.uid())
        and s.status in ('active', 'trialing')
    )
  );

How to test your paywall

Sign in as a free user and try each of these. All should fail:

  1. Visit the success URL directly without paying.
  2. Run supabase.from("profiles").update({ plan: "pro", is_pro: true }) on your own row from the console.
  3. Run an insert or update on subscriptions from the console.
  4. Call each premium API route directly with fetch.
  5. Query each premium table directly with the Supabase client.
  6. Cancel a test subscription in Stripe test mode and confirm access is removed after the webhook arrives.

Related guides

Get an automated check

PreflightPR reviews AI-built apps for client-side paywalls, user-editable plan columns, unsigned Stripe webhooks, missing RLS and leaked keys. Run a free scan on a public repo for a launch score and a prioritized fix list, or install the PreflightPR GitHub App to check every pull request before it merges.

Check your repo in about a minute

Paste a public GitHub URL and get a free launch score.

Run a free scan

More guides