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;
.
Send cookie
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

This article introduces a variety of methods and tools to monitor PostgreSQL databases under the Debian system, helping you to fully grasp database performance monitoring. 1. Use PostgreSQL to build-in monitoring view PostgreSQL itself provides multiple views for monitoring database activities: pg_stat_activity: displays database activities in real time, including connections, queries, transactions and other information. pg_stat_replication: Monitors replication status, especially suitable for stream replication clusters. pg_stat_database: Provides database statistics, such as database size, transaction commit/rollback times and other key indicators. 2. Use log analysis tool pgBadg

The article discusses the go fmt command in Go programming, which formats code to adhere to official style guidelines. It highlights the importance of go fmt for maintaining code consistency, readability, and reducing style debates. Best practices fo

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...
