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.
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:
- Setting the domain to localhost directly in the cookie options.
- Using 127.0.0.1 as the domain, which works initially but the cookie disappears on refresh.
- 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
I found the solution I needed to add localhost to my api server.
This is a common problem with localhost cookies, since
localhost
is not a valid place to set cookies andlocalhost
and127.0.0.1
are treated as 2 different domains. So you can still see your cookies on127.0.0.1
.Edit: Add CORS
This should bypass your cookie checks
});