Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js Middleware Error :- [Error: The edge runtime does not support Node.js 'crypto' module]

I am new to next.js and typescript and i am really fustrated with this problem as its been 4 days and i can't find a solution.. please if anyone knows the cause and problem help me with the solution. It will be so helpfull . Thanks

-- This is my 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",
};
like image 520
Aayush singh Avatar asked Jun 09 '26 22:06

Aayush singh


1 Answers

jsonwebtoken doesn't support running on Edge environment as it's different from Node.js. You could use jose which supports Vercel's Edge Runtime instead of jsonwebtoken.

like image 121
Burak Ozarslan Avatar answered Jun 11 '26 13:06

Burak Ozarslan