【问题标题】:Cannot access the NextAuth session data in Next.js 12 middleware无法访问 Next.js 12 中间件中的 NextAuth 会话数据
【发布时间】:2022-01-06 11:51:21
【问题描述】:

我正在尝试使用新的 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 

【问题讨论】:

标签: javascript next.js middleware


【解决方案1】:

还有其他方法可以访问您的session

这里我们使用来自next-auth/jwtgetToken注意

  • 必须使用声明secret作为optionNextAuthfunction(相关参考here)。如果没有,它将无法正常工作。不管你使用session 还是jwt option。两者都可以。
export default NextAuth({
  secret: process.env.SECRET,
  ...otherOptions
})
  • 目前我不知道如果你不使用令牌它是否会起作用。或者您只使用数据库选项。或适配器。我不确定,因为目前我还不能让适配器工作。就是这样。

这是一个例子_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()
}

如果您已经找到了如何使用getSession 的解决方案。您可以上传您的答案并与我们分享。谢谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-07
    • 1970-01-01
    • 2019-03-27
    • 1970-01-01
    • 2022-01-25
    • 2012-02-25
    • 1970-01-01
    • 2016-04-21
    相关资源
    最近更新 更多