webpack-dev-server代理模式下Cookie无法在浏览器设置的问题求助
Hey there! Let's figure out why that login cookie isn't sticking in your browser, even though you can see it in the network tab. Here's what you need to check and fix:
1. Add withCredentials to Your Proxy Configuration
The main issue here is likely that your webpack-dev-server proxy isn't allowing credentials (like cookies) to be passed between your frontend and backend. By default, withCredentials is set to false, which blocks browsers from saving or sending cookies across the proxy.
Update your config to enable this for both proxy routes:
const config = { devServer: { index: "/", proxy: { "/rest_end_point/page": { target: "https://middleware_server", secure: false, withCredentials: true // Add this line }, "/": { target: "https://middleware_server/app/login", secure: false, withCredentials: true // Add this line }, } }
2. Verify Backend Response Headers
Even with the proxy setup, your backend needs to send the right headers to make browsers accept the cookie. Check these in the network tab's response headers:
Access-Control-Allow-Credentials: true: This tells the browser it's okay to store and send credentials for this request.Access-Control-Allow-Origin: This can't be*(wildcard) when using credentials. It must be set to your exact frontend dev server URL, likehttp://localhost:3000orhttp://localhost:8080(whichever port you're using for React).Set-CookieAttributes: Make sure the cookie's properties align with browser security rules:- If your frontend is using HTTPS (or your proxy targets HTTPS), add
Secureto the cookie. - For cross-domain scenarios (even via proxy), set
SameSite=Noneto ensure the cookie is sent with cross-origin requests. - The
Domainattribute should match the domain your frontend is running on (e.g.,localhostfor dev) unless your backend is on a subdomain of your frontend domain.
- If your frontend is using HTTPS (or your proxy targets HTTPS), add
3. No Extra Work Needed in the Shared Login Page
You don't need to add any code to the shared login page itself. Browsers automatically handle setting cookies from Set-Cookie response headers as long as the above proxy and backend configurations are correct. The login page just needs to be served via the proxy so the browser treats the request as same-origin (or properly cross-origin with the right headers).
Once you make these changes, restart your webpack-dev-server, and the cookie should be saved in your browser for subsequent requests.
内容的提问来源于stack exchange,提问作者Ishan Hettiarachchi

