Foy*_*med 5 javascript middleware next.js
我正在尝试使用新的 Next.js 12 中间件功能来实现路由保护。但我发现每次我尝试访问会话时我都会得到空值。因此没有得到预期的结果。这是为什么?
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
Run Code Online (Sandbox Code Playgroud)
还有另一种方法可以帮助您访问您的session.
这里我们使用getTokenfrom next-auth/jwt.
要注意:
secret为optionin (此处NextAuth function相关参考)。如果没有,它将无法工作。如果您使用或并不重要。两者都会起作用。sessionjwt optionexport default NextAuth({
secret: process.env.SECRET,
...otherOptions
})
Run Code Online (Sandbox Code Playgroud)
这是一个例子_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()
}
Run Code Online (Sandbox Code Playgroud)
如果您已经找到了如何使用的解决方案getSession。您可以上传您的答案并与我们分享。谢谢。
| 归档时间: |
|
| 查看次数: |
6678 次 |
| 最近记录: |