I'm using Go and mux for the backend and simple html for the frontend. The code for setting a cookie in the response (not full):
import "github.com/gorilla/sessions" // this is where sessions come from
var store = sessions.NewCookieStore([]byte("secret"))
store.Options = &sessions.Options{
MaxAge: 3600 * 24,
HttpOnly: true,
Path: "/",
Secure: true,
}
session, _ := store.Get(request, "uid")
session.Values["uid"] = token
err = session.Save(request, writer)
if err != nil {
log.Fatalln(err)
return
}
and this is how I fetch:
fetch("http://localhost:8000/user/register", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
credentials: 'include',
body: JSON.stringify(user),
})
Also I have cors enabled on the backend:
c := cors.New(cors.Options{
AllowedOrigins: []string{"http://127.0.0.1:3000"},
AllowCredentials: true,
})
The content of the set-cookie header:
Set-Cookie: uid=jwt_token; Path=/; Expires=Tue, 20 Jul 2021 08:42:37 GMT; Max-Age=86400; HttpOnly; Secure
The cookie is not being set, but in the network tab the 'set-cookie' header is present. If you need more details about my code, ask in the comments and I will post a link to a pastebin.
Edit: until I find a better solution, I'm setting the cookie from the frontend, now the backend is sending a json with the data. A bit hacky considering my "initial design" but it works for now.
I think this has to do with the SameSite
cookie attribute. Check if your response's header Set-Cookie
field has an yellow triangle in the end, indicating that something went wrong (I'm using chrome dev tools). If it does, you should use the same domain
to POST
to the server. For example;
http://127.0.0.1:3000
, and your server is listening to the port 8000
then the request to the server should like like;fetch("http://127.0.0.1:8000/user/register", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
credentials: 'include',
body: JSON.stringify(user),
})
This is happenning because localhost
and 127.0.0.1
are treated as different hosts.
For more information about the SameSite
attribute you could check the MDN docs.