SupabaseS
Supabaseβ€’2mo ago
desmond12

Next.js middleware with @supabase/ssr: auth.getUser() returns null even when auth cookie exists

Hey everyone πŸ‘‹ β€” I’m new to Supabase and trying to implement route protection in Next.js Middleware.
I’m using the @supabase/ssr client to fetch the user session, but supabase.auth.getUser() always returns user: null.


import { createServerClient } from '@supabase/ssr';
import { NextResponse } from 'next/server';

const protectedRoutes = {
  '/admin': ['system_admin'],
  '/director': ['system_admin', 'club_owner', 'tournament_director'],
};

export async function middleware(req) {
  let res = NextResponse.next();
  const supabase = createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        getAll: () => req.cookies.getAll(),
        setAll: (cookies) => {
          res = NextResponse.next();
          cookies.forEach(({ name, value, options }) =>
            res.cookies.set(name, value, options)
          );
        },
      },
    }
  );

  const { data: { user } } = await supabase.auth.getUser();
  console.log('πŸ” User:', user);

  const path = req.nextUrl.pathname;
  const baseUrl = process.env.NEXT_PUBLIC_BASE_URL1;

  const matched = Object.keys(protectedRoutes).find(r =>
    path === r || path.startsWith(r + '/')
  );

  if (matched && !user) {
    const redirectUrl = new URL('/auth/signin', baseUrl);
    redirectUrl.searchParams.set('redirectTo', path);
    return NextResponse.redirect(redirectUrl);
  }

  return res;
}

export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico|public|auth).*)'],
};
Was this page helpful?