← Back to dashboard
supabasedatabasefreshReader view (for NotebookLM)

Supabase Integration Guide

What is Row-Level Security?

The real model

Per-row authorization enforced at the planner, keyed off the JWT.

Supabase runs every API request as either `anon` or `authenticated`, with the user's JWT mapped into `request.jwt.claims`. RLS policies are PG-native: `USING (...)` filters reads/updates/deletes; `WITH CHECK (...)` filters inserts/updates. You enable RLS per table (`ALTER TABLE x ENABLE ROW LEVEL SECURITY`) and write policies `TO authenticated` that reference `(select auth.uid())` or `(select auth.jwt() ->> 'sub')` — the `select` wrapper makes Postgres evaluate it once per statement, not per row. With Clerk as a third-party auth provider (the codeAmani default), `sub` is the Clerk user id, so owner columns are `text`. The publishable key (`sb_publishable_…`) maps to `anon`/`authenticated`; the secret key (`sb_secret_…`, formerly `service_role`) has `BYPASSRLS` and is server-only — leaking it defeats the entire model. Storage objects are gated by the same policy engine against the `storage.objects` table.

The five pillars

Postgres holds the data; the other four bolt-on services share the same auth and the same RLS layer. Tap a card for the long version.

See RLS in motion

Same four rows, four roles, three policies. Switch the role and watch the table change without the query changing — that's the whole idea. The SQL block underneath is the exact policy doing the filtering.

RLS Policy Playground3 of 4 rows visible
Connecting as
Policy preset
SELECT * FROM postsresult for this role
authortitlepublic
✓aliceWelcome to my notestrue
✓aliceDraft: AI ideasfalse
✓bobM-Pesa flow writeuptrue
✗bobPersonal: bank detailsfalse
Active policy
ALTER TABLE posts ENABLE ROW LEVEL SECURITY;

CREATE POLICY "public_or_own"
  ON posts FOR SELECT
  USING (
    is_public = true
    OR author_id = auth.uid()
  );

Flip to service_role and the policy stops mattering — that key has BYPASSRLS, which is why it must stay server-side. Flip to anon with own rows only and the table goes empty: there is no auth.uid() to match against.

The #1 production foot-gun: leaving RLS disabled on a public-facing table while assuming the API key restricts access. The anon key is shipped to every browser — without RLS, anyone can SELECT * any table the schema exposes.

Text
███████╗██╗   ██╗██████╗  █████╗ ██████╗  █████╗ ███████╗███████╗
██╔════╝██║   ██║██╔══██╗██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔════╝
███████╗██║   ██║██████╔╝███████║██████╔╝███████║███████╗█████╗
╚════██║██║   ██║██╔═══╝ ██╔══██║██╔══██╗██╔══██║╚════██║██╔══╝
███████║╚██████╔╝██║     ██║  ██║██████╔╝██║  ██║███████║███████╗
╚══════╝ ╚═════╝ ╚═╝     ╚═╝  ╚═╝╚═════╝ ╚═╝  ╚═╝╚══════╝╚══════╝

Supabase Integration Guide

Focus: Postgres + RLS, publishable/secret API keys, SSR auth, Edge Functions, and Storage — wired into codeAmani's Next.js + Clerk stack, and driven from coding agents through the hosted Supabase MCP server and the supabase CLI.

Overview

Supabase is an open-source Firebase alternative built on Postgres. Every project gets a dedicated Postgres database, an auto-generated REST/GraphQL Data API, Auth, Storage, Realtime, and Deno-based Edge Functions. Authorization lives in the database as Row Level Security policies, so the Data API is safe to call straight from a browser.

Everything centers on one Postgres database, which makes Supabase easy to reason about:

Pinned versions (npm, verified 2026-10-17): @supabase/supabase-js 2.118.0 (v3 is only on the next tag — stay on v2), @supabase/ssr 0.12.7, @supabase/server 1.9.2, supabase CLI 2.121.0, @supabase/mcp-server-supabase 0.14.0. @supabase/auth-helpers-nextjs is deprecated — use @supabase/ssr.

