Tutorial8 min read

Build a Web App With Next.js and Supabase

Ship a working full-stack app on Next.js and Supabase: auth, Postgres, row-level security and deployment, with the code for each step.

UL

Ullass Engineering Team

Editorial Team — Software Development & Digital Products

What You Are Actually Assembling

Next.js and Supabase are two decisions that only look unrelated. Next.js owns rendering, request routing and the build. Supabase owns a managed PostgreSQL instance, an auth server, object storage and a realtime channel. The reason teams pick this pairing over "Next.js plus a Node API plus a Postgres box" is one specific property: Supabase exposes your database to the application through PostgREST using the anon key, and gates every query with row-level security. A bug in your route handler then degrades into "the user sees nothing" instead of "the user sees another tenant's invoices".

That is a real difference, and it is also the only one worth paying for. Everything else here is plumbing. We will build a small project tracker: a projects table, a signed-in dashboard, and an endpoint that creates projects. The shape matters more than the domain, and the whole stack — framework, database, auth and file storage — costs nothing until you need a domain and a database with more than 500MB of storage.

It is worth being explicit about what Supabase is not. It is not a managed Kubernetes cluster you can reshape freely, and the free tier will not survive a launch. Treat it as an unusually well-instrumented managed Postgres with a generous API around it, and you will make the right architectural bets: you can always export the schema and run it elsewhere, which is why the migrations in this guide are plain SQL rather than a series of dashboard clicks.

Setting Up the Project and Environment

Scaffold with TypeScript and the App Router, then install the two Supabase packages. @supabase/supabase-js is the client itself; @supabase/ssr is the adapter that makes it respect Next's cookie handling and that performs the PKCE code exchange in the browser.

bash
npx create-next-app@latest project-tracker --ts --tailwind --app --eslint cd project-tracker npm install @supabase/supabase-js @supabase/ssr npm install -D supabase npx supabase init

supabase init writes supabase/config.toml and links the directory to a Supabase project. Install it even if you never run a local database, because supabase db push later replays your migrations against the cloud instance in order — that is what keeps schema drift out of production.

Environment variables go in .env.local, which Next loads in development and gitignores by default:

bash
# Project settings -> API in the Supabase dashboard NEXT_PUBLIC_SUPABASE_URL=https://abcdefghijklmnop.supabase.co NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOi... # Project settings -> Database -> Connection string, password appended separately SUPABASE_DB_PASSWORD=your-database-password

The anon key is designed to be public; it ships to every browser. Security comes from RLS, not from hiding the key. What must never reach a repo is the service_role key, which bypasses RLS entirely, and the database password. Treat a leaked service_role key the way you would treat a leaked root password, because operationally it is the same thing.

Two Supabase Clients, Not One

The most common mistake in Supabase apps is creating one client and using it everywhere. That produces either a session that never refreshes, or a refresh race where two components refresh simultaneously and one of them signs the user out.

The server client

This is the client for every Server Component, Server Action and Route Handler. The write-back half of the cookies adapter is the part people omit, and it is the part that makes long sessions work: Supabase rotates tokens roughly hourly, and if the refreshed cookie is dropped instead of written, the user is silently signed out on the next navigation.

ts
// 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_ANON_KEY!, { cookies: { getAll() { return cookieStore.getAll(); }, setAll(cookiesToSet) { for (const { name, value, options } of cookiesToSet) { cookieStore.set(name, value, options); } }, }, }, ); }

Because this calls cookies(), the function is dynamic and the page cannot be statically rendered. That is correct — an authenticated page should never be served from a shared cache. It also means every server render opens a Postgres connection, which is the constraint that eventually decides your hosting bill.

The browser client and middleware

Client Components need their own client, and the session needs refreshing on every navigation. Supabase's guide to server-side authentication with Next.js puts that refresh in middleware, which runs before rendering on both server and client navigations.

ts
// lib/supabase/client.ts import { createBrowserClient } from "@supabase/ssr"; export function createClient() { return createBrowserClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, ); }
ts
// middleware.ts import type { NextRequest } from "next/server"; import { updateSession } from "@/lib/supabase/middleware"; export async function middleware(request: NextRequest) { return await updateSession(request); } export const config = { matcher: ["/((?!_next/static|_next/image|favicon.ico|og).*)"], };

