gpt4 book ai didi

typescript - Next.js 中间件错误 :- [Error: The edge runtime does not support Node. js 'crypto' 模块]

转载 作者:行者123 更新时间:2023-12-03 07:55:42 24 4
gpt4 key购买 nike

我是 next.js 和 typescript 的新手,我对这个问题感到非常沮丧,因为已经过去 4 天了,我找不到解决方案。如果有人知道原因和问题,请帮助我解决方案。这会很有帮助的。谢谢

-- 这是我的 middleware.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",
};

最佳答案

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

关于typescript - Next.js 中间件错误 :- [Error: The edge runtime does not support Node. js 'crypto' 模块],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76080784/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com