Official Documentation

Every docs page is also served as markdown — append .md to the URL. Old paths (/guides/api/api-keys, /guides/getting-started/mcp, /guides/auth/server-side/nextjs) redirect to the canonical URLs above.


API keys

Supabase replaced the JWT-based anon / service_role keys with publishable and secret keys. The legacy keys still work but are deprecated by end of 2026. Both schemes run side by side, and creating new keys does not revoke the old ones.

Where the code runsKeyPostgres role
Anything you ship — browser, mobile, CLIPublishable sb_publishable_...anon, or authenticated once a user token is attached
Anything you control — server, Edge Function, cronSecret sb_secret_...service_role (has BYPASSRLS)

Facts that trip agents up:

  • New keys are short strings, not JWTs. A tutorial telling you to copy a long eyJ... key was written for the legacy keys.
  • Send them on the apikey header, not Authorization: Bearer. Anything that tries to verify one as a JWT fails.
  • A secret key refuses to work in a browser — Supabase matches on User-Agent and returns 401.
  • You can create several named secret keys (one per backend component), so a leak means rotating one key, not all of them.
  • Postgres checks grants before RLS. A missing grant returns a permission error (even for service_role); a policy that matches nothing returns an empty result. Check the grant before you debug the policy.

Get keys from the project's Connect dialog, Dashboard → Settings → API Keys, or the CLI: supabase projects api-keys --project-ref <ref>. A preview branch has its own keys — pass the branch's ref.


MCP server (agents)

The official server is the hosted HTTP endpoint https://mcp.supabase.com/mcp. Clients sign in over OAuth (dynamic client registration) — no personal access token for interactive use. When you run the local stack, the CLI serves a limited server at http://localhost:54321/mcp. Source: github.com/supabase/mcp.

Bash
# Claude Code (project scope), then run /mcp → supabase → Authenticate
claude mcp add --scope project --transport http supabase "https://mcp.supabase.com/mcp"

# Grok Build (writes ~/.grok/config.toml); verify with /mcps or `grok mcp doctor supabase`
grok mcp add supabase "https://mcp.supabase.com/mcp" --transport http

# Codex
codex mcp add supabase --url "https://mcp.supabase.com/mcp" && codex mcp login supabase

Cursor uses .cursor/mcp.json with { "mcpServers": { "supabase": { "url": "https://mcp.supabase.com/mcp" } } }. claude.ai has a Supabase connector in its directory.

Scoping options (URL query params)

JSON
{
  "mcpServers": {
    "supabase": {
      "type": "http",
      "url": "https://mcp.supabase.com/mcp?project_ref=<project-ref>&read_only=true&features=database,docs,debugging"
    }
  }
}
ParamEffect
project_ref=<ref>Scope to one project; hides account tools
read_only=trueRun every query as a read-only Postgres user
features=<groups>Enable only these groups: account, database, debugging, development, functions, branching, storage, docs
skip_elicitations=<tools>Skip form confirmations for create_project, create_branch, execute_sql, apply_migration. codeAmani: never set this.

Tools

All groups except Storage are on by default.

GroupTools
Databaselist_tables, list_extensions, list_migrations, apply_migration, execute_sql
Debuggingquery_logs (read-only SQL over logs), get_advisors
Developmentget_project_url, get_publishable_keys, generate_typescript_types
Edge Functionslist_edge_functions, get_edge_function, deploy_edge_function, create_edge_function_secret
Account (not in project-scoped mode)list_projects, get_project, create_project, pause_project, restore_project, list_organizations, get_organization, get_cost, confirm_cost
Docssearch_docs
Branching (paid plan)create_branch, list_branches, delete_branch, merge_branch, reset_branch, rebase_branch
Storage (off by default)list_storage_buckets, get_storage_config, update_storage_config

Elicitations: on clients that support them, the server pauses to confirm costs (create_project, create_branch) and destructive SQL (execute_sql, apply_migration). create_edge_function_secret opens a Dashboard URL where the human types the value — the value never passes through the agent. Treat both as guardrails, not guarantees.

