Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Browser is not saving cookie

I am creating a React app with a Go server. I set the cookie on the login request's response with http.cookie, which sends it back as seen in the network tab. But the browser doesn't save it. Tried with Chrome and Firefox. What am I doing wrong?

// Cors handler
r.Use(cors.Handler(cors.Options{
    AllowOriginFunc:  AllowOriginFunc,
    AllowedMethods:   []string{"GET", "POST", "DELETE"},
    AllowedHeaders:   []string{"*"},
    AllowCredentials: true,
}))
func AllowOriginFunc(r *http.Request, origin string) bool {
    if origin == "http://localhost:3000" || origin == "http://127.0.0.1:3000" {
        return true
    }
    return false
}

// End of Login route sending back the token
    userDetails := types.User{Name: user.Name, Email: user.Email, Profile_Pic: user.Profile_Pic}
    cookie := &http.Cookie{Name: "accessToken", Value: token, MaxAge: int(maxAge), Path: "/api", HttpOnly: true, SameSite: http.SameSiteLaxMode}
    http.SetCookie(w, cookie)
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(userDetails)

Edit: Screenshots of the network tab. Response headers

Request headers

like image 535
Daniel Chettiar Avatar asked May 07 '26 18:05

Daniel Chettiar


1 Answers

Anybody else who comes across a similar problem, and is using the Fetch API, try setting 'credentials: "include"' in your fetch request that is EXPECTING A COOKIE IN THE RESPONSE. The browser then set the cookie it got in the response.

I had the wrong assumption that the 'credentials' flag must be set for requests that occur after the cookie is received. Finally working. Can't believe I spent 12 hours on setting a cookie smh.

fetch(`${url}/login`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                credentials: "include", // This here
                body: JSON.stringify({
                    email: userDetails.email,
                    password: userDetails.password,
                }),
            }).then((response) => { ...
like image 76
Daniel Chettiar Avatar answered May 09 '26 12:05

Daniel Chettiar