5

We have a react app running on multiple domain names, but I am unsure of how to get the current domain name in react.

E.g. The app runs the same code on www.example-one.com and www.example-two.com but using window.location or document.location.href etc just returns localhost as the app is served via a reverse proxy in Apache.

How do I get it to return www.example-one.com or www.example-two.com?


EDIT: After some more testing the issue was because I was using location.href before the component had mounted. Moving the code to componentDidMount allowed me to access the domain name. Thanks for your help

  • `location.href` will return the domain, even if running via a reverse proxy. It would be `localhost` on your server, but not the browser. Unless of course you access the browser via `localhost` – Keith Apr 24 '19 at 13:21
  • Are you sure that wont work? Have you looked at this: https://stackoverflow.com/questions/51988873/how-to-read-the-current-url-in-the-react-application – Martin M Apr 24 '19 at 13:21
  • You need to separate your project into two different releases and place them in different folders with different config file. – Ilya Manyahin Apr 24 '19 at 13:29
  • Thanks for the responses. I just tried again and using `location.href` results in the error `location is not defined` or using `window.location.href` results in `window is not defined` and the app fails to start – calum.rejuvenate Apr 24 '19 at 13:40

1 Answers1

7

You can achieve that by

const domain = window.location.host;
Aziza Kasenova
  • 1,501
  • 2
  • 10
  • 22
Samarth
  • 71
  • 1
  • 4