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

3

10

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

Fite answered 18/11, 2021 at 15:37 Comment(0)
P
4

you can get the session inside of the middleware like this.

import { NextRequest, NextResponse } from 'next/server';
import { withMiddlewareAuthRequired, getSession } from '@auth0/nextjs-auth0/edge';

export default withMiddlewareAuthRequired(async (req: NextRequest) => {
  const res = NextResponse.next();

  const user = await getSession(req, res);

  if (user) {
    // Do what you want...
  }

  return res;
});

// only work on the '/' path
export const config = {
  matcher: '/',
};

Found it here, hope it helps!

https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md

Pandemic answered 12/1, 2023 at 18:27 Comment(0)
M
4

Checking for the existing of the appSession cookie like corysimmons described works for routing use cases, if you want your middleware to securely check if the user is logged in you could try this:

import { getSession } from '@auth0/nextjs-auth0/edge';
import { NextRequest, NextResponse } from 'next/server'

export default async function middleware(req: NextRequest) {
  const response = NextResponse.next();

  const session = await getSession(req, response);

  if (req.nextUrl.pathname === '/' && session?.user) {
    return NextResponse.redirect(new URL('/app', req.url))
  }
  if (req.nextUrl.pathname.startsWith('/app') && !session?.user) {
    return NextResponse.redirect(new URL('/', req.url))
  }

  return NextResponse.next();
}

The trick is to import getSession from the edge package. This gives you more flexibility in case you need to combine multiple middlewares like described here. NextJs NestedMiddleware

Using withMiddlewareAuthRequired from the auth0 package, does not allow you to use other middlewares as far as I could tell.

Meliorism answered 10/6, 2023 at 15:33 Comment(0)
S
0

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('/')
  }
}
Signalment answered 8/2, 2022 at 6:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.