Fixing Supabase Auth in Next.js Middleware: A Common Issue Explained

Fixing Supabase Auth in Next.js Middleware: A Common Issue Explained

Fixing Supabase Auth in Next.js Middleware: A Common Issue Explained

If you've been struggling to get authentication working with Supabase and Next.js middleware, you're not alone. This is a common issue faced by developers using Supabase in server-side rendered (SSR) environments. In this post, I’ll explain the problem and how I fixed it—step-by-step.

The Problem

Symptoms:

  • Middleware doesn’t detect any Supabase auth cookies.
  • getSession() or getUser() return null in middleware, even after signing in.
  • Authentication appears successful on the client, but protected SSR/admin routes remain inaccessible.

Root Cause:

  • Supabase sessions are stored in localStorage by default—which middleware can’t access.
  • Cookies are either not being set at all or are misconfigured (wrong domain/path/SameSite settings).

How I Fixed It

After a lot of trial and error, here's what solved the issue for me:

1. Use Cookie-Based Session Storage

  • Configure Supabase to persist the session in both localStorage and cookies.
  • This allows middleware to read the session tokens using HTTP cookies.

2. Set Up the Supabase Client for SSR

  • Use @supabase/auth-helpers-nextjs or @supabase/ssr.
  • In middleware, create a Supabase client with createServerClient() and pass cookies from the request.

3. Proper Cookie Handling in Middleware

  • Read the sb-access-token and sb-refresh-token from cookies.
  • Use supabase.auth.getUser() to verify the user session.
  • Set updated cookies on the response with response.cookies.set().

4. Verify Cookie Settings

  • Ensure cookies are sent to all relevant routes (set path=/).
  • Use SameSite=Lax or Strict appropriately.
  • Double-check domain settings—especially if you're testing on localhost.

Success Flow (Logs)

  • ✅ Session Found: hasSession: true
  • ✅ User Authenticated: sessionUserId: 'fa638614-bed1-4359-9fe2-990c81db582a'
  • ✅ Cookies Present: sb-auth-token with 2192 characters
  • ✅ Admin Role Verified: userRole: 'admin'
  • ✅ Access Granted: Middleware passed!
  • ✅ Dashboard Loaded: GET /admin/dashboard 200

Wrapping Up

If you're using Supabase with Next.js and running into issues with auth in middleware, this fix should help. The key is to ensure your session tokens are stored in cookies—not just localStorage—and that your middleware is correctly configured to read and update those cookies. Once everything’s set up, you’ll enjoy secure, persistent auth even across page refreshes and SSR routes.