Skip to content

React Supabase prompt

Rules that make your coding agent build on Supabase safely: @supabase/ssr clients, sessions refreshed in proxy.ts, Row Level Security on every table and realtime channels that clean up.

What it makes your agent good at

Agents still install the auth helpers, authorize with getSession on the server, create tables without Row Level Security and leave realtime channels open after unmount. This prompt gives them the current model: @supabase/ssr clients with getAll and setAll, token refresh in proxy.ts, getClaims for trust, policies on every table, generated types, and the secret key kept on the server.

  1. Clients from @supabase/ssrcreateBrowserClient and a per-request createServerClient with getAll and setAll cookies, typed with the generated Database.
  2. Sessions refreshed in proxy.tsgetClaims in proxy.ts on every request; getClaims or getUser to authorize, never getSession on the server.
  3. RLS on every tableA policy per operation with (select auth.uid()), indexed policy columns, security definer helpers, no user_metadata checks.
  4. Realtime that cleans upChannels created in an effect and removed on unmount, with Broadcast and private channels when subscribers grow.
  5. Keys where they belongThe publishable key in the browser; the secret or service_role key only in server code and Edge Functions.
  6. Migrations, not dashboard editssupabase migration new, db reset and db push, with types regenerated after every schema change.

The React Supabase rules

170 lines, current to @supabase/ssr and supabase-js with Next.js 16.4 and React 19.3. Last reviewed October 23, 2026. Plain Markdown, no front matter: each agent's is below.

Download

react-supabase.md

# React Supabase

You are working in a React project backed by Supabase, usually a Next.js 16 App Router app using `@supabase/ssr`, `@supabase/supabase-js` and TypeScript. Write code for the versions in `package.json`: the auth helpers packages, `getSession()` on the server and `middleware.ts` are outdated patterns.

## Before you write code

- Check `package.json` for `@supabase/ssr` and `@supabase/supabase-js`, and whether this is Next.js or a Vite single-page app (see the last section).
- Find the existing client factories (`lib/supabase/client.ts`, `lib/supabase/server.ts`, the proxy helper) and reuse them. There is one factory per environment.
- Read `supabase/migrations/` and the generated types file (`lib/database.types.ts` or similar) before touching data: they are the schema. If `supabase/config.toml` exists, the project runs Supabase locally.
- Environment: `NEXT_PUBLIC_SUPABASE_URL` and the publishable key (`sb_publishable_…`, or the legacy anon key) are public. The secret key (`sb_secret_…`, or the legacy `service_role` key) is server only.

## Clients from @supabase/ssr

```ts
// lib/supabase/server.ts
import { createServerClient } from "@supabase/ssr";
import { cookies } from "next/headers";
import type { Database } from "@/lib/database.types";

export async function createClient() {
  const cookieStore = await cookies();
  return createServerClient<Database>(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
    {
      cookies: {
        getAll: () => cookieStore.getAll(),
        setAll(cookiesToSet) {
          try {
            for (const { name, value, options } of cookiesToSet) {
              cookieStore.set(name, value, options);
            }
          } catch {
            // Server Components cannot set cookies; proxy.ts refreshes them.
          }
        },
      },
    }
  );
}
```

- Browser: `createBrowserClient<Database>(url, publishableKey)` in `lib/supabase/client.ts`, called from Client Components. It is a singleton in the browser.
- Server: create a new server client per request (as above) in Server Components, Server Functions and Route Handlers. Never share one across requests or store it in a module variable.
- Use only `getAll` and `setAll` for cookies. The old `get`/`set`/`remove` interface is deprecated.
- Pass the generated `Database` type to every client so queries, inserts and RPC calls are typed.

## Sessions in proxy.ts

Next.js 16 uses `proxy.ts` (not `middleware.ts`) to refresh the auth token on each request:

