I had hosted the server on the localhost:3000 and frontend on the localhost:5173 when i send the request to the server i get the response in network tab. using node.js in backend and react in frontend
HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: http://localhost:5173
Vary: Origin
Access-Control-Allow-Credentials: true
Set-Cookie: student=%22eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xsTm8iOjczMDEsIm1vYmlsZSI6ODg3MjcyNzU5NCwiaWF0IjoxNzUxNzIyMjAyLCJleHAiOjE3NTE3NjU0MDJ9.lynxPB-ClH8Qsn7MPBiRpWeslXoyIyPrC4n7bEYBEik%22; Path=/; HttpOnly; Secure; SameSite=None
Content-Type: application/json; charset=utf-8
Content-Length: 154
ETag: W/"9a-IVg/WdzNccNXZy6a7aBAOds5Q08"
Date: 2025年7月05日 13:30:02 GMT
Connection: keep-alive
Keep-Alive: timeout=5
But the cookie is not set (i am not able to use the cookie for authentication and cookie not visible in application/ cookies)
I don't what is a problem and had spent more that 6 hours solving this problem but still not resolved.
below is the cors and the cookie config in backend
CORS config:
cookie config:
I am using the axios in the frontend with instance having
baseURL: 'http://localhost:3000/api',
headers: {
'Content-Type': 'application/json',
},
withCredentials: true,
i had visited various articles showing crossOriginResourcePolicy: "cross-origin" to be set in the cookie but it didn't work for me and also used fetch api instead but still same problem
-
share code directly and not as imagesSpicyCatGames– SpicyCatGames2025年07月06日 09:47:31 +00:00Commented Jul 6, 2025 at 9:47
-
If the cookie you set from the backend is HttpOnly, client side javascript can't access itProDeSquare– ProDeSquare2025年07月08日 07:49:41 +00:00Commented Jul 8, 2025 at 7:49
1 Answer 1
Finally, the problem is resolved the actual problem was with the vite.config.js.
the problem was actually vite was not forwarding the set-cookie header to the browser by which set-cookie header was visible in network tab in chrome dev tools and cookie was not set.
Below is configuration that resolved the issue
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
server:{
proxy:{
'/api':{
target:"http://localhost:3000",
changeOrigin: true,
secure:false,
configure: (proxy) => {
proxy.on('proxyReq', (proxyReq, req) => {
// Forward cookies from the original request
if (req.headers.cookie) {
proxyReq.setHeader('cookie', req.headers.cookie);
}
});
proxy.on('proxyRes', (proxyRes, req, res) => {
// Forward Set-Cookie headers from the backend
if (proxyRes.headers['set-cookie']) {
res.setHeader('set-cookie', proxyRes.headers['set-cookie']);
}
});
}
}
}
}
})