Supabase Integration Guide

Technology: supabase · Category: database · Last reviewed: 2026-10-17

Source: https://tech-stack.codeamanilabs.org/guide/supabase

Insight:

Supabase is Postgres + Auth + Storage + Edge Functions in one. Its superpower is RLS — push authorization into the database so multi-tenant isolation holds even when app code is wrong. It also ships pgvector, so relational data and RAG embeddings can live in the same DB.

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

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:

flowchart TD
    APP["Your app<br/>supabase-js client"] --> CORE["Supabase<br/>built on Postgres"]
    AGENT["Coding agent<br/>hosted MCP + CLI"] --> CORE
    CORE --> DB["Postgres database<br/>+ RLS policies"]
    CORE --> AUTH["Auth<br/>Supabase Auth or Clerk"]
    CORE --> STORE["Storage<br/>buckets"]
    CORE --> RT["Realtime<br/>postgres_changes"]
    CORE --> FN["Edge Functions<br/>Deno + @supabase/server"]

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

Resource URL
Supabase Docs https://supabase.com/docs
API keys (publishable / secret) https://supabase.com/docs/guides/getting-started/api-keys
Migrating to new API keys https://supabase.com/docs/guides/getting-started/migrating-to-new-api-keys
SSR client (Next.js) https://supabase.com/docs/guides/auth/server-side/creating-a-client
Connecting to Postgres https://supabase.com/docs/guides/database/connecting-to-postgres
Row Level Security https://supabase.com/docs/guides/database/postgres/row-level-security
Securing Edge Functions https://supabase.com/docs/guides/functions/auth
Clerk third-party auth https://supabase.com/docs/guides/auth/third-party/clerk
MCP server https://supabase.com/docs/guides/ai-tools/mcp
CLI reference https://supabase.com/docs/reference/cli
JavaScript client https://supabase.com/docs/reference/javascript/introduction

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 runs Key Postgres role
Anything you ship — browser, mobile, CLI Publishable sb_publishable_... anon, or authenticated once a user token is attached
Anything you control — server, Edge Function, cron Secret sb_secret_... service_role (has BYPASSRLS)

Facts that trip agents up:

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.

# 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)

{
  "mcpServers": {
    "supabase": {
      "type": "http",
      "url": "https://mcp.supabase.com/mcp?project_ref=<project-ref>&read_only=true&features=database,docs,debugging"
    }
  }
}
Param Effect
project_ref=<ref> Scope to one project; hides account tools
read_only=true Run 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.

Group Tools
Database list_tables, list_extensions, list_migrations, apply_migration, execute_sql
Debugging query_logs (read-only SQL over logs), get_advisors
Development get_project_url, get_publishable_keys, generate_typescript_types
Edge Functions list_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
Docs search_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

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

# 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

npm install @supabase/supabase-js
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

# 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 in Use Notes
Browser Data API (supabase-js) No connection string; RLS required
Vercel Functions / serverless Shared pooler, transaction mode (port 6543) Pool max: 1, prepare: false, ssl: 'require'
Migrations, pg_dump Direct (port 5432) IPv6 unless you buy the IPv4 add-on
Persistent backend on IPv4 only Shared pooler, session mode (port 5432)
High-throughput, paid plan Dedicated pooler db.<ref>.supabase.co:6543 Transaction 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.

// 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.

sequenceDiagram
    participant C as "Client"
    participant P as "Postgres + RLS"
    participant T as "posts table"
    C->>P: "select on posts as auth.uid"
    P->>P: "check policy auth.uid = user_id"
    alt "policy passes"
        P->>T: "read matching rows"
        T-->>C: "return user own posts"
    else "policy blocks"
        P-->>C: "return no rows"
    end
-- 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:
    [auth.third_party.clerk]
    enabled = true
    domain = "<your-instance>.clerk.accounts.dev"
    
  3. Give createClient an accessToken() callback that returns the Clerk session token.
// 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; } },
  );
}
// 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:

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:

// 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:

Call Verifies? Use for
getClaims() Yes — locally against cached JWKS (asymmetric keys, default for new projects) or via Auth server Protecting pages and data
getUser() Yes — network call to Auth When you need the fresh user record
getSession() No — reads the cookie Only 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 mode Accepts verify_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 apikey false
'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.

// 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 });
  }),
};
# 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

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:

{
  "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

Task How
Schema change supabase migration new → edit → db reset locally → db push
Types supabase gen types --linked --lang=typescript
Security / perf lints supabase db advisors or MCP get_advisors
Slow query MCP execute_sql with explain analyze, or supabase inspect db outliers
Read logs MCP query_logs (read-only SQL over logs)
Feature branch DB MCP create_branch / merge_branch (paid plan)

Troubleshooting

Issue Fix
Query returns empty rows A 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 table A missing grant, checked before RLS — even service_role hits it
Users signed out after every request Next 15 with a proxy.ts (needs middleware.ts), or the proxy returned a response without the refreshed cookies
Clerk policy never matches Owner column is uuid; Clerk IDs need text
prepared statement already exists Transaction pooler — set prepare: false / pgbouncer=true
Tenant or user not found Pooler username must be postgres.<project-ref>; copy the host from Connect
Edge Function returns 401 verify_jwt is on for a function called with an API key — set it false and use withSupabase
Secret key returns 401 in the browser By design — move the call server-side
supabase start fails Start Docker Desktop (or your container runtime)

codeAmani notes

Official docs: