# How to get a session in NextJS Middleware

**URL:** <https://community.auth0.com/t/how-to-get-a-session-in-nextjs-middleware/188482>\
**Category:** Get Help\
**Tags:** sdks-quickstarts, nextjs-auth0\
**Created:** [June 26, 2025, 11:19pm UTC](https://community.auth0.com/t/how-to-get-a-session-in-nextjs-middleware/188482 "2025-06-26T23:19:24Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![gerald.czifra](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/gerald.czifra/32/75301_2.png) [@gerald.czifra](https://community.auth0.com/u/gerald.czifra)\
**Post date:** [June 30, 2025, 6:26pm UTC](https://community.auth0.com/t/how-to-get-a-session-in-nextjs-middleware/188482/3 "2025-06-30T18:26:37Z")

</div>

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?

```auto
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](https://community.auth0.com/t/error-error-cookies-was-called-outside-a-request-scope/188318/3) as it was on a similar use-case.

Hope this helped!  
Gerald

---

_[View the full topic](https://community.auth0.com/t/how-to-get-a-session-in-nextjs-middleware/188482)._