updateSession calls auth.getUser(), writes refreshed cookies onto the request, and — the step most examples skip — rebuilds the response so the browser receives the new token:

ts
// lib/supabase/middleware.ts import { createServerClient } from "@supabase/ssr"; import { NextResponse, type NextRequest } from "next/server"; export async function updateSession(request: NextRequest) { let supabaseResponse = NextResponse.next({ request }); const supabase = createServerClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, { cookies: { getAll: () => request.cookies.getAll(), setAll(cookiesToSet) { for (const { name, value } of cookiesToSet) { request.cookies.set(name, value); } supabaseResponse = NextResponse.next({ request }); for (const { name, value, options } of cookiesToSet) { supabaseResponse.cookies.set(name, value, options); } }, }, }, ); const { data: { user } } = await supabase.auth.getUser(); if (!user && !request.nextUrl.pathname.startsWith("/login")) { const url = request.nextUrl.clone(); url.pathname = "/login"; return NextResponse.redirect(url); } return supabaseResponse; }

Keep every line between createServerClient and getUser free of async work. Awaiting something in that window lets a concurrent refresh overwrite the cookie set, which presents to users as a logout with no obvious cause. Supabase sets its session cookies with SameSite=Lax and Secure in production; if you need a cookie to survive a cross-site redirect — a Stripe return URL, for example — read the Set-Cookie semantics on MDN before loosening it.

Authentication With a Server Action

Sign-in is a Server Action posting form data. The redirect has to happen outside the try block, because redirect() signals control flow by throwing a sentinel exception that a broad catch will happily swallow — the symptom is "sign-in succeeds and then nothing happens".

ts
// app/(auth)/login/actions.ts "use server"; import { redirect } from "next/navigation"; import { createClient } from "@/lib/supabase/server"; export async function signIn(formData: FormData) { const email = String(formData.get("email") ?? ""); const password = String(formData.get("password") ?? ""); const supabase = await createClient(); const { error } = await supabase.auth.signInWithPassword({ email, password }); if (error) { return { error: "That email and password combination did not work." }; } redirect("/dashboard"); }

Returning a plain object on failure lets the form render the message inline. Never surface the raw Supabase error string: it distinguishes "no such user" from "wrong password", which is an account-enumeration leak. Map errors to fixed strings the way above and you close it for free.

Row-Level Security, Written Properly

RLS is the actual security boundary. Enabling it does nothing on its own, because with RLS enabled and no policy every row becomes invisible — so a half-configured table produces an app that looks broken rather than one that looks dangerous. Write policies in a migration, not ad hoc in the dashboard, and cover INSERT and UPDATE separately. A SELECT policy silently allows no writes at all, and plenty of apps ship exactly that.

sql
-- supabase/migrations/0001_projects.sql create table public.projects ( id uuid primary key default gen_random_uuid(), owner_id uuid not null references auth.users (id) on delete cascade, name text not null check (char_length(name) between 1 and 120), archived boolean not null default false, created_at timestamptz not null default now() ); alter table public.projects enable row level security; create policy "read own projects" on public.projects for select using (auth.uid() = owner_id); create policy "insert own projects" on public.projects for insert with check (auth.uid() = owner_id); create policy "update own projects" on public.projects for update using (auth.uid() = owner_id) with check (auth.uid() = owner_id);

Three details carry the weight. with check on INSERT is what stops a client from creating a row owned by somebody else. Adding with check to UPDATE stops a user from reassigning a row to a victim and reading it afterwards. And auth.uid() returns NULL for anonymous requests, so NULL = owner_id evaluates to unknown rather than true — unauthenticated traffic reads nothing at all. The rules are spelled out in the Supabase row-level security guide; the underlying semantics are in the PostgreSQL manual on row security policies.

Turn this on from the first migration rather than retroactively. Enabling RLS after launch means auditing every live query for rows you are about to start hiding, and that audit is where incidents come from.

Reading Data in a Server Component

Reads belong on the server, where the query costs no client bundle. The owner_id filter is redundant with the policy; keep it for the common case, but understand that it is not what protects you, and that it must come from the session rather than from props.

