I've encountered an issue where sending cookies from my express server using res.cookie()
is not working with the front end. Even though I include {withCredentials:true}
in the get requests, the cookies are not being set in the browser's application tab.
Interestingly, when I try the requests with Postman, the middleware works perfectly and the cookies are shown.
I have tried different browsers and devices, but the issue persists.
Here is my CORS configuration:
app.use(
cors({
credentials: true,
origin: [
"http://localhost:3000",
],
methods: ["GET", "POST"],
})
);
Cookie parser configuration:
app.use(cookieParser())
This is the GET request to check if the user is already logged in:
await axios
.get("http://192.168.0.141:3001/login", { withCredentials: true })
.then(async (response) => {
if (response) {
loggedIn = true
}
})
.catch(async err => {
loggedIn = false
})
The JWT middleware:
const validateToken = (req, res, next) => {
const accessToken = req.cookies["access-token"]
if (!accessToken) { return res.status(400).json({ error: "user not authenticated" }) }
try {
const validToken = jwt.verify(accessToken, "test");
if (validToken) {
req.authenticated = true
return next();
}
} catch (error) {
return res.status(400).json({ error: error });
}
}
If you require further clarification, please let me know. Thank you for your assistance.