Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

React
  • Backend vs Frontend: What Runs Where, and Why the Server Is the One You Trust
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
  • How a Web Page Works: HTML Tags, Elements and Attributes
  • Semantic HTML: header, nav, main, aside and footer as Page Landmarks
  • HTML Forms: Labels, Names, Input Types and Where the Data Goes (GET vs POST)
  • CSS Basics: Selectors, Which Rule Wins, and the Box Model
  • CSS Flexbox vs Grid: A Nav Bar, a Card Row and a Dashboard
  • Responsive CSS: Viewport, Mobile-First Media Queries, clamp() and Dark Mode with Tokens
  • JavaScript for People Who Already Code: Syntax, Modules and Five Surprises
  • JavaScript Arrays the Functional Way: map, filter, reduce, find, sort and Object.entries
  • Async JavaScript: Promises, async/await, fetch and Promise.all
  • JavaScript in the Page: the DOM, querySelector and Events
  • npm, package.json and Vite: What npm install Fetches and How Vite Serves and Builds Your Page
  • TypeScript Essentials: Types Checked, Then Erased (Interfaces, Unions, Generics)
  • Why React, JSX and Components: The Page as a Function of Data
  • React Props and Composition: Data Down, Calls Up, Children in the Slot
  • Routing With React Router: One Page, Many Addresses
  • React Component Tests With Vitest and Testing Library: Test What the User Sees
  • End-to-End Tests for a React App With Playwright: A Full Dress Rehearsal
  • Why AI-Built Websites All Look the Same, and Four Levels That Fix It
  • Visual Hierarchy, Spacing and the 8-Point Grid: Tell the Eye What to Read First
  • Colour, Contrast and Dark Palettes: 60-30-10, Semantic Tokens and Ratios You Can Compute
  • Typography That Sells: Type Scale, Line Length and Free Font Pairings
  • The UI Element Catalogue: Buttons to Toasts, Their Jobs, States and shadcn/ui Names
  • Design Tokens: Primitive and Semantic Tokens, from Figma to CSS to Tailwind
  • Tailwind CSS 4 in React: Utility Classes, Responsive Prefixes, Hover and Dark Mode
  • shadcn/ui in React: Components You Own, Edit and Commit
  • Design Tokens to a Tailwind Theme: Light and Dark Mode with @theme inline
  • Motion in React: Entrance, Hover, Exit and Layout Animations
  • A React Dashboard: Stat Cards, a Recharts Line Chart and a Sortable Table
  • Accessibility in Practice: Dialogs, Menus and the Keyboard in React
  • Reference-Driven Design: Extract a DESIGN.md From a Site You Admire and Build From It
  • Components, Variants and Variables: One Design System in Figma and in CSS
  • Figma MCP Server: Build a React Component From a Frame, Then Write It Back
  • Claude Design: From a Brief to a Clickable Prototype, Then Hand It Off to Claude Code
  • Critiquing AI-Generated UI: Six Checks for Every Screen
  • The AI Design Landscape: Prompt to UI, Prompt to App, and Design to Code
  • Your Brand Rules Folder: One Folder Every AI-Built Page Follows
  • The Best-Practice UI Prompt: Plain Sentences That Beat the Average AI Page
  • UI Ideas From Figma Make, Google Stitch and ChatGPT: One Prompt, Three Designs
  • Google Stitch From a Sketch or Screenshot: Show the Layout, Say What to Keep
  • Stitch to Figma to Code: Turn a Stitch Screen Into Code That Uses Your Tokens
  • Figma Make: Prompt to Prototype With a Four-Part Prompt
  • Upgrade a Dated UI From One Screenshot (or a Reference Image)
  • States and Feedback: Make Every Click Get an Answer
  • A Design-Loop Skill: Claude Screenshots, Scores and Fixes Its Own UI
  • Copy Without the AI Tells: A Copy Pass on a Landing Page
  • Running a Next.js Admin Starter Kit: Route Groups, Theme Tokens and npm run dev
  • Remotion Basics: A Video as One Composition Object, Frames, Sequences and the Player
  • Spline: Put a 3D Scene on a Landing Page Without Writing 3D Code
  • Framer: A Launch Page Without Code, From a Free Animated Template
  • Three.js: What It Can Do on Real Sites, and How to Let Your AI Agent Use It
  • Animated Component Libraries (Magic UI, Aceternity UI): Copy-In Motion and When It Becomes Noise
  • WebGPU and Three.js Shaders in TSL: A Living Gradient, 4,500 Particles and a Hover Ripple
  • Deploy Many Vite Demos as One Static Site: A Gallery Page, One Build Command and import.meta.env.BASE_URL
  • React State, Events, Lists and Conditional Rendering: Follow One Click
  • React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One
  • Lifting State Up, Refs and React DevTools: Put State Where It Is Needed
  • Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus
  • React Context and Custom Hooks: Share One Value, Reuse the Logic
  • Finishing a Remotion Video Editor: Timeline Sync, Track Order, Trims and Fades, and the Server MP4 Render
  • A 3D Product Page in React and Three.js: Scroll Becomes a Number, One Camera Shot per Panel, One Choice Drives Everything
  • A Personal 3D Portfolio Room in React Three Fiber: Hover Glow, Click to Open, Pointer Drift and a Contact Form to FastAPI
  • Server State With TanStack Query: One Key, One Request, One Cache
  • Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
  • Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
  • A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Forms With React Hook Form and Zod: The API's Rules in the Browser, the Server's Errors Under the Field
  • JWT Auth in a React Client With a FastAPI Backend: Log In, Carry the Token, Let the Server Decide
  • Supabase as a Backend: Postgres, Instant APIs, Row Level Security and the Two Keys
  • Email Login With Supabase in Next.js: Three Clients, Server Actions, the Callback Route and Middleware
  • Google Sign-In With Supabase in Next.js: Which Address Goes Where
  • hCaptcha on a Supabase Login Page: Site Key in the Browser, Secret in Supabase
  1. Blog
  2. /
  3. React
  4. /
  5. Working with APIs

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.

