无法访问 Next.js 12 中间件中的 NextAuth 会话数据

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)

lal*_*ala 7

还有另一种方法可以帮助您访问您的session.

这里我们使用getTokenfrom next-auth/jwt. 要注意

  • 必须使用声明 secretoptionin (此处NextAuth function相关参考)。如果没有,它将无法工作。如果您使用或并不重要。两者都会起作用。sessionjwt option
export default NextAuth({
  secret: process.env.SECRET,
  ...otherOptions
})
Run Code Online (Sandbox Code Playgroud)
  • 目前不知道不使用token是否行得通。或者您仅使用数据库选项。或适配器。我不确定,因为目前我还无法使适配器工作。就是这样。

这是一个例子_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。您可以上传您的答案并与我们分享。谢谢。

  • 不幸的是,我们现在不能在“中间件”中使用“getSession()”@JulianWagner。您可以使用“getToken()”来获取您的会话。 (2认同)