Node.js Quickie - checking the current domain name

This post is more than 2 years old.

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 versus, and obviously support and 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:

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 then you (probably) want to see x.y as a result, but for my needs I'm fine with just x being returned.

Raymond Camden's Picture

About Raymond Camden

Raymond is a senior developer evangelist for Adobe. He focuses on document services, JavaScript, and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA

Archived Comments

Comment 1 by VIKAS posted on 5/2/2018 at 10:45 AM

var host = req.get('host'); and var origin = req.get('origin'); will also work fine without doing this much coding

Comment 2 (In reply to #1) by Raymond Camden posted on 5/2/2018 at 1:07 PM

Cool. Maybe this wasn't around 5 years ago. But more likely - I just didn't know. ;)