Email Login With Supabase in Next.js: Three Clients, Server Actions, the Callback Route and Middleware
Connect a Next.js admin starter to Supabase: ask Claude Code for email login, fill the env file, turn on email confirmation and the callback redirect, then read the three clients, the sign-up action, the callback route and the middleware that guards every page.
What you will learn
- Fill the four env values from the Supabase dashboard and keep the service role key server-side
- Explain the browser, server and admin Supabase clients and when each one runs
- Follow a sign-up from the form to the confirmation email, the /auth/callback route and the session cookie
- Read the middleware that refreshes the session and protects pages
Before you start
- Supabase as a backend: RLS and the two keys
- A Next.js App Router project
Our admin UI runs, and we have a Supabase project with a URL and keys. Now we join the two. After this step the login page stops being a picture: it creates users, signs them in, and keeps them signed in. By the end, a new user signs up, confirms the email, and lands on the dashboard.
One prompt, then read what it wrote
We start in Claude Code, with the Frontend folder as the working directory so it can read the whole project first. Here's the sample prompt, in four parts:
Role: You're a Next.js and Supabase developer.
Context: This folder is our admin starter, a few Next.js pages with no backend yet.
Task: Add Supabase email and password login, sign up and forgot password, a navigation bar that changes once you're signed in, and admin pages only signed-in users can open. No social login for now.
Format: Change the code in the project, and write a sample env file that lists every value we need and where to find it in the Supabase dashboard.
Its summary lists four variables and one extra line: add the site URL, and the site URL plus /auth/callback, under Redirect URLs. Keep that line in mind.
Here's what it added:
| File | Job |
|---|---|
lib/supabase/client.ts | Client for code that runs in the browser |
lib/supabase/server.ts | Client for server code: actions, layouts, route handlers |
lib/supabase/admin.ts | Service-role client for the users page |
middleware.ts | Checks the session on every request |
app/(auth)/actions.ts | Login, sign-up and password functions the forms call |
app/auth/callback/route.ts | Handles the link in the confirmation email |
sample.env | Template for the values |
The env file
sample.env lists four values. The values below are the placeholders from that file, not real keys:
# Dashboard -> Project Settings -> Data API -> "Project URL"
NEXT_PUBLIC_SUPABASE_URL=https://your-project-ref.supabase.co
# Dashboard -> Project Settings -> API Keys -> "anon" "public" key
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-public-key
# SECRET. Bypasses Row Level Security. Server-side ONLY.
# Required only for the /users admin page.
SUPABASE_SERVICE_ROLE_KEY=your-service-role-secret-key
# Used to build the links in confirmation and password-reset emails.
NEXT_PUBLIC_SITE_URL=http://localhost:3000
Look at the prefix. Next.js sends anything that starts with NEXT_PUBLIC_ to the browser. The URL and the anon key carry it. The service role key doesn't, on purpose, so it stays on the server.
In PyCharm, right-click Frontend, create a file called .env, and paste the sample in. Claude's note suggests .env.local, and that name is better because git already ignores it. Plain .env also works with the dev server, but then make sure it never goes into git, because it holds the service role key.
Now fill it from the dashboard:
- Connect at the top: copy the project URL.
- Project settings → API keys: the code reads the anon key, so open the second tab with the classic pair. Copy
anon public. Then reveal and copyservice_role secret. - Authentication → Sign in / Providers: allow new users to sign up is on, confirm email is on, and the email provider is enabled.
- Authentication → URL Configuration: the site URL is already
http://localhost:3000. Under Redirect URLs, click add and enterhttp://localhost:3000/auth/callback. That's the line Claude asked for, because the confirmation link comes back to that route.
Three clients
The browser client is short. Pages that run in the browser use it:
import { createBrowserClient } from "@supabase/ssr";
export function createClient() {
return createBrowserClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
);
}
The server client takes the same two values. The difference is cookies: the session is kept in a cookie, so the server client reads them with getAll and writes them with setAll. In Next.js 15 cookies() is async, so the helper is async too.
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) {
try {
cookiesToSet.forEach(({ name, value, options }) =>
cookieStore.set(name, value, options),
);
} catch {
// Called from a Server Component. Middleware refreshes the session.
}
},
},
},
);
}
The admin client uses the service role key. It imports server-only, so if anyone imports it into browser code, the build fails. If the key is empty it returns null, and the users page shows "admin key not configured".
import "server-only";
import { createClient } from "@supabase/supabase-js";
export function createAdminClient() {
const url = process.env.NEXT_PUBLIC_SUPABASE_URL;
const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
if (!url || !serviceKey) return null;
return createClient(url, serviceKey, {
auth: { autoRefreshToken: false, persistSession: false },
});
}
The sign-up and login actions
actions.ts starts with "use server", so these functions run on the server. Sign-up checks the password first, then calls Supabase:
export async function signup(_prev: AuthState, formData: FormData): Promise<AuthState> {
const name = String(formData.get("name") ?? "").trim();
const email = String(formData.get("email") ?? "").trim();
const password = String(formData.get("password") ?? "");
const confirm = String(formData.get("confirm") ?? "");
if (!email || !password) return { error: "Enter your email and password." };
if (password.length < 6) return { error: "Password must be at least 6 characters." };
if (password !== confirm) return { error: "Passwords do not match." };
const origin = await getOrigin();
const supabase = await createClient();
const { data, error } = await supabase.auth.signUp({
email,
password,
options: {
data: { full_name: name },
emailRedirectTo: `${origin}/auth/callback?next=/dashboard`,
},
});
if (error) return { error: error.message };
// When email confirmation is enabled, no session is returned yet.
if (data.user && !data.session) {
return { message: "Check your inbox to confirm your email, then sign in." };
}
revalidatePath("/", "layout");
redirect("/dashboard");
}
With confirm email on, Supabase creates the user but gives no session yet, so the form shows the "check your inbox" message. Login is simpler: supabase.auth.signInWithPassword({ email, password }), and if there's no error it redirects to the dashboard.
From sign-up to signed in
The callback route is where the code becomes a session:
export async function GET(request: Request) {
const { searchParams, origin } = new URL(request.url);
const code = searchParams.get("code");
const next = searchParams.get("next") ?? "/dashboard";
if (code) {
const supabase = await createClient();
const { error } = await supabase.auth.exchangeCodeForSession(code);
if (!error) {
return NextResponse.redirect(`${origin}${next}`);
}
}
return NextResponse.redirect(
`${origin}/login?error=${encodeURIComponent("Sorry, we couldn't verify that link. Please try again.")}`,
);
}
The middleware guards every page
middleware.ts runs before every page except static files and the callback (the callback swaps the code itself and must not be intercepted):
export const config = {
matcher: [
"/((?!_next/static|_next/image|favicon.ico|auth/callback|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
],
};
It calls updateSession, which builds a server client on the request cookies, then calls getUser(). That call also refreshes the session and writes the new cookie back. Then it decides:
// IMPORTANT: do not run any logic between createServerClient and getUser().
const {
data: { user },
} = await supabase.auth.getUser();
const { pathname } = request.nextUrl;
const isAuthRoute = ["/login", "/signup", "/forgot-password"].includes(pathname);
const isPublic = PUBLIC_ROUTES.includes(pathname);
// Not signed in and visiting a protected page: send to login.
if (!user && !isPublic) {
const url = request.nextUrl.clone();
url.pathname = "/login";
url.searchParams.set("redirectTo", pathname);
return NextResponse.redirect(url);
}
// Already signed in but on an auth screen: send to the dashboard.
if (user && isAuthRoute) {
const url = request.nextUrl.clone();
url.pathname = "/dashboard";
url.search = "";
return NextResponse.redirect(url);
}
So signed out, /dashboard lands you on /login?redirectTo=/dashboard. Signed in, /login sends you to the dashboard.
Run it
Claude added two Supabase packages, so install first. In the lecture, npm install failed with "could not read package.json", because the terminal was in the parent folder. cd Frontend fixed it, and the install said "up to date, audited 61 packages". Then npm run dev showed the app on localhost:3000, with "Environments: .env", so our values were loaded.
The navigation bar now shows Sign in and Get started. Sign up with a full name, email and password, and you get "Check your inbox to confirm your email, then sign in." Click the link in the email from Supabase, it goes through our callback, and the dashboard opens, signed in. In Supabase under Authentication → Users, the new user is there with provider email.
Common mistakes
- Forgetting the redirect URL. Without
/auth/callbackon the list, the confirmation link can't come back to your app. - Putting
NEXT_PUBLIC_on the service role key. That ships the key to every browser. - Committing
.env. Use.env.local, or add.envto.gitignore. - Running npm in the wrong folder. "Could not read package.json" means you're one level too high.
Quick recap
| Piece | Key call |
|---|---|
| Browser client | createBrowserClient(url, anonKey) |
| Server client | createServerClient with cookie getAll/setAll |
| Admin client | service role key, import "server-only" |
| Sign up | auth.signUp with emailRedirectTo the callback |
| Callback | auth.exchangeCodeForSession(code) |
| Middleware | auth.getUser(), then redirect by route |
Try it yourself
Sign out, open /dashboard, and see where the middleware sends you. Then look at the address bar: the redirectTo value tells you which line of the middleware ran.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Server State With TanStack Query: One Key, One Request, One Cache
Three components need the same list of books. Fetch it by hand and you get three requests; ask TanStack Query for one key and you get one. With real request counts, retries and a quiet refetch on tab focus.
Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
Add a book with useMutation and let invalidateQueries refetch the list, then make delete instant: snapshot, remove the row in 3 ms, roll back on a 404 and refetch the truth in onSettled.
Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
Let the API's OpenAPI spec write your React client: Orval turns /v3/api-docs into TypeScript types, useGetBooks and a Zod schema, and a renamed field becomes error TS2339 at BookList.tsx line 26.
A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
Build the React screen before the API exists: Orval writes MSW handlers and faker data from the spec, a service worker answers GET /api/books inside the browser, and npm run dev:real switches back to the real server.
