Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

239
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda