How to Route using Subdomain in React.

How to Route using Subdomain in React.

Fredy Somy's photo
Fredy Somy

Published on Jan 28, 2021

3 min read

Subscribe to my newsletter and never miss my upcoming articles

When i was making my portfolio in React , i wanted to have all components in different subdomains.

Eg :

My domain : ,

I want my Projects component at,
My blog at and more.. I really wanted to do that , but i found nothing. After asking some of my seniors i finally did it with conditional component rendering .

It means if a url is having a specific subdomain , the component ( which we have assigned for the subdomain) should be rendered.


We all know the Web API's . Lets use window.location API

if ('.')[0] == 'projects' 
console.log("projects component")

Well this is the core idea i am using.

What is window.location

{hash: ""
host: ""
hostname: ""
href: ""
origin: ""
pathname: "/"
port: ""
protocol: "https:"}

So window.location gives us the details about the current website url and other stuffs like hostname,href,pathname,protocol etc.

Our goal is to find the subdomain in the url.

>> console.log(
// Here we get the host of the website and the subdomain can be extracted after spliting the above result.
>> console.log('.')[0])
>> projects
// Yes we got the subdomain after spliting the host and getting its 0th index which in here is the subdomain name.

Lets get back to React.

Lets do some basic react stuffs after using CRA template.

import Projects from "./projects/Projects";
// Projects is the component i want to render 
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
// If you are using react router inside the component better wrap the component in </Router>

function App() {
  if (".")[0] == "projects") {
// It checks if the subdomain is named projects.
    return (
        <Header />
        <Projects />

export default App;
// Exporting App

That's the whole code needed to setup a subdomain based router in react.

You can add a else block and render a Error page if needed.


  • Feel free to email me for Bugs Found or queries.

  • I will be happy to help.

  • Cover image taken from here
Share this