Home > Backend Development > Golang > Why Doesn\'t My Browser Store Cookies Set by My Go Server in a React App?

Why Doesn\'t My Browser Store Cookies Set by My Go Server in a React App?

Patricia Arquette
Release: 2024-12-01 13:02:09
Original
730 people have browsed it

Why Doesn't My Browser Store Cookies Set by My Go Server in a React App?

Browser Declines to Store Cookie

Problem Statement

In a React application integrated with a Go server, the server attempts to set a cookie during the login response. However, the cookie is not being saved by the browser, despite it being returned in the network tab's response.

Exploration

The provided code snippets indicate that:

  • Cross-origin resource sharing (CORS) is configured to allow credentials.
  • The http.SetCookie() function is used to add the cookie to the response with the following settings:

    • Name: "accessToken"
    • Value: token
    • Max age: specified as an integer
    • Path: "/api"
    • HTTP Only: true
    • SameSite: LaxMode

Screenshots from the network tab show that the cookie is indeed being sent back in the response headers.

Solution

The key to solving this issue lies in the Fetch API's credentials flag. When making a fetch request that anticipates a cookie in the response, it is essential to set credentials: "include".

Edited Code:

fetch(`${url}/login`, {
    method: "POST",
    headers: {
        "Content-Type": "application/json",
    },
    credentials: "include", // This line has been added
    body: JSON.stringify({
        email: userDetails.email,
        password: userDetails.password,
    }),
}).then((response) => { ...
Copy after login

By setting credentials to "include", the browser understands that it should accept and store the cookie included in the response. This configuration ensures that the browser correctly saves the cookie and makes it available for subsequent requests.

The above is the detailed content of Why Doesn't My Browser Store Cookies Set by My Go Server in a React App?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template