Error Error: `cookies` was called outside a request scope

Hello!

I was following this quickstart guide.

I tried to comment the usecase with /:


import { NextResponse } from "next/server";
import { auth0 } from "./lib/auth0"

export async function middleware(request) {
    try {
        const authRes = await auth0.middleware(request);

        // authentication routes — let the middleware handle it
        if (request.nextUrl.pathname.startsWith("/auth")) {
            return authRes;
        }

        // public routes — no need to check for session
        if (request.nextUrl.pathname === ("/")) {
            // COMMENTED.
            // return authRes;
        }


        const { origin } = new URL(request.url)
        const session = await auth0.getSession()
        // user does not have a session — redirect to login
        if (!session) {
            return NextResponse.redirect(`${origin}/auth/login`)
        }


        return authRes
    } catch (e) {
        console.info('error', e)
    }
}

export const config = {
    matcher: [
        /*
         * Match all request paths except for the ones starting with:
         * - _next/static (static files)
         * - _next/image (image optimization files)
         * - favicon.ico, sitemap.xml, robots.txt (metadata files)
         * - api (API routes)
         */
        "/((?!_next/static|_next/image|favicon.ico|file.svg|globe.svg|next.svg|vercel.svg|window.svg|sitemap.xml|robots.txt|api).*)",
    ],
}

However, I got the error

error Error: `cookies` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context
    at middleware (src/middleware.js:23:32)
  21 |   
  22 |     const { origin } = new URL(request.url)
> 23 |     const session = await auth0.getSession()

The error redirects me to dynamic-api doc page but it doesn’t give me a clue why with commented line for / I got it.

My intention to protect all routes under Auth0, even a a root one.

thx!

Ran into the same issue, you need to pass the request to getSession().

Thank you, that resolved my initial issue.

However, I’m facing another problem, which I’ve described in my latest comment on issue #2081.

Could you please let me know if a solution is available or if this has been addressed in a newer version? This is a high priority for me as my application is in production.

Any help would be greatly appreciated.

The error “cookies was called outside a request scope” happens because when you commented out return authRes; for the root path (/), you prevented the Auth0 middleware from fully processing the request and setting up the necessary context for auth0.getSession(). To fix this and protect all routes (including /), simply remove the if (request.nextUrl.pathname === ("/")) block entirely. This ensures that auth0.middleware(request) runs for all matched routes, correctly preparing the environment for session checks and allowing auth0.getSession() to function as intended.

I have this to prevent user to access the “/” when they are not log in

The error “cookies was called outside a request scope” in your Next.js middleware occurs because auth0.getSession() needs the request context to be properly set up, which is typically done by auth0.middleware(request). When you commented out return authRes; for the root path (/), the execution continued past auth0.middleware(request) without its intended return, leading to getSession() being called in an invalid state. To protect all routes, including /, you should always call auth0.middleware(request) first and then return its result immediately if the path starts with /auth. For all other paths, proceed to check auth0.getSession() and redirect if no session exists, otherwise let the request proceed.