Hello guys,
Can some help? I have deployed a MERN stack app on Vercel, but separately (client, and server).
But I’m having issues with cookies. When testing locally, the server sends the cookie to the client and the whole app is working as expected. 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" };
}
};
Whenever 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 returns "cookie not found error"
.
Does Vercel has a special way of dealing with cookie for ExpressJS servers?
Regards
Evariste