26 July, 2017 Tags: , ,

Fetching the subdomain from URL with Javascript / Nodejs

This is a very quick article where I will talk about a situation that I’ve faced when developing a web app, basically the app had a different behavior for each subdomain, so I needed to identify the subdomains from the main domain.

There’s two approaches to achieve this goal, one in the client-side with plain Javascript and another from the server-side with expressjs.

Client-side with plain Javascript

 

var subdomain = window.location.hostname.split('.')[0];
console.log(subdomain);

In the code above I accessed the global object window.location, and it returns the information about the location of the document or page that was loaded, such as the port, hostname or the domain.

From the properties returned by the window.location we are interested in the host or hostname property, because they return as value the domain name from which the page loaded or requested.

var getHostname = window.location.hostname;

From here we can use regular expressions to get the first word before the point (.) from left to right, but the Javascript string object has a method called split(), it splits the string using a separator character and then returns an array containing each of the small strings obtained. Since a domain consists of names and an extension, and they are separated by periods (.), Then we will proceed like this:

var getArray = getHostname.split('.');

This way we have an array, and since the subdomain is the leftmost item, we get the first element of the array with index 0.

var getSubDominio = getArray[0];

Server side with Nodejs / Express

On the server side the process is as simple as on the client side. Using ExpressJS we can get the subdomain through the request.headers object, it returns a set of properties, including the host property, just like on the client side.

const express = require('express');

const app = express();

// Routes
app.get('/', (request, response) => {
    // Get the subdomain
    let subdomain = request.headers.host.split('.')[0];

    // Sent a response
    response.send(`You are in ${subdomain} subdomain`);
});

So this it. I hope it helps you somehow. If know another way of achieving this result, please comment bellow. Thanks.

OTHER ARTICLES