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

ogq8wdun  于 2022-12-03  发布在  React
关注(0)|答案(1)|浏览(511)
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 Runtime中不允许动态代码求值(例如'eval'、'new Function'、'WebAssembly. compile')了解更多:https://nextjs.org/docs/messages/edge-dynamic-code-evaluation"
它在本地运行良好,但似乎我做错了什么,因为它似乎在部署项目时导致错误。
我想通过使用next-auth会话将未授权的人重定向到“/enter”页面。所以我使用了getSession。在“edge”中获得会话的方法是错误的吗?那么我应该怎么做?

e4eetjau

e4eetjau1#

如果我理解得很清楚,您是在_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")
        }
    }
}

相关问题