Home > Enterprise >  Browser is not saving cookie
Browser is not saving cookie

Time:06-15

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

CodePudding user response:

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) => { ...

CodePudding user response:

please try to put you cookie in header filed:"Set-Cookie".

e.g:

w.Header().Set("Set-Cookie","cookieName=cookieValue")

Make sure the response header has this field, and check it in you browser devtools.

  • Related