DEV Community

Cover image for How to Route using Subdomain in React.
Fredy Somy
Fredy Somy

Posted on


How to Route using Subdomain in React.

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")
Enter fullscreen mode Exit fullscreen mode

Well this is the core idea i am using.

What is window.location

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

Enter fullscreen mode Exit fullscreen mode

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.

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)

Why You Need to Study Javascript Fundamentals

The harsh reality for JS Developers: If you don't study the fundamentals, you'll be just another “Coder”. Top learnings on how to get to the mid/senior level faster as a JavaScript developer by Dragos Nedelcu.