CI / headless: create a scoped personal access token (one project, only the permissions your enabled tools need) and send Authorization: Bearer ${SUPABASE_ACCESS_TOKEN} to https://mcp.supabase.com/mcp?project_ref=${SUPABASE_PROJECT_REF}.

Security (codeAmani default): the server acts with your developer permissions, and data in your tables can carry prompt-injection text. Scope it (project_ref), run it read_only=true unless you are applying changes, prefer a development branch over production, keep per-call approval on, and never give it to end users.

Agent skills: npx skills add supabase/agent-skills installs Supabase's official development and security guidance for coding agents.


CLI

Install and authenticate

Bash
npm install -g supabase          # or: brew install supabase/tap/supabase
# Windows: scoop bucket add supabase https://github.com/supabase/scoop-bucket.git && scoop install supabase
supabase login                    # interactive; CI uses SUPABASE_ACCESS_TOKEN
supabase link --project-ref <ref>

Key commands

Bash
# Local stack (Docker or another container runtime)
supabase start                    # prints local publishable + secret keys
supabase status
supabase stop

# Migrations
supabase migration new add_posts
supabase db diff -f add_posts     # diff the LOCAL db against a shadow db → new migration file
supabase db reset                 # rebuild local db from migrations + seed
supabase db push                  # apply pending migrations to the linked project
supabase db pull                  # pull remote schema into a migration

# Inspect and lint
supabase db advisors              # security + performance advisors
supabase db lint                  # plpgsql type checks
supabase db query "select count(*) from posts"
supabase inspect db outliers      # also: locks, blocking, bloat, index-stats, ...

# Types (typescript is the default --lang)
supabase gen types --linked --lang=typescript > src/types/database.ts

# Edge Functions
supabase functions new stripe-webhook
supabase functions serve
supabase functions deploy stripe-webhook --no-verify-jwt   # only for signed webhooks
supabase secrets set STRIPE_WEBHOOK_SECRET=<value>          # the human runs this

# Keys
supabase projects api-keys --project-ref <ref>

There is no supabase logs command — read logs with the MCP query_logs tool or the Dashboard. Storage subcommands (storage ls|cp|mv|rm) need --experimental.


Client SDK

Bash
npm install @supabase/supabase-js
TypeScript
import { createClient } from "@supabase/supabase-js";
import type { Database } from "./types/database"; // supabase gen types --linked

const supabase = createClient<Database>(
  process.env.NEXT_PUBLIC_SUPABASE_URL!,
  process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
);

// Always destructure { data, error } and handle error explicitly
const { data, error } = await supabase
  .from("posts")
  .select("id, title, created_at")
  .eq("published", true)
  .order("created_at", { ascending: false })
  .limit(10);

// Realtime — RLS applies to what each subscriber receives
const channel = supabase
  .channel("db-changes")
  .on("postgres_changes", { event: "INSERT", schema: "public", table: "messages" }, (payload) => {
    handleNewMessage(payload.new);
  })
  .subscribe();

Environment variables

Bash
# Browser-safe (RLS-respecting)
NEXT_PUBLIC_SUPABASE_URL=https://<project-ref>.supabase.co
NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=sb_publishable_...

# Server-only — never prefix with NEXT_PUBLIC_
SUPABASE_SECRET_KEY=sb_secret_...

# Postgres (only if you use an ORM or a driver; copy hosts from the Connect dialog)
DATABASE_URL=postgresql://postgres.<project-ref>:<password>@<pooler-host>:6543/postgres
DIRECT_URL=postgresql://postgres:<password>@db.<project-ref>.supabase.co:5432/postgres

# CI only (interactive CLI/MCP use OAuth)
SUPABASE_ACCESS_TOKEN=sbp_...

Legacy names you will meet in older code: NEXT_PUBLIC_SUPABASE_ANON_KEY (→ publishable) and SUPABASE_SERVICE_ROLE_KEY (→ secret). Migrate them; don't add new uses.

Which Postgres connection

