10

I'd like to setup react router for use with subdomains. I'm unsure where the logic for subdomain proxying should lie.

I want:

roxy.coolestblog.com/profile to route to coolestblog.com/roxy/profile mohammed.coolestblog.com/profile to route to coolestblog.com/mohammed/profile benben.coolestblog.com/profile to route to coolestblog.com/benben/profile

another use case:

en.coolestblog.com/some-article to route to coolestblog.com/en/some-article fr.coolestblog.com/un-article to route to coolestblog.com/fr/un-article es.coolestblog.com/una-article to route to coolestblog.com/es/una-article

I already have it working without the subdomain.

How can I achieve this so it works both on client and server?

4
  • 1
    Did you find any solution to this? Looks like I have the same need... Apr 1, 2016 at 14:32
  • If you found a solution, please share
    – Learner
    Mar 5, 2019 at 7:28
  • Answered similar question here in case its helpful Jun 18, 2020 at 21:25
  • Did you find a solution for this @collinglass?
    – poca
    Mar 29, 2021 at 2:16

1 Answer 1

8

While the browser history API limits our ability, we can interact directly with window.location in order to accomplish this.

Just before setting up your router, you can modify the URL by doing something like this:

let host = window.location.host;
let protocol = window.location.protocol;
let parts = host.split(".");
let subdomain = "";
// If we get more than 3 parts, then we have a subdomain
// INFO: This could be 4, if you have a co.uk TLD or something like that.
if (parts.length >= 3) {
  subdomain = parts[0];
  // Remove the subdomain from the parts list
  parts.splice(0, 1);
  // Set the location to the new url
  window.location = protocol + "//" + parts.join(".") + "/" + subdomain;
}

Of course, this has its caveats. For instance, if you do not know your host name explicitly, you cannot correctly determine if there is a subdomain or not. It does not make any assumptions about what the following URL should be, but it would be trivial to solve for that.

1
  • Does it have an advantage over getting it from cookies?
    – SalahAdDin
    Aug 31, 2020 at 9:54

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.