```ts
// proxy.ts
import { type NextRequest, NextResponse } from "next/server";
import { createServerClient } from "@supabase/ssr";

export async function proxy(request: NextRequest) {
  let response = NextResponse.next({ request });
  const supabase = createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
    {
      cookies: {
        getAll: () => request.cookies.getAll(),
        setAll(cookiesToSet) {
          for (const { name, value } of cookiesToSet) request.cookies.set(name, value);
          response = NextResponse.next({ request });
          for (const { name, value, options } of cookiesToSet) {
            response.cookies.set(name, value, options);
          }
        },
      },
    }
  );
  const { data } = await supabase.auth.getClaims(); // refreshes the session
  if (!data?.claims && request.nextUrl.pathname.startsWith("/app")) {
    return NextResponse.redirect(new URL("/login", request.url));
  }
  return response;
}

export const config = {
  matcher: ["/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|webp)$).*)"],
};
```

- Run no code between `createServerClient` and `auth.getClaims()`, and return the same `response` object (or copy its cookies onto a new one). Dropping those cookies logs users out at random.
- On the server, trust `supabase.auth.getClaims()` (verifies the JWT signature) or `supabase.auth.getUser()` (asks the Auth server; use it when a revoked or deleted user must be refused at once). Never authorize with `getSession()` on the server: it reads the cookie without verifying it.
- Proxy redirects are a convenience. Authorize again where the data is read or written; Row Level Security is the final check.
- Auth flows: `signInWithPassword`, `signInWithOtp`, `signInWithOAuth({ provider, options: { redirectTo } })`. OAuth and magic links return to a Route Handler (`app/auth/callback/route.ts`) that calls `exchangeCodeForSession(code)`; email confirmation links call `verifyOtp({ type, token_hash })`. Redirect only to paths you allow.
- After sign in or sign out in a Server Function, `revalidatePath("/", "layout")`, then `redirect()`.

## Row Level Security on every table

- Enable RLS on every table in an exposed schema (`public`) in the same migration that creates it. A table without RLS is readable and writable by anyone holding the publishable key.
- Write one policy per operation and role, with `(select auth.uid())` so Postgres evaluates it once per query, not per row:

```sql
alter table public.notes enable row level security;

create policy "Owners read notes" on public.notes
  for select to authenticated
  using ((select auth.uid()) = user_id);

create policy "Owners insert notes" on public.notes
  for insert to authenticated
  with check ((select auth.uid()) = user_id);
```

- `update` needs both `using` and `with check`. Add `to authenticated` (or `anon`) to every policy, and index the columns policies filter on (`user_id`, `org_id`).
- For membership checks across tables, call a `security definer` function in a schema the API does not expose, with `set search_path = ''`, instead of joining inside the policy.
- Never base authorization on `user_metadata` (users can edit it). Use `app_metadata` or your own tables.
- Views bypass RLS unless created `with (security_invoker = true)`.
- Still filter in queries (`.eq("user_id", userId)`): RLS secures, filters make the planner fast.

## Queries and types

- Generate types after every migration: `supabase gen types typescript --local > lib/database.types.ts` (or `--project-id`). Use the generated helpers `Tables<"notes">`, `TablesInsert<"notes">`, `Enums<"status">` instead of hand-written interfaces.
- Every call returns `{ data, error }` and does not throw: check `error` before using `data`. Use `.single()` when a row must exist and `.maybeSingle()` when it may not.
- Select the columns you need (`.select("id, title, author:profiles(name)")`), never `*` into a Client Component.
- Read data in Server Components with the server client and pass plain values down. Under Cache Components, the server client reads cookies: render it inside `<Suspense>` and never call it inside `"use cache"`.
- Put multi-step writes that must succeed together in a Postgres function called with `.rpc()`, not in several client calls.

## Realtime and Storage

- Subscribe in an effect and remove the channel on cleanup, or every remount adds a listener:

```tsx
useEffect(() => {
  const channel = supabase
    .channel(`room:${roomId}`)
    .on("postgres_changes", { event: "INSERT", schema: "public", table: "messages", filter: `room_id=eq.${roomId}` }, onInsert)
    .subscribe();
  return () => {
    supabase.removeChannel(channel);
  };
}, [roomId]);
```

