search
HomeBackend DevelopmentGolangBrowser does not save cookies sent by Golang backend

Browser does not save cookies sent by Golang backend

php editor Strawberry is here to introduce to you a problem about browsers saving cookies. Sometimes when we use the Golang backend to send cookies, we find that the browser does not save them. This may be due to a number of reasons, such as browser privacy settings or some issues in the code. In this article, we will explore this issue in detail and provide some solutions to ensure that browsers correctly save cookies sent by the Golang backend. let's start!

Question content

I know this question has been asked many times, but I tried most of the answers and still can't get it to work.

I have a golang api with net/http package and js frontend. I have a function

func setcookie(w *http.responsewriter, email string) string {
    val := uuid.newstring()
    http.setcookie(*w, &http.cookie{
        name:     "gocookie",
        value:    val,
        path:     "/",
    })
    return val
}

This function is called when the user logs in and I want it to be sent to all other endpoints. This is consistent with postman's expectations. However, when it comes to the browser, I can't seem to get it to remember the cookie or even send it to other endpoints.

js example using endpoint

async function getDataWithQuery(query, schema){
    
    let raw = `{"query":"${query}", "schema":"${schema}"}`;
    let requestOptions = {
        method: 'POST',
        body: raw,
        redirect: 'follow',
    };
    try{
        let dataJson = await fetch("http://localhost:8080/query/", requestOptions)
        data = await dataJson.json();
    }catch(error){
        console.log(error);
    }

    return data;
}

I have tried setting the samesite attribute in golang, or using credential: "include" and other answers in js, but without success.

Solution

Thanks to the discussion in the comments, I found some tips about this problem.

Save cookies (api and frontend are on the same host)

I use document.cookie to save cookies. I set the options manually because calling res.cookie on the response from api fetch only returns the value. An example is document.cookie = `gocookie=${res.cookie};path=/;domain=localhost;.

This question has been answered in a previous question and again in the comments. The problem was that I used credential:'include' instead of the correct credentials:'include' (plural).

cors and cookies

If the api and frontend are not on the same host, you will have to modify both the api and the frontend.

front end

The cookie must have the domain of the api, since it is the api that requires it, not the frontend. So for security reasons you cannot set cookies for a domain (api) of another domain (frontend). The solution is to redirect the user to an api endpoint that returns the set-cookie header in the response headers. This solution instructs the browser to register the cookie with an additional domain (the api's domain, since the api sent it).

Also, you still need to include credentials:'include' on the frontend.

api

You need to set some headers. What I set is

    w.header().set("access-control-allow-origin", frontendorigin)
    w.header().set("access-control-allow-credentials", "true")
    w.header().set("access-control-allow-headers", "content-type, withcredentials")
    w.header().set("access-control-allow-methods", method) // use the endpoint's method: post, get, options

You need to expose the endpoint where the frontend will redirect the user and set a cookie in the response. You can omit it and instead of manually setting the api's domain, the browser will automatically populate it with the domain.

To handle cors and let js successfully send the cookie, you must set the samesite=none and secure attributes in the cookie and provide the api over https (for simplicity, I use ngrok).

like this

func SetCookie(w *http.ResponseWriter, email string) string {
    val := uuid.NewString()
    http.SetCookie(*w, &http.Cookie{
        Name:     "goCookie",
        Value:    val,
        SameSite: http.SameSiteNoneMode,
        Secure:   true,
        Path:     "/",
    })
   // rest of the code
}

I recommend you also read the difference between using localstorage and document.cookie, this was one of the issues I had.

Hope this helps.

The above is the detailed content of Browser does not save cookies sent by Golang backend. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete
Choosing Between Golang and Python: The Right Fit for Your ProjectChoosing Between Golang and Python: The Right Fit for Your ProjectApr 19, 2025 am 12:21 AM

Golangisidealforperformance-criticalapplicationsandconcurrentprogramming,whilePythonexcelsindatascience,rapidprototyping,andversatility.1)Forhigh-performanceneeds,chooseGolangduetoitsefficiencyandconcurrencyfeatures.2)Fordata-drivenprojects,Pythonisp

Golang: Concurrency and Performance in ActionGolang: Concurrency and Performance in ActionApr 19, 2025 am 12:20 AM

Golang achieves efficient concurrency through goroutine and channel: 1.goroutine is a lightweight thread, started with the go keyword; 2.channel is used for secure communication between goroutines to avoid race conditions; 3. The usage example shows basic and advanced usage; 4. Common errors include deadlocks and data competition, which can be detected by gorun-race; 5. Performance optimization suggests reducing the use of channel, reasonably setting the number of goroutines, and using sync.Pool to manage memory.

Golang vs. Python: Which Language Should You Learn?Golang vs. Python: Which Language Should You Learn?Apr 19, 2025 am 12:20 AM

Golang is more suitable for system programming and high concurrency applications, while Python is more suitable for data science and rapid development. 1) Golang is developed by Google, statically typing, emphasizing simplicity and efficiency, and is suitable for high concurrency scenarios. 2) Python is created by Guidovan Rossum, dynamically typed, concise syntax, wide application, suitable for beginners and data processing.

Golang vs. Python: Performance and ScalabilityGolang vs. Python: Performance and ScalabilityApr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang vs. Other Languages: A ComparisonGolang vs. Other Languages: A ComparisonApr 19, 2025 am 12:11 AM

Go language has unique advantages in concurrent programming, performance, learning curve, etc.: 1. Concurrent programming is realized through goroutine and channel, which is lightweight and efficient. 2. The compilation speed is fast and the operation performance is close to that of C language. 3. The grammar is concise, the learning curve is smooth, and the ecosystem is rich.

Golang and Python: Understanding the DifferencesGolang and Python: Understanding the DifferencesApr 18, 2025 am 12:21 AM

The main differences between Golang and Python are concurrency models, type systems, performance and execution speed. 1. Golang uses the CSP model, which is suitable for high concurrent tasks; Python relies on multi-threading and GIL, which is suitable for I/O-intensive tasks. 2. Golang is a static type, and Python is a dynamic type. 3. Golang compiled language execution speed is fast, and Python interpreted language development is fast.

Golang vs. C  : Assessing the Speed DifferenceGolang vs. C : Assessing the Speed DifferenceApr 18, 2025 am 12:20 AM

Golang is usually slower than C, but Golang has more advantages in concurrent programming and development efficiency: 1) Golang's garbage collection and concurrency model makes it perform well in high concurrency scenarios; 2) C obtains higher performance through manual memory management and hardware optimization, but has higher development complexity.

Golang: A Key Language for Cloud Computing and DevOpsGolang: A Key Language for Cloud Computing and DevOpsApr 18, 2025 am 12:18 AM

Golang is widely used in cloud computing and DevOps, and its advantages lie in simplicity, efficiency and concurrent programming capabilities. 1) In cloud computing, Golang efficiently handles concurrent requests through goroutine and channel mechanisms. 2) In DevOps, Golang's fast compilation and cross-platform features make it the first choice for automation tools.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.