Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express js Redirect cookies not sent

I have 2 separate apps, let's call them Login & Dashboard. Both apps have a UI written in react and an express server.

In my Login app, when I make a POST from my Login UI, it hits the Login Express server to authenticate. Once authenticated, I set a cookie and redirect to my Dashboard url:

res.cookie(cookie.key, cookie.access_token, {
      path: '/',
      domain: cookie.domain,
      httpOnly: true,
      maxAge: cookie.rememberExpiry
    })

res.redirect(dashboard_url)

However when I use req.cookies in my dashboard app I don't see any cookies.

When I make the POST from my Login UI I do indeed see a network call stating response header:

Set-Cookie: mycookie=cookievalue; Max-Age=28800; Domain=.local.myurl.com; Path=/; Expires=Thu, 03 Nov 2016 19:20:39 GMT; HttpOnly

Note that as of this moment the time is Nov 3 2016, 11:28 GMT so its not an expiry issue.

To test I have edited my hosts file such that login.local.myurl.com & dashboard.local.myurl.com point to localhost.

Is there any reason why the req.cookies is not available in the Dashboard express app??

like image 996
Terence Chow Avatar asked Nov 06 '25 16:11

Terence Chow


1 Answers

My problem was 2 fold.

First I needed to set credentials: 'same-origin' on fetch, which is to say that I had to allow cookies to persist on the request library I was using.

Second, because my server and my client are essentially separate, a redirect on the server did not have the intended effect on the client. Hence I could not just res.redirect from the server response. instead I replaced the res.redirect line with res.status(200).send() and in my client code, I simply did window.location.replace('http://dashboardurl.com').

Hope that helps anyone who has this issue in the future.

like image 141
Terence Chow Avatar answered Nov 09 '25 17:11

Terence Chow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!