- Postgres Changes needs the table in the `supabase_realtime` publication and respects RLS. For many subscribers or high write rates, use Broadcast; private channels (`{ config: { private: true } }`) are authorized by RLS policies on `realtime.messages`. Use Presence for who is online.
- Storage buckets are private unless they hold truly public assets. Write policies on `storage.objects` scoped by bucket and owner folder (`(storage.foldername(name))[1] = (select auth.uid())::text`), and store files under `<user id>/…`.
- Serve private files with `createSignedUrl(path, seconds)` created on the server after checking access; keep expiry short. Validate type and size before upload.

## Keys, migrations and functions

- The secret or `service_role` key bypasses RLS. Use it only in server code (Route Handlers, Server Functions, Edge Functions, scripts) through a separate admin client, with `auth: { persistSession: false, autoRefreshToken: false }`, and never for a request you could make as the user. Never prefix it `NEXT_PUBLIC_` or import it into a client file.
- Change the schema only through migrations: `supabase migration new <name>`, write SQL, `supabase db reset` locally (replays migrations and `seed.sql`), `supabase db push` to the linked project. Use `supabase db diff` only to draft a migration from changes made in the local Studio, then read it.
- Use Next.js Server Functions for mutations that belong to the app's UI. Use Supabase Edge Functions (Deno, `Deno.serve`) for work that must live beside the database: third-party webhooks, database webhooks, jobs shared by web and mobile clients. Set their secrets with `supabase secrets set`.
- For auth screens, file uploads, realtime chat and avatars, start from the Supabase UI Library (shadcn registry blocks installed with the shadcn CLI) and adapt them, instead of writing them from scratch.

## Vite single-page apps

- Without a server, use `createClient` from `@supabase/supabase-js` with `import.meta.env.VITE_SUPABASE_URL` and the publishable key; the session lives in local storage and RLS is your only authorization.
- Subscribe to `onAuthStateChange` once at the root and call `data.subscription.unsubscribe()` on cleanup. Do not await other Supabase calls inside its callback; defer them.
- Anything that needs the secret key runs in an Edge Function, never in the bundle.

## Do not

- Do not use `@supabase/auth-helpers-nextjs` or `@supabase/auth-helpers-react`, cookie `get`/`set`/`remove` methods, or `middleware.ts` in Next.js 16.
- Do not authorize with `getSession()` on the server, or trust a user ID sent from the client instead of `auth.uid()`.
- Do not create a table without RLS, write `auth.uid()` in a policy without `select`, or put the secret key in client code.
- Do not leave realtime channels subscribed after unmount or make buckets public to avoid writing policies.
- Do not edit the remote schema in the dashboard without a migration.

## Before you finish

- Run the type checker after regenerating types; a type error on a query usually means a stale types file or a wrong column.
- Run `supabase db reset` and test each policy as two different users and as `anon`: one must not see or change the other's rows.
- Check the dashboard's Security and Performance Advisors for tables without RLS, mutable function search paths and unindexed policy columns.
- Confirm no secret key appears in client bundles or `NEXT_PUBLIC_` variables, and list the migrations you added.

10,806 characters, 1,499 words. Under Windsurf's 12,000-character limit for a rule, as every prompt here is.

Use it in your agent

The same rules, where your agent reads them. Each file has the front matter its agent needs, set to apply on every request.

Claude Code

A rule it loads every session

  1. Save it as .claude/rules/react-supabase.md in your project, front matter included, or run the install command.
  2. Claude Code loads every file in .claude/rules with your CLAUDE.md when a session starts.
  3. Prefer one file? Paste it into CLAUDE.md under its own heading instead.

.claude/rules/react-supabase.md