tsx
// app/dashboard/page.tsx import { createClient } from "@/lib/supabase/server"; import { redirect } from "next/navigation"; export default async function DashboardPage() { const supabase = await createClient(); const { data: { user } } = await supabase.auth.getUser(); if (!user) redirect("/login"); const { data: projects, error } = await supabase .from("projects") .select("id, name, created_at") .eq("archived", false) .order("created_at", { ascending: false }) .limit(50); if (error) { throw new Error("Failed to load projects: " + error.message); } return ( <ul> {projects.map((project) => ( <li key={project.id}> {project.name} — {new Date(project.created_at).toLocaleDateString()} </li> ))} </ul> ); }

This avoids two things. There is no API route, so there is no second place to authorise the read. And React dedupes identical fetches within a render pass, so three components reading the same table cost one round trip. If you want the row shape in the editor, run npx supabase gen types typescript --linked and annotate results as Database["public"]["Tables"]["projects"]["Row"], which turns a renamed column into a compile error instead of a runtime undefined.

Notice what is not in that query: no or filter, no user_id.eq(input), no branching on a role column. When a request reads on behalf of someone else, that is the moment to reach for the service_role client inside a tightly scoped server function — and the moment to ask whether the feature is worth permanently widening your blast radius.

Writing Data Through a Route Handler

Use a Server Action for form-driven writes and a Route Handler when a webhook, a mobile client or a third party needs an endpoint. Validate at the boundary either way: RLS checks authorisation, never whether name is a string.

ts
// app/api/projects/route.ts import { NextResponse, type NextRequest } from "next/server"; import { z } from "zod"; import { createClient } from "@/lib/supabase/server"; const CreateProject = z.object({ name: z.string().min(1).max(120), }); export async function POST(request: NextRequest) { const parsed = CreateProject.safeParse(await request.json().catch(() => null)); if (!parsed.success) { return NextResponse.json( { error: { code: "validation_failed", details: parsed.error.flatten() } }, { status: 422 }, ); } const supabase = await createClient(); const { data: { user } } = await supabase.auth.getUser(); if (!user) { return NextResponse.json({ error: { code: "unauthenticated" } }, { status: 401 }); } const { data, error } = await supabase .from("projects") .insert({ ...parsed.data, owner_id: user.id }) .select("id, name, created_at") .single(); if (error) { return NextResponse.json({ error: { code: "insert_failed" } }, { status: 500 }); } return NextResponse.json({ data }, { status: 201 }); }

Take owner_id from the session, never from the request body, even though the policy would reject a forged value anyway. Defence in depth costs nothing; debugging why a legitimate insert failed does.

Deployment and the Three Things That Break

Push migrations before code, then deploy:

bash
# 1. Schema first — every migration we ship is backwards compatible on its own npx supabase db push --linked # 2. Environment variables, which are not in your repository npx vercel env add NEXT_PUBLIC_SUPABASE_URL production npx vercel env add NEXT_PUBLIC_SUPABASE_ANON_KEY production # 3. Deploy npx vercel --prod

Three failure modes account for most of the tickets we get on apps built this way.

  1. Redirect URLs. Supabase only returns sessions to origins listed under Authentication → URL Configuration, and every preview deployment is a new origin. Without that entry, email-confirmation links land on a dead page and the flow looks broken end to end.
  2. Server Action error redaction. Development builds return full stack traces, which leak table names and query text to whoever triggered the error. Ship with NODE_ENV=production and confirm your host honours it.
  3. Connection exhaustion. Every server render opens a connection. Sustained concurrency above your plan's pool ceiling produces failures that look like random timeouts, so watch the connection monitor in the dashboard before your traffic does. See our cloud and DevOps service page for how we size and monitor that.

If you are scoping this rather than building it alone, our web development service covers how we estimate a build like this, SaaS development is the relevant read if billing and multi-tenancy come next, and the Posnova project is a production example of Next.js on a managed Postgres backend. Get in touch for a scoped estimate.

How Ullass can help

This guide covers the theory. If you would rather have it implemented and operated for you, these are the services that cover it.

Related Articles

Ullass — Software Development Company

We build web apps, SaaS platforms, and digital products

Ullass designs, engineers, and scales software products for ambitious businesses. Also try our free online tools at tools.ullass.com. Questions? hello@ullass.com