Over a million developers have joined DZone.

Node.js Quickie: Checking the Current Domain Name

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

I'm working on a quick proof of concept (for a killer idea, honest, I swear) that needs to rely on a subdomain name to determine how the application responds. So, as an example, I want to see something different for foo.app.com versus goo.app.com, and obviously support www.app.com and app.com. Here is a quick way to handle that.

First, my thanks to StackOverflow user cjohn for his answer. If you examine the Request object in your Node app you can introspect the headers object to view the host value.

I did a quick dump (JSON.stringify(req.headers)) to see what this looked like:

Pretty much what I expected. So I wrote a quick little snippet that would focus on returning just the subdomain:

function getSubdomain(h) {
  var parts = h.split(".");
	if(parts.length == 2) return "www";
	return parts[0];

//later on...
exports.index = function(req, res) {
  var subdomain = getSubdomain(req.headers.host);
  res.render('index', { title: 'Express', subdomain:subdomain });

You can see both the function as well as the route that makes use of it. This isn't perfect. If a user hits the site via x.y.app.com then you (probably) want to see x.y as a result, but for my needs I'm fine with just x being returned.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


Published at DZone with permission of Raymond Camden, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}