skip to Main Content

I’m having trouble setting cookies with the domain set to localhost. Here’s what’s happening:

When I set the cookie with the domain as localhost, I get an error saying the domain attribute is invalid with respect to the current host URL.

Image

res.cookie('token', "test", {    
                sameSite: "none", 
                secure: true,
                httpOnly: "true",   
                domain: "localhost",
                path: "/",              
                maxAge: 2400000, 
            })

However, if I set the domain to 127.0.0.1, the cookie is successfully created and visible. The issue is that when I refresh the page, the cookie disappears.

Interestingly, if I manually change the domain of the cookie to localhost after it has been set, it persists as expected.

I would like to understand why this happens and how I can set cookies with the domain localhost so that they remain consistent across page reloads.

app.use(cors({
    origin: 'http://localhost:4321',
    credentials: true
}));

Thank you for your help!

Here are a few things I’ve tried:

  1. Setting the domain to localhost directly in the cookie options.
  2. Using 127.0.0.1 as the domain, which works initially but the cookie disappears on refresh.
  3. Manually editing the domain in the browser to localhost, which works fine.

Does anyone know how to resolve this issue or if there is a workaround to set cookies with the domain localhost?

3

Answers


  1. Chosen as BEST ANSWER

    I found the solution I needed to add localhost to my api server.

    app.listen(
        PORT, 'localhost',
        () => console.log(`it's alive on http://localhost:${PORT}`)
    )         
    

  2. This is a common problem with localhost cookies, since localhost is not a valid place to set cookies and localhost and 127.0.0.1 are treated as 2 different domains. So you can still see your cookies on 127.0.0.1.

    const isLocalhost = req.hostname === 'localhost' || req.hostname === '127.0.0.1';
    
    res.cookie('token', "test", {    
        sameSite: isLocalhost ? "lax" : "none", 
        secure: !isLocalhost,
        httpOnly: true,
        path: "/",              
        maxAge: 2400000, 
        ...(isLocalhost ? {} : {domain: req.hostname})
    })
    

    Edit: Add CORS

    app.use(cors({
      origin: 'http://localhost:3000',
      credentials: true
    }));
    

    This should bypass your cookie checks

    Login or Signup to reply.
  3. res.cookie('token', "test", {    
    sameSite: "strict", // Or "lax".
    secure: false,   // Set it to false for development
    httpOnly: true,  // Set to a boolean.
    path: "/",              
    maxAge: 2400000, 
    

    });

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search