Reputation: 61
I have an express server that has written a cookie, but I can not access it from the client side. I can see it in the Chrome dev tools, it is NOT marked as being httpOnly or Secure, yet when I try to access it via my React app or even just by typing document.cookie in the browser console, I get nothing.
Right now the express server is running on Heroku, and my client side is localhost.
I'm stumped.
Here is my server side code that is setting the cookie:
return res
.status(200)
.cookie('id_token', token, {
httpOnly: false,
path: '/',
secure: false,
maxAge: 400000
})
.json({
token: token
});
Upvotes: 1
Views: 2560
Reputation: 38922
Express server is running in heroku and Client server is running in localhost.
The cookie set in the Express server is scoped to the current host when Domain
for the cookie isn't set. [1]
Say your application is served at express.herokuapp.com
,
scripts can only read it when they're running in the same host. i.e. express.herokuapp.com
However, with cookie scopes cookie set on a domain can be read by scripts running in a subdomain.
In development, you can set Domain
attribute for the cookie to be .herokuapp.com
For production, I strongly suggest to explicitly scope the cookie to the client domain. While you can apply the same process as development if client and server are running in different subdomains. You should only do this if other client apps running in other subdomains share cookies.
However if both client and server are going to be running in the same domain, I suggest to keep the default cookies scope.
If client and server are running in different domains, I strongly suggest to explicitly scope the cookie to the client domain.
Then add the following entry in your /etc/hosts
to alias localhost
to a subdomain of herokuapp.com
127.0.0.1 local.herokuapp.com
Visit the address alias and the client side script will read the cookie.
Upvotes: 2