Code runs inUseNotes
BrowserData API (supabase-js)No connection string; RLS required
Vercel Functions / serverlessShared pooler, transaction mode (port 6543)Pool max: 1, prepare: false, ssl: 'require'
Migrations, pg_dumpDirect (port 5432)IPv6 unless you buy the IPv4 add-on
Persistent backend on IPv4 onlyShared pooler, session mode (port 5432)
High-throughput, paid planDedicated pooler db.<ref>.supabase.co:6543Transaction mode only

The shared pooler host is aws-<index>-<region>.pooler.supabase.com and its username is postgres.<project-ref> — copy both from the Connect dialog; you can't derive the host from the region. Transaction mode loses session state (SET, advisory locks, LISTEN/NOTIFY, temp tables) and doesn't support prepared statements or pipelining.

TypeScript
// lib/db.ts — Postgres.js in a serverless function
import postgres from "postgres";

export const sql = postgres(process.env.DATABASE_URL!, {
  max: 1,          // one connection per warm instance
  prepare: false,  // transaction mode has no prepared statements
  ssl: "require",
});

Prisma uses pgbouncer=true on the pooled URL instead of prepare: false.


Row Level Security

RLS is how a browser-held publishable key stays safe. Enable it on every table in an exposed schema, then write policies for the anon and authenticated roles. RLS with no policies denies everything.

SQL
-- supabase/migrations/20261017000000_add_posts.sql
create table if not exists public.posts (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null references auth.users (id) on delete cascade,
  title text not null check (char_length(title) <= 200),
  created_at timestamptz not null default now()
);

alter table public.posts enable row level security;

create policy "posts_select_own" on public.posts
  for select to authenticated
  using ((select auth.uid()) = user_id);

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

create index if not exists posts_user_id_idx on public.posts (user_id);

Performance rules from the RLS docs:

  1. Wrap auth helpers in select — (select auth.uid()) runs once per statement (an initPlan) instead of once per row.
  2. Always name the role with to authenticated (or to anon) so policies don't run for callers they can't apply to.
  3. Index every column a policy filters on (first column of a btree index).
  4. For lookups across tables, use a security definer function with set search_path = '' in a non-exposed schema, called as (select private.fn()).

UPDATE needs both using (the existing row) and with check (the new row). For the Clerk version of these policies, see the next section.


Auth: Clerk (codeAmani default) or Supabase Auth

Clerk as a third-party auth provider

codeAmani apps use Clerk for identity. Register Clerk as a third-party auth provider and Supabase accepts Clerk session tokens directly — RLS reads the Clerk user ID from auth.jwt() ->> 'sub'.

  1. Run Clerk's Connect with Supabase setup. It adds "role": "authenticated" to Clerk session tokens.
  2. Supabase Dashboard → Authentication → Third-Party Auth → Clerk. For the local stack, add to supabase/config.toml:
    TOML
    [auth.third_party.clerk]
    enabled = true
    domain = "<your-instance>.clerk.accounts.dev"
  3. Give createClient an accessToken() callback that returns the Clerk session token.
TypeScript
// Client Component
"use client";
import { useSession } from "@clerk/nextjs";
import { createClient } from "@supabase/supabase-js";

export function useClerkSupabase() {
  const { session } = useSession();
  return createClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
    { async accessToken() { return (await session?.getToken()) ?? null; } },
  );
}
TypeScript
// Server Component / Route Handler / Server Action
import { auth } from "@clerk/nextjs/server";
import { createClient } from "@supabase/supabase-js";

export function createClerkSupabaseServerClient() {
  return createClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
    { async accessToken() { return (await auth()).getToken(); } },
  );
}

Clerk user IDs are strings like user_2abc..., so the owner column is text, not uuid:

SQL
create table public.tasks (
  id bigint generated always as identity primary key,
  name text not null,
  user_id text not null default (auth.jwt() ->> 'sub')
);
alter table public.tasks enable row level security;

create policy "tasks_select_own" on public.tasks
  for select to authenticated
  using ((select auth.jwt() ->> 'sub') = user_id);

create policy "tasks_insert_own" on public.tasks
  for insert to authenticated
  with check ((select auth.jwt() ->> 'sub') = user_id);