# React SupabaseYou are working in a React project backed by Supabase, usually a Next.js 16 App Router app using `@supabase/ssr`, `@supabase/supabase-js` and TypeScript. Write code for the versions in `package.json`: the auth helpers packages, `getSession()` on the server and `middleware.ts` are outdated patterns.## Before you write code- Check `package.json` for `@supabase/ssr` and `@supabase/supabase-js`, and whether this is Next.js or a Vite single-page app (see the last section).- Find the existing client factories (`lib/supabase/client.ts`, `lib/supabase/server.ts`, the proxy helper) and reuse them. There is one factory per environment.- Read `supabase/migrations/` and the generated types file (`lib/database.types.ts` or similar) before touching data: they are the schema. If `supabase/config.toml` exists, the project runs Supabase locally.- Environment: `NEXT_PUBLIC_SUPABASE_URL` and the publishable key (`sb_publishable_…`, or the legacy anon key) are public. The secret key (`sb_secret_…`, or the legacy `service_role` key) is server only.## Clients from @supabase/ssr…

Or let the shadcn CLI write this file: sign in (free) for your command.

Cursor

A project rule with front matter

  1. Save it as .cursor/rules/react-supabase.mdc, front matter included, or run the install command.
  2. alwaysApply: true adds it to every Agent request in this project.
  3. Check it under Cursor Settings, Rules, then commit the folder for your team.

.cursor/rules/react-supabase.mdc

---description: "Supabase in React and Next.js: clients, auth sessions, Row Level Security, typed queries, realtime, storage, keys and migrations."alwaysApply: true---# React SupabaseYou are working in a React project backed by Supabase, usually a Next.js 16 App Router app using `@supabase/ssr`, `@supabase/supabase-js` and TypeScript. Write code for the versions in `package.json`: the auth helpers packages, `getSession()` on the server and `middleware.ts` are outdated patterns.## Before you write code- Check `package.json` for `@supabase/ssr` and `@supabase/supabase-js`, and whether this is Next.js or a Vite single-page app (see the last section).- Find the existing client factories (`lib/supabase/client.ts`, `lib/supabase/server.ts`, the proxy helper) and reuse them. There is one factory per environment.- Read `supabase/migrations/` and the generated types file (`lib/database.types.ts` or similar) before touching data: they are the schema. If `supabase/config.toml` exists, the project runs Supabase locally.- Environment: `NEXT_PUBLIC_SUPABASE_URL` and the publishable key (`sb_publishable_…`, or the legacy anon key) are public. The secret key (`sb_secret_…`, or the legacy `service_role` key) is server only.## Clients from @supabase/ssr…

Or let the shadcn CLI write this file: sign in (free) for your command.

Windsurf

A workspace rule for Cascade

  1. Save it as .windsurf/rules/react-supabase.md, or run the install command.
  2. trigger: always_on applies it to every Cascade request in this workspace.
  3. Windsurf reads up to 12,000 characters per rule; this one is 10,806.

.windsurf/rules/react-supabase.md

---trigger: always_on---# React SupabaseYou are working in a React project backed by Supabase, usually a Next.js 16 App Router app using `@supabase/ssr`, `@supabase/supabase-js` and TypeScript. Write code for the versions in `package.json`: the auth helpers packages, `getSession()` on the server and `middleware.ts` are outdated patterns.## Before you write code- Check `package.json` for `@supabase/ssr` and `@supabase/supabase-js`, and whether this is Next.js or a Vite single-page app (see the last section).- Find the existing client factories (`lib/supabase/client.ts`, `lib/supabase/server.ts`, the proxy helper) and reuse them. There is one factory per environment.- Read `supabase/migrations/` and the generated types file (`lib/database.types.ts` or similar) before touching data: they are the schema. If `supabase/config.toml` exists, the project runs Supabase locally.- Environment: `NEXT_PUBLIC_SUPABASE_URL` and the publishable key (`sb_publishable_…`, or the legacy anon key) are public. The secret key (`sb_secret_…`, or the legacy `service_role` key) is server only.## Clients from @supabase/ssr…

Or let the shadcn CLI write this file: sign in (free) for your command.

GitHub Copilot

Instructions for the repository

  1. Save it as .github/instructions/react-supabase.instructions.md, or run the install command.
  2. applyTo: "**" applies it to every request in this repository.
  3. Or paste it into .github/copilot-instructions.md, which Copilot reads for every request.

