Thanks @swarnava
I have solved this issue. Thanks for your help. I found a bug in my source code that was causing this error.
Now the other issue I am dealing with is about cookies. When testing locally, the server is sending the cookie to the client, but when tested in production, the same code can’t send the cookie to the client:
Here is the code I use to set the cookie when the user either login or sign up:
import jwt from "jsonwebtoken";
import { Response } from "express";
export const generateJWToken = (res: Response, userId: string) => {
try {
const cookie = jwt.sign({ userId }, process.env.JWT_SECRET!, {
expiresIn: "1d",
});
res.cookie("user", cookie, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
maxAge: 24 * 60 * 60 * 1000,
});
return cookie;
} catch (error) {
console.log(error);
return { success: false, message: "Erro ao gerar token JWT" };
}
};
And when I want to check if the user is authenticated, I call the function below as a middleware to the protected route:
import { Request, Response, NextFunction, RequestHandler } from "express";
import jwt from "jsonwebtoken";
export const authenticatedUser: RequestHandler = async (
req: Request,
res: Response,
next: NextFunction
) => {
const cookie = req.cookies.user
try {
if (!cookie) {
res.status(200).json({ success: false, user: null, message: "Token não encontrado" });
return;
}
const decoded = await jwt.verify(cookie, process.env.JWT_SECRET!);
req.userId = (
decoded as { userId: string; iat: number; exp: number }
).userId;
await next();
} catch (error) {
res.status(200).json({ success: false, user: null, message: "Token inválido" });
}
};
Unfortunately, whenever I want to check if the user is authenticated, the middleware above return cookie not found error.
Does Vercel has a special way of dealing with cookie for ExpressJS servers?
Regards
Evariste