Clerk organization claims (o.id, o.rol) and the second-factor claim (fva) are also available to policies. The old JWT-template integration (sharing the Supabase JWT secret with Clerk) is deprecated since 2025-04-01.

Supabase Auth with SSR (when a project uses it instead of Clerk)

Install @supabase/supabase-js @supabase/ssr. Use createBrowserClient in Client Components and createServerClient (with getAll/setAll cookie accessors) on the server. A proxy refreshes the session cookie on each request:

  • Next.js 16+: proxy.ts exporting async function proxy(request).
  • Next.js 15 and earlier: middleware.ts exporting async function middleware(request). A proxy.ts is silently ignored on 15 — sessions never refresh and users get signed out.
TypeScript
// lib/supabase/server.ts
import { createServerClient } from "@supabase/ssr";
import { cookies } from "next/headers";

export async function createClient() {
  const cookieStore = await cookies();
  return createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
    {
      cookies: {
        getAll: () => cookieStore.getAll(),
        setAll: (cookiesToSet) => {
          try {
            cookiesToSet.forEach(({ name, value, options }) => cookieStore.set(name, value, options));
          } catch {
            // Server Components can't write cookies; the proxy refreshes the session.
          }
        },
      },
    },
  );
}

// In a Server Component:
const supabase = await createClient();
const { data, error } = await supabase.auth.getClaims(); // verifies the JWT signature
if (error || !data) redirect("/login");

Which auth call to use:

CallVerifies?Use for
getClaims()Yes — locally against cached JWKS (asymmetric keys, default for new projects) or via Auth serverProtecting pages and data
getUser()Yes — network call to AuthWhen you need the fresh user record
getSession()No — reads the cookieOnly to forward a raw token; never for authorization

The proxy must return the supabaseResponse that setAll last built (or copy its cookies and cache-control/expires/pragma headers onto your own response), or the refreshed token is lost. Don't let a CDN or ISR cache a response that sets a session cookie — another user would receive it.


Edge Functions

Edge Functions run on Deno. Secure each one with withSupabase from @supabase/server, which checks the caller against the auth mode you declare and hands your handler preconfigured clients on ctx.

auth modeAcceptsverify_jwt
'user'A user JWT on Authorization (gives RLS-scoped ctx.supabase)true (default)
'secret' / 'secret:<name>'A secret key on apikey (cron, workers, pg_net)false
'publishable'A publishable key on apikeyfalse
'none'Anyone — you authenticate in the handler (signed webhooks)false

Pass an array (auth: ['user', 'secret']) to accept several; ctx.authMode says which matched. Use createSupabaseContext(req, { auth }) instead when you want to shape the 401 yourself.

TypeScript
// supabase/functions/stripe-webhook/index.ts — Stripe is codeAmani's default payments rail
import { withSupabase } from "npm:@supabase/server@1";
import Stripe from "npm:stripe";

const stripe = new Stripe(Deno.env.get("STRIPE_SECRET_KEY")!);
const cryptoProvider = Stripe.createSubtleCryptoProvider(); // Deno has no sync crypto

export default {
  fetch: withSupabase({ auth: "none" }, async (req, ctx) => {
    const body = await req.text();
    let event: Stripe.Event;
    try {
      event = await stripe.webhooks.constructEventAsync(
        body,
        req.headers.get("stripe-signature") ?? "",
        Deno.env.get("STRIPE_WEBHOOK_SECRET")!,
        undefined,
        cryptoProvider,
      );
    } catch (err) {
      console.error("Stripe signature verification failed:", err);
      return new Response("bad signature", { status: 400 });
    }

    // Idempotency: the unique event id makes retries a no-op
    const { error } = await ctx.supabaseAdmin
      .from("stripe_events")
      .upsert({ id: event.id, type: event.type }, { onConflict: "id", ignoreDuplicates: true });
    if (error) return new Response("db error", { status: 500 });

    return Response.json({ received: true });
  }),
};
TOML
# supabase/config.toml
[functions.stripe-webhook]
verify_jwt = false

