typescript - Error de Middleware de Next.js :- [Error: El runtime de borde no soporta el módulo 'crypto' de Node.js]
Soy nuevo en next.js y TypeScript y estoy realmente frustrado con este problema, ya que han pasado 4 días y no puedo encontrar una solución... por favor, si alguien conoce la causa y el problema, ayúdeme con la solución. Sería de gran ayuda. Gracias
-- Este es mi 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",
};
Respuesta #1
jsonwebtoken no es compatible con la ejecución en el entorno Edge ya que es diferente de Node.js. Podrías usar jose, que es compatible con el Runtime Edge de Vercel en lugar de jsonwebtoken.
Respuesta #2
Funcionó para mí | Enrutador de páginas
Primero :
npm install jose
Crea el archivo middleware.js en src/middleware.js
import { isAuthenticated } from './lib/jwtTokenControl'
// Limit the middleware to paths starting with `/api/`
// matcher: ['/about/:path*', '/dashboard/:path*'],
export const config = {
matcher: '/api/v1/:function*'
}
export async function middleware(request) {
const result = await isAuthenticated(request)
if (!result) {
return Response.json({ success: false, message: 'Invalid token. Paths starting with `/api/v1/`' }, { status: 401 })
}
}
Crea el archivo src/lib/jwtTokenControl.js
import * as jose from 'jose'
const jwtConfig = {
secret: new TextEncoder().encode(process.env.NEXT_PUBLIC_JWT_SECRET),
}
export const isAuthenticated = async req => {
let token = req.headers.get('authorization') || req.headers.get('Authorization')
if (token) {
try {
if (token.startsWith('Bearer')) {
token = token.replace('Bearer ', '')
}
const decoded = await jose.jwtVerify(token, jwtConfig.secret)
if (decoded.payload?._id) {
return true
} else {
return false
}
} catch (err) {
console.error('isAuthenticated error: ', err)
return false
}
} else {
return false
}
}