.github/instructions/react-supabase.instructions.md

---description: "Supabase in React and Next.js: clients, auth sessions, Row Level Security, typed queries, realtime, storage, keys and migrations."applyTo: "**"---# React SupabaseYou are working in a React project backed by Supabase, usually a Next.js 16 App Router app using `@supabase/ssr`, `@supabase/supabase-js` and TypeScript. Write code for the versions in `package.json`: the auth helpers packages, `getSession()` on the server and `middleware.ts` are outdated patterns.## Before you write code- Check `package.json` for `@supabase/ssr` and `@supabase/supabase-js`, and whether this is Next.js or a Vite single-page app (see the last section).- Find the existing client factories (`lib/supabase/client.ts`, `lib/supabase/server.ts`, the proxy helper) and reuse them. There is one factory per environment.- Read `supabase/migrations/` and the generated types file (`lib/database.types.ts` or similar) before touching data: they are the schema. If `supabase/config.toml` exists, the project runs Supabase locally.- Environment: `NEXT_PUBLIC_SUPABASE_URL` and the publishable key (`sb_publishable_…`, or the legacy anon key) are public. The secret key (`sb_secret_…`, or the legacy `service_role` key) is server only.## Clients from @supabase/ssr…

Or let the shadcn CLI write this file: sign in (free) for your command.

Codex & AGENTS.md

The file most agents read

  1. Paste it into AGENTS.md at your project's root, under its own heading.
  2. Codex reads AGENTS.md before it starts work, and so do Cursor, Zed, Jules, Amp and Copilot's coding agent.
  3. A folder can have its own AGENTS.md: the one closest to the file being edited wins.

AGENTS.md

## React SupabaseYou are working in a React project backed by Supabase, usually a Next.js 16 App Router app using `@supabase/ssr`, `@supabase/supabase-js` and TypeScript. Write code for the versions in `package.json`: the auth helpers packages, `getSession()` on the server and `middleware.ts` are outdated patterns.### Before you write code- Check `package.json` for `@supabase/ssr` and `@supabase/supabase-js`, and whether this is Next.js or a Vite single-page app (see the last section).- Find the existing client factories (`lib/supabase/client.ts`, `lib/supabase/server.ts`, the proxy helper) and reuse them. There is one factory per environment.- Read `supabase/migrations/` and the generated types file (`lib/database.types.ts` or similar) before touching data: they are the schema. If `supabase/config.toml` exists, the project runs Supabase locally.- Environment: `NEXT_PUBLIC_SUPABASE_URL` and the publishable key (`sb_publishable_…`, or the legacy anon key) are public. The secret key (`sb_secret_…`, or the legacy `service_role` key) is server only.### Clients from @supabase/ssr…

AGENTS.md is shared with your own instructions, so paste the rules in: the copy sets their headings a level down.

Rules teach it. The MCP equips it. With Pro, your agent installs every component, block and icon it needs, from a prompt.

Get Pro

Pricing

Give your agent the parts, with Pro

The prompts are free. Every Pro plan adds the MCP server, so your agent installs the components, blocks and icons it writes code around.

4.9/5 out of 5 · 150+ reviewsfrom 150+ founders and developers.

Billed once a year in USD. Cancel anytime.

Individual

For personal projects & open source

$32instead of $49/mo

