Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

238
Visualizações
Cannot access the NextAuth session data in Next.js 12 middleware

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 
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda