Home >Backend Development >Golang >Why Aren\'t My HTTPOnly Cookies Being Set on Localhost?

Why Aren\'t My HTTPOnly Cookies Being Set on Localhost?

Susan Sarandon
Susan SarandonOriginal
2024-11-25 05:02:11965browse

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:

  • Implementing the core essentials of the login endpoint in Go fiber and Node Express.
  • Stripping down the front-end to a basic login form.

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:

  • If using Axios for HTTP requests, it automatically includes the credentials in its configuration.
  • For Node Express, you may also need to set withCredentials: true in the request configuration to allow the browser to set the cookie.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn