title: Subdomain Routing in React and React Router
body: <p>I have 3 types of users and we want to maintain the same code base for the project instead of having 3-4 code bases when most views are just subjective to the kind of users.</p>
  <blockquote>
  <p>Admin &gt; admin.example.com</p>
  <p>Moderator &gt; moderator.example.com</p>
  <p>Brands &gt; brands.example.com</p>
  </blockquote>
  <p>My structure of the React App</p>
  <pre><code>src
  -BaseRoutes.js &lt;--- Should handle by subdomain logic
  - modules
  -- admin
  ---- AdminRoutes.js &lt;---- handles all Admin route logic
  ---- components
  ---- pages
  -- moderator
  ---- ModeratorRoutes.js &lt;---- handles all Moderator route logic
  ---- components
  ---- pages
  -- brands
  ---- BrandsRoutes.js &lt;---- handles all Brands route logic
  ---- components
  ---- pages
  - components
  - pages
  </code></pre>
  <p>Each type of user will have its own authentication to allow access to inner routes. I found a function to split the domain and do the routing using the following:</p>
  <pre><code>let host = window.location.host;
  let protocol = window.location.protocol;
  let parts = host.split(&quot;.&quot;);
  let subdomain = &quot;&quot;;
  // 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 &gt;= 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 + &quot;//&quot; + parts.join(&quot;.&quot;) + &quot;/&quot; + subdomain;
  }
  </code></pre>
  <p>Is this the right way to handle subdomain based routing in React? I have never used a single code base for multiple user types. So confused about the right implementation.</p>