$389 billed yearly

  • How many people can use the license.Seats: 1 seat
  • Client work, SaaS products and anything you charge for.Commercial use: Personal & open source only
  • Page sections in 56 categories, from heroes and pricing tables to dashboards and settings, on every framework and UI library, in your theme.Blocks: All 6,181 blocks
  • Complete Next.js sites for startups, SaaS, agencies and portfolios, every page designed, ready to ship.Templates: All 14 templates
  • Your AI agent searches, previews and installs any component, block, icon or DESIGN.md from a prompt: 22 tools in Claude Code, Cursor, VS Code and 35 more clients.MCP server: 38 AI clients
  • Buttons with motion and states of their own, from an arrow that slides in to a burst of confetti.Animated buttons: All 35 buttons
  • Typewriters, scrambles, counters and more, for headlines, labels and numbers.Text effects: All 97 effects
  • Animated backgrounds for heroes, sections and cards, from a soft aurora to a flock that flees the cursor. Most are pure CSS.Backgrounds: All 100 backgrounds
  • WebGPU shaders, from a slow aurora to a black hole, each drawing only while it's on screen.Shaders: All 100 shaders
  • One design and one theme on all four: the components, blocks and effects are built for each framework.Frameworks: React, Vue, Svelte, Solid
  • React on Base UI, Radix UI, React Aria or Ark UI: install the version for the library your project already uses. Vue, Svelte and Solid run on Ark UI.UI libraries: Base UI, Radix, Aria, Ark
  • From a button to a date picker, a color picker or a guided tour: accessible, typed in TypeScript, each with live demos.Components: All 174 components
  • Real-world patterns built from the components, in 53 galleries: forms, tables, menus, dialogs and more.Examples: All 1,103 examples
  • Area, bar, line, pie, radar and radial charts on TanStack Charts, on every framework. React also gets the Recharts originals.Charts: All 70 charts
  • Debounce, local storage, media queries and more: each hook is one typed file you own.React hooks: All 35 hooks
  • From 222 libraries, Lucide, Heroicons, Tabler and Material Symbols among them, as SVG or a React component in one command.Icons: 294k+ icons
  • Stripe, Linear, Apple and 497 more: a brand's colors, typography and components in one file your AI agent builds from.DESIGN.md files: All 500 brands
  • Restyle every component and block at once: 8 styles, 7 grays, 18 colors and 5 radii, shared as a shadcn preset code.Theme builder: 8 styles × 18 colors
  • Priority requests are answered first.Support: Standard

Team

Most popular

For freelancers, agencies & startups

$66instead of $99/mo

$789 billed yearly · ≈ $13/dev/mo

Everything in Individual, plus

  • How many people can use the license.Seats: Up to 5 seats
  • Client work, SaaS products and anything you charge for.Commercial use: Included
  • Priority requests are answered first.Support: Priority

Organization

For companies with larger teams

$132instead of $199/mo

$1,589 billed yearly

Everything in Team, plus

  • How many people can use the license.Seats: Unlimited seats
  • Secure checkout via Stripe
  • Code lives in your repo
  • Keep what you've shipped if you cancel
  • License terms

React Supabase prompt FAQ

What the React Supabase prompt covers and how to use it in your agent.

Does the React Supabase prompt use @supabase/ssr or the auth helpers?

@supabase/ssr. The prompt has the agent create a browser client with createBrowserClient and a new server client per request with createServerClient and the getAll and setAll cookie methods. The deprecated auth helpers packages and the old get, set and remove cookie methods are listed under Do not.

Why does the React Supabase prompt use getClaims instead of getSession?

getSession reads the session from the cookie without verifying it, so on the server anyone can forge what it returns. The prompt has the agent authorize with getClaims, which verifies the token's signature, or getUser, which asks the Auth server and also refuses users who were deleted or signed out.

How does the React Supabase prompt refresh Supabase sessions in Next.js 16?

In proxy.ts, which replaces middleware.ts in Next.js 16. A server client built on the request's cookies calls getClaims on every matched request, which refreshes the token, and the proxy returns the response carrying the new cookies. Redirects there are a convenience; RLS and the data layer still authorize.

Does the React Supabase prompt work in a Vite single-page app?

Yes. For a Vite app it uses createClient from supabase-js with the publishable key from import.meta.env, subscribes to onAuthStateChange once and unsubscribes on cleanup, and treats RLS as the only authorization. Anything that needs the secret key moves to an Edge Function.

4.9 out of 5 from 150+ developers

Rules teach it. The MCP equips it.

Every component, block and icon, installed by your AI agent on your stack. The prompts stay free.

Get Pro
  • Cancel anytime
  • Keep what you've shipped