Home >Backend Development >Golang >Why Aren\'t My HTTPOnly Cookies Being Set on Localhost?
HTTPOnly Cookie Not Being Set in Browser Localhost
Problem:
A REST API's login endpoint sends an HTTPOnly cookie containing payload (JWT), but the cookie is not being set in browsers. The approach had been working for years, but recently stopped. The issue is isolated to the localhost environment. Postman testing confirms the cookie is set as expected.
Approaches Used:
Investigation:
The Go and Node APIs both correctly send the Set-Cookie header with the HTTPOnly flag set. This indicates that the problem may lie in the browser or the fetch() method.
Solution:
The issue was resolved by adding the credentials: "include" property to the fetch() method in the front-end JavaScript. This property instructs the browser to send and receive cookies.
Reason:
HTTPOnly cookies are designed to prevent client-side JavaScript from accessing the cookie's contents. Browsers support this by not sending the cookie in XHR or fetch() requests by default. By adding the credentials: "include" property, the browser is explicitly told to send the cookie along with the request, allowing it to be received by the server and set appropriately.
Additional Notes:
The above is the detailed content of Why Aren\'t My HTTPOnly Cookies Being Set on Localhost?. For more information, please follow other related articles on the PHP Chinese website!