How to get a session in NextJS Middleware

I have an application that was set up using NextJS 15.3.1 and the 4.0.0-beta.0 nextjs-auth0 SDK. I can see that this SDK has been brought into a stable version and am attempting to update to use it but am running into an issue.

How can I access a session object from my middleware? My original middleware setup was something like…

export async function middleware(request: NextRequest) {
    const businessUnit = detectBusinessUnitFromRequest(request);
    const auth0 = await createAuth0Client(businessUnit);
    const authResponse = await auth0.middleware(request);

    if (request.nextUrl.pathname.startsWith('/auth')) {
        return authResponse;
    }

    const session = await auth0.getSession();

    // assorted route access checks based on user permissions from the session object

    return authResponse;
}

export const config = {
    matcher: ["/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)"],
} 

That await auth0.getSession() now throws a NextJS error for calling cookies outside of a request scope. What is the alternative? How else can I access the users data and access tokens here in the middleware?

Hi @relero90

Thank you for reaching out to us!

Could you try changing your middleware function like this and let me know if the results change?

export async function middleware(request: NextRequest) {
  const { origin } = new URL(request.url)
  const res = await auth0.middleware(request)
  const session = await auth0.getSession()

  if (!session && !request.nextUrl.pathname.startsWith("/auth")) {
    console.log("No session found, redirecting to login")
    return NextResponse.redirect(`${origin}/auth/login`)
  }

  return res
}

I would suggest looking through the following Post as it was on a similar use-case.

Hope this helped!
Gerald

Thank you. The post you linked provided the correct clue. It is now necessary to pass the request object to getSession:

export async function middleware(request: NextRequest) {
   ...

    const session = await auth0.getSession(request);

    ...
}
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.