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

Aay*_*ngh 2 typescript next.js

我是 next.js 和 typescript 的新手,我对这个问题感到非常沮丧,因为已经 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",
};
Run Code Online (Sandbox Code Playgroud)

小智 8

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