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",
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With