Next.js中间件错误:- [错误:边缘运行时不支持Node,js 'crypto' module]

yyhrrdl8  于 2023-04-30  发布在  其他
关注(0)|答案(1)|浏览(296)

我是新来的。js和typescript和我真的fustrated与这个问题,因为它的4天,我不能找到一个解决方案。如果有人知道原因和问题,请帮助我解决。这将是如此有益的。谢谢
这是我的中间件。ts

import jwt from "jsonwebtoken";
import { NextResponse, NextRequest } from "next/server";
import clientPromise from "./database/db";

interface RequestWithUserId extends NextRequest {
  userId: string;
}

export async function middleware(req: RequestWithUserId) {
  try {
    const mongoClient = await clientPromise;
    const token = req.cookies.get("jwt")?.value;

    if (!token) {
      return NextResponse.redirect("http://localhost:3000/login");
    }

    const decodedToken: any = jwt.verify(token, process.env.SECRET_KEY);

    const userId = decodedToken._id;

    const checkUserExists = await mongoClient
      .db()
      .collection("user")
      .findOne({ _id: userId });

    if (!checkUserExists) {
      return NextResponse.redirect("http://localhost:3000/login");
    }

    req.userId = userId;
    return NextResponse.next();
  } catch (err) {
    console.log("miidleware error", err);
    NextResponse.redirect("http://localhost:3000/login");
  }
}

export const config = {
  matcher: "/api/addToCart",
};
vmdwslir

vmdwslir1#

jsonwebtoken与Node不同,不支持在Edge环境下运行。js。您可以使用jose,它支持Vercel的Edge Runtime,而不是jsonwebtoken

相关问题