Search code examples
reactjsgonext.jscookiesjwt

Why is the cookie being set on the frontend domain?


I am running a golang server at localhost:8080 and nextjs server at localhost:3000

When you make a POST request to localhost:8080/login, it authenticates and sets a cookie.

When I send a POST request to the /login route on the backend, I got a cookie on the localhost:3000 which is the frontend(as I can see on my browser). Why is the cookie being set on the frontend domain?

Browser Screenshot

I am using the following options on the backend

corsConfig := cors.Config{
    AllowOrigins:     []string{"http://localhost:3000"},
    AllowMethods:     []string{"GET", "POST", "PUT", "DELETE"},
    AllowHeaders:     []string{"Origin", "Content-Type"},
    AllowCredentials: true,
}


c.SetCookie("token", tokenString, int(expirationTime.Unix()), "/", "localhost", false, true)

fetch request on the frontend

  const res = await fetch("http://localhost:8080/login", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    credentials: "include",
    body: JSON.stringify(data),
  });

Isn't the token supposed to be set on localhost:8080. This is the same in this video posted freecodecamp channel React and Golang JWT Authentication

Data for the token

token:"eyJhbGciOiJIUzI1NiIsInR...."
Domain:"localhost"
HostOnly:true
HttpOnly:true
Expires / Max-Age:"Thu, 11 Nov 2077 00:17:16 GMT"
SameSite:"None"
Secure:false
.
.

Solution

  • "A browser today shares cookies on localhost, regardless of the port." link to discussion

    Even though localhost:8080 and localhost:3000 are on different ports, they are both on the localhost domain on which the cookie is set. Hence we see the cookie localhost:{port} regardless of the port number