Skip to content
SPEN10
All guides

Add a database and auth to a Next.js app with Supabase

Set up Supabase Postgres, Row Level Security and email login in a Next.js App Router project — the secure way.

2 min read

A woman holding a tablet next to a glass wall of server racks
Photo by Christina Morillo on StockSnap

Supabase gives you Postgres, authentication and auto-generated APIs. Paired with Next.js, it's one of the quickest ways to get a real backend. The key to doing it safely is Row Level Security (RLS).

1. Create the project

Create a project at supabase.com, then copy the Project URL and anon (publishable) key into .env.local:

NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key

The anon key is safe in the browser only because RLS protects your tables. Never expose the service role key.

2. Install the clients

npm install @supabase/supabase-js @supabase/ssr

@supabase/ssr stores the session in cookies so Server Components, Server Actions and the browser all see the same user.

3. Create a table with RLS

create table public.notes (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null references auth.users (id) default auth.uid(),
  body text not null,
  created_at timestamptz not null default now()
);

alter table public.notes enable row level security;

create policy "Users manage their own notes" on public.notes
  for all to authenticated
  using ((select auth.uid()) = user_id)
  with check ((select auth.uid()) = user_id);

With RLS enabled and no policy, a table is locked. Each policy opens exactly one door.

4. Query from a Server Component

const supabase = await createClient();
const { data: notes } = await supabase
  .from("notes")
  .select("id, body, created_at")
  .order("created_at", { ascending: false });

Because RLS runs inside Postgres, this query can only ever return the signed-in user's notes — even if your app code has a bug.

5. Test the rules

Sign in as two different users and confirm neither can see the other's data. Then try the API with no session at all. Testing your policies is the single most valuable security habit with Supabase.

Found this useful?

Get the next one in your inbox. No spam, unsubscribe anytime.