Search code examples
reactjsexpresscookieshostingexpress-session

Hosting a React app and Express app on the same domain


I've developed a React app that calls an Express backend. They are two completely different apps in two different directories and hosted on different domains. I'm using passport to authenticate users and express-session to make sure their session persists. Everything works as expected in development but when the apps are hosted, the session does not persist. I realised that it's because the apps are on different domains and cookies from my Express server are being blocked by the browser. What I need to do to fix this is put my apps on the same domain and I'm trying to figure out the best way to do this. I've come up with two solutions so far but I'd like some input as to which is the best and whether there's a better one than these two.

1) Move the applications in the same directory. I'm unsure about how to go about this in terms of routing and defining the entry point for my app (how do I start both apps in the same directory at once?). Any resources on this would be appreciated

2) Both apps are currently hosted on Heroku. I was thinking about buying a domain and using Route 53 Aliases to get them on the same domain but I am also unsure about the logic behind this and whether this will even be effective.


Solution

  • Thanks Enioluwa Segun for your answer but I actually decided to try the other approach where I buy a domain and unify the two apps on this domain because I remembered that I did something similar in another project. It ended up working, my session persists!

    More specifically, what I did was buy a domain on AWS Route 53 and then I followed this guide to set it up to alias my frontend Heroku app. I then used this guide to redirect api.mydomain.com to my backend Heroku app.