The runtime injects SUPABASE_URL, SUPABASE_PUBLISHABLE_KEYS, SUPABASE_SECRET_KEYS (JSON objects keyed by key name) and SUPABASE_JWKS. SUPABASE_ANON_KEY / SUPABASE_SERVICE_ROLE_KEY still exist but carry the legacy keys. Don't read keys yourself — let @supabase/server do it.

ctx.supabaseAdmin bypasses RLS. In a 'user' handler, query through ctx.supabase, or filter by ctx.userClaims.id — otherwise one user can read everyone's rows.


Storage

TypeScript
const { error } = await supabase.storage
  .from("avatars")
  .upload(`${userId}/avatar.png`, file, { contentType: "image/png", upsert: true });

// Private bucket → short-lived signed URL
const { data, error: signError } = await supabase.storage
  .from("avatars")
  .createSignedUrl(`${userId}/avatar.png`, 60);

Buckets are private by default; keep them that way. Storage access is controlled by RLS policies on storage.objects (filter on bucket_id and the path prefix).


Agent automation

Hook: regenerate types after a migration

Claude Code hooks receive the tool call as JSON on stdin (there is no $CLAUDE_TOOL_INPUT variable). .claude/settings.json:

JSON
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.tool_input.command // empty' | grep -qE 'supabase (db push|db reset|migration up)' && supabase gen types --linked --lang=typescript > src/types/database.ts || true"
          }
        ]
      }
    ]
  }
}

Common tasks

TaskHow
Schema changesupabase migration new → edit → db reset locally → db push
Typessupabase gen types --linked --lang=typescript
Security / perf lintssupabase db advisors or MCP get_advisors
Slow queryMCP execute_sql with explain analyze, or supabase inspect db outliers
Read logsMCP query_logs (read-only SQL over logs)
Feature branch DBMCP create_branch / merge_branch (paid plan)

Troubleshooting

IssueFix
Query returns empty rowsA policy is filtering them. Check you sent a user token and the policy's to role. Don't switch to the secret key to "fix" it.
permission denied for tableA missing grant, checked before RLS — even service_role hits it
Users signed out after every requestNext 15 with a proxy.ts (needs middleware.ts), or the proxy returned a response without the refreshed cookies
Clerk policy never matchesOwner column is uuid; Clerk IDs need text
prepared statement already existsTransaction pooler — set prepare: false / pgbouncer=true
Tenant or user not foundPooler username must be postgres.<project-ref>; copy the host from Connect
Edge Function returns 401verify_jwt is on for a function called with an API key — set it false and use withSupabase
Secret key returns 401 in the browserBy design — move the call server-side
supabase start failsStart Docker Desktop (or your container runtime)

codeAmani notes

  • Role in the stack: Supabase (or Neon) is the database layer. Clerk stays the identity provider — connect it through third-party auth, not the deprecated JWT template. Stripe stays the payments rail; handle its webhooks in a Route Handler or an Edge Function that verifies the signature and dedupes on event.id.
  • Secrets: SUPABASE_SECRET_KEY, DATABASE_URL, DIRECT_URL, and SUPABASE_ACCESS_TOKEN live in the Hazina vault and are injected server-side. Only NEXT_PUBLIC_SUPABASE_URL and the publishable key may carry NEXT_PUBLIC_. Edge Function secrets are set by the human (supabase secrets set or the MCP Dashboard flow) — never pasted into chat.
  • AI routing: pgvector lets RAG embeddings live next to relational data. Generate embeddings and call Claude from server code only; the publishable key never fronts an AI call.
  • Kenya-targeted projects: M-Pesa callbacks fit an Edge Function with auth: 'none' that validates the callback (shortcode, amount, known CheckoutRequestID) and dedupes on CheckoutRequestID before writing. Supabase has no African region; measure latency from Nairobi to eu-central-1 (Frankfurt), eu-west-2 (London) and ap-south-1 (Mumbai) and pick the fastest. The region can't be changed later. Keep payloads small for 2G/3G clients.
  • Free tier projects pause after a week of inactivity — fine for prototypes, never for production. See reference/limits-and-pricing.md.