I have a folder on my FTP with a React / Nextjs app in /myapp. My url my.app points to that folder. Is it possible to to add different subdomains (e.g. user1.my.app and user2.my.app) that point to the same folder /myapp. The app detects the subdomain and can set different states based on the subdomains?
React has nothing to do with domains at all. I guess, your question is relevant to the hosting configuration. So, it depends on a particular web server you use.
URL
URL consists of different parts: <scheme>://<user-info>@<subdomain>.<domain>:<port>/<path>?<query-string>#<hash>
.
Diagram made by OmenBreeze - Own work, CC BY-SA 4.0,
https://commons.wikimedia.org/w/index.php?curid=82827943
React Router
Domain has nothing to do with a webpage itself and a router on a webpage. SPA router works with <path>
, <query-string>
, and <hash>
(also known as <fragment>
) parts of the URL.
location
Locations represent where the app is now, where you want it to go, or even where it was. It looks like this:
{ "key": "ac3df4", // not with HashHistory! "pathname": "/somewhere", "search": "?some=search-string", "hash": "#howdy", "state": undefined }
SPA router works in the browser page when it's already loaded. But you are saying that different domains should point to the same folder. It's a web server job.
Apache (as a web server example)
In Apache web server you can configure two different virtual hosts to point to the same directory:
<VirtualHost *:80> DocumentRoot "/myapp" ServerName user1.my.app </VirtualHost> <VirtualHost *:80> DocumentRoot "/myapp" ServerName user2.my.app </VirtualHost>
❗ In comments you stated:
My question aims at how react can detect the domain (subdomain) and do something based on that value.
It's not exactly a React question anyway. It can be addressed with pure JavaScript.
✅ Get current domain in JavaScript and use it in React
If you want to know what is the domain in the current browser address in JavaScript, you need to use document.location
.
document.location.hostname
contains the full domain name from the address URL.
Location
The Location interface represents the location (URL) of the object it is linked to. Changes done on it are reflected on the object it relates to. Both the
Document
andWindow
interface have such a linkedLocation
, accessible viaDocument.location
andWindow.location
respectively.
Location.hostname
Is a USVString containing the domain of the URL.
In React you can do it in your root App
component in its constructor.
export default class App extends React.Component {
constructor(props) {
super(props);
this.hostname = document.location.hostname;
console.log(this.hostname);
}
}