Chaand Sheikh

·27 November 2026·Updated 29 November 2026Working with APIs

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:

FileJob
lib/supabase/client.tsClient for code that runs in the browser
lib/supabase/server.tsClient for server code: actions, layouts, route handlers
lib/supabase/admin.tsService-role client for the users page
middleware.tsChecks the session on every request
app/(auth)/actions.tsLogin, sign-up and password functions the forms call
app/auth/callback/route.tsHandles the link in the confirmation email
sample.envTemplate 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:

  1. Connect at the top: copy the project URL.
  2. 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 copy service_role secret.
  3. Authentication → Sign in / Providers: allow new users to sign up is on, confirm email is on, and the email provider is enabled.
  4. Authentication → URL Configuration: the site URL is already http://localhost:3000. Under Redirect URLs, click add and enter http://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

Email sign-up flow 1. sign-up form signUp(email, pw) 2. Supabase saves user, sends email 3. user clicks confirmation link 4. /auth/callback ?code=...&next=... 5. exchangeCode ForSession: cookie 6. /dashboard signed in bad code: /login?error
The email link comes back to our own route, which swaps the code for a session cookie.

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/callback on 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 .env to .gitignore.
  • Running npm in the wrong folder. "Could not read package.json" means you're one level too high.

Quick recap

PieceKey call
Browser clientcreateBrowserClient(url, anonKey)
Server clientcreateServerClient with cookie getAll/setAll
Admin clientservice role key, import "server-only"
Sign upauth.signUp with emailRedirectTo the callback
Callbackauth.exchangeCodeForSession(code)
Middlewareauth.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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in React · 73 of 75

Previous
Supabase as a Backend: Postgres, Instant APIs, Row Level Security and the Two Keys
Next post
Google Sign-In With Supabase in Next.js: Which Address Goes Where

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.

On this page

  • One prompt, then read what it wrote
  • The env file
  • Three clients
  • The sign-up and login actions
  • From sign-up to signed in
  • The middleware guards every page
  • Run it
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.