2

I have a node js service application and a react frontend. I am using Discord oauth and express sessions for authentication to my application frontend.

Everything works flawlessly when running both on locally but I found that when deploying my applications to heroku, my service is setting the cookie to the service's home domain meaning my frontend cannot use it.

(for example the cookie domain is being set to 'fakeservice.herokuapp.com' instead of 'fakefrontend.herokuapp.com)

Obviously this worked locally as both applications were running on local host meaning the cookie host was identical anyway.

Below is by piece of code that is setting the cookie, however if I try and edit the domain or path of the cookie, it wont save to the browser.

The only thing I can change and still have it save is the MaxAge.

All solutions I have read seem to set this domain element in the cookie object but again this stops my cookie from being saved to the browser.

Any help or guidance anyone could give would be greatly apperciated.

app.use(session({
    secret: SECRET_GOES_HERE,
    store: new Store({
        url: MONGODB_URI,
        mongoOptions: {useNewUrlParser: true, useUnifiedTopology: true}
    }),
    cookie: {
        maxAge: 7200000,
        domain: '.herokuapp.com' << adding this breaks cookie save
    },
    resave: false,
    saveUninitialized: false,
}))
app.use( cors({
    credentials: true,
    origin:['.herokuapp.com']
}));
RossyBergg
  • 121
  • 1
  • 8

1 Answers1

3

So after some further digging I found a solution.

It seems that express does not like setting cookies for other domains than it’s own. Doing so would mean that it was setting a 3rd party cookie.

I read some users that were setting up backends and front ends on the same server to fix the issue, but this didn't sit well with me.

Also as herokuapp.com is registered as public it doesn't seem like we can set cookies for that domain. (but don't quote me too much on that, I read that on a few git issues)

I decided to create custom domains for each of the applications (i.e app.mycustomdomain.com & service.mycustomdomain.com' which pointed to heroku's DNS servers.

This meant both my applications now shared the same domain and the cookie setting worked instantly (also by adding the new domain to CORS).

There's guides on setting up custom domains on your Heroku Dashboard under the settings tab.

I hope this helps people a little faster than my days of searching.

RossyBergg
  • 121
  • 1
  • 8
  • 1
    I cannot thank you enough for this post. It's amazing how many posts I've read on this issue and yours is the first real answer. I implemented this and it worked like a charm. You should add a tip link in your Stackoverflow profile :) – AndrewLeonardi Sep 02 '22 at 21:00