如何在Next.js中间件中获取会话?(部署时出错)


import type { NextFetchEvent, NextRequest } from "next/server";
import { getSession } from "next-auth/react";
import { NextResponse } from "next/server";
export async function middleware(req: NextRequest, ev: NextFetchEvent) {
const requestForNextAuth = {
headers: {
cookie: req.headers.get("cookie"),
},
};
//@ts-ignore
const session = await getSession({ req: requestForNextAuth });
if (
req.nextUrl.pathname.startsWith("/fictions/create") &&
(!req.cookies.get("~~session") || !session)
) {
return NextResponse.rewrite(new URL("/enter", req.url));
}
if (
req.nextUrl.pathname.includes("/edit") &&
(!req.cookies.get("~~session") || !session)
) {
return NextResponse.rewrite(new URL("/enter", req.url));
}
if (req.nextUrl.pathname.startsWith("/profile") && !session) {
if (!session) {
return NextResponse.rewrite(new URL("/enter", req.url));
}
}
}

错误消息:"Edge运行时中不允许动态代码求值(例如"eval"、"new Function"、"WebAssembly.compile"(了解更多信息:https://nextjs.org/docs/messages/edge-dynamic-code-evaluation">

它在本地运行得很好,但似乎我做错了什么,因为它似乎会在部署项目时导致错误。

我希望未经授权的人通过使用下一个身份验证会话重定向到'/enter'页面。所以我使用了getSession。让会话处于"边缘"的方式是错误的吗?那我该做什么?

如果我理解得很好,您正在尝试在_middleware.js中检查当前用户是否登录?您不能在此处使用getSession()

这是我的解决方法,它在本地工作(还没有在生产中尝试(:

export async function middleware(req) {
const pathname = req.nextUrl.pathname
const session = await getToken({ req: req, secret: process.env.NEXTAUTH_SECRET }); // I am getting the session here
// Protect protected pages
if (arrayOfProtectedPaths.includes(pathname)) {
if (session === null) {
return NextResponse.redirect("http://localhost:3008/spots/allSpots")
}
}
// Prevent logged in user to access to register and sign in 
if (shouldNotBeUser.includes(pathname)) {
if (session !== null) {
return NextResponse.redirect("http://localhost:3008/spots/allSpots")
}
}
}

相关内容

  • 没有找到相关文章

最新更新