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