SupabaseS
Supabase•3y ago
Masini

Auth Session is being Null in Next JS Middleware

I am using Next 14 and wrote this simple middleware (taken from the documentation):

import { createMiddlewareClient } from '@supabase/auth-helpers-nextjs'
import { NextRequest, NextResponse } from "next/server";

export async function middleware(req: NextRequest) {
    const res = NextResponse.next()
    const supabase = createMiddlewareClient({ req, res })
    const { data: { session } } = await supabase.auth.getSession()

    console.log("SESSION: ", session)
    
    if(session && req.nextUrl.pathname === '/')
    {
        return NextResponse.redirect(new URL('/dashboard', req.url));
    }

    if(!session && req.nextUrl.pathname !== '/login')
    {
        return NextResponse.redirect(new URL('/login', req.url));
    }

    return res;
}

export const config = {
    matcher: ['/', '/dashboard', '/login']
}


However, even with a session being available in the client side (I am able to check this from console logs) the session in the middleware is always being null. Honestly I have no idea what is wrong here since I followed the documentation for this and it's still not working. Any help would be gladly appreciated šŸ™‚
Was this page helpful?