Cannot access the NextAuth session data in Next.js 12 middleware
Asked Answered
S

2

7

I am trying to implement route protection using the new Next.js 12 middleware function. But it occurs to me that every time I try to access the session I get null. Hence not getting the expected result. Why is that?

import { NextResponse, NextRequest } from 'next/server'
import { getSession } from "next-auth/react"

//This acts like a middleware, will run every time for pages under /dashboard, also runs for the nested pages
const redirectUnauthenticatedUserMiddleware = async (req, ev) => {
     const session = await getSession({ req })
     if (!session) {
         return NextResponse.redirect('/login')
     }
    return NextResponse.next()
}

export default redirectUnauthenticatedUserMiddleware 
Shoemaker answered 29/11, 2021 at 16:25 Comment(2)
I had a similar issue, maybe this question I raised would help #67235294Elrod
any updates regarding this matter?Mayle
M
10

There's another ways on how you can get access to your session.

Here we're using getToken from next-auth/jwt. to note:

  • must use or declared secret as an option in NextAuth function (related reference here). If not, it will not work. Doesn't matter if you use session or jwt option. Both will work.
export default NextAuth({
  secret: process.env.SECRET,
  ...otherOptions
})
  • currently I don't know whether it will work or not if you don't use token. Or you use database option only. Or adapter. I'm not sure since currently I'm unable to make adapter work just yet. So that's that.

Here is an example _middleware.js:-

import { getToken } from 'next-auth/jwt';
import { NextResponse } from 'next/server';

export async function middleware(req, ev) {
  // 'secret' should be the same 'process.env.SECRET' use in NextAuth function
  const session = await getToken({ req: req, secret: process.env.SECRET }); console.log('session in middleware: ', session)

  if(!session) return NextResponse.redirect('/')
  
  return NextResponse.next()
}

If you already found a solution on how to make use getSession. You may upload your answer and share with us. Thank you.

Mayle answered 20/12, 2021 at 9:39 Comment(2)
const session = await getSession({ req: req, secret: process.env.SECRET }); console.log('session in middleware: ', session) Is not working for me.Sunshade
unfortunately we can't use getSession() here in middleware as of now @JulianWagner. You can use getToken() to get your session.Mayle
D
2

The above answer is correct and working, for those who are wondering. useSession and getSession only work on the client side but the application of middleware in nextjs is on the server side so using these two won't work or probably throw an error. consider using getToken. also secret you pass to getToken is your self-created secret usually named NEXTAUTH_SECRET in env

Dill answered 8/11, 2023 at 10:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.