'How can I use auth0 getSession() from nextjs middleware function, or is there some other way to get user particulars via middleware

I have this code in /pages/api/_middleware.js:

import { getSession } from '@auth0/nextjs-auth0'

export default async function middleware(req, ev) {
    const session = await getSession(req)
    console.log(session)
    return NextResponse.next()
}

Whenever I run an API call that hits this I get this message:

error - node_modules@auth0\nextjs-auth0\dist\index.browser.js?b875 (11:0) @ Object.getSession Error: The getSession method can only be used from the server side



Solution 1:[1]

I'm not sure it's possible with the @auth0/nextjs-auth0 lib, but I'm lazily just checking if the appSession cookie is in storage like so:

import type { NextRequest } from 'next/server'

export function middleware(req: NextRequest) {
  if (req.nextUrl.pathname === '/' && req.cookies.appSession) {
    return Response.redirect('/app')
  }
  if (req.nextUrl.pathname === '/app' && !req.cookies.appSession) {
    return Response.redirect('/')
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 corysimmons