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
There's another ways on how you can get access to your session
.
Here we're using getToken
from next-auth/jwt
. to note :
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
})
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.
This solution helped me to fix my issue. Thanks a lot @julianWagner
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.