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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With