by Sai gowtham

How to get the hostname in Node.js Express

Learn, how to get the hostname or domain name of a current HTTP request in express.

Using req.hostname property

We can use the req.hostname property to get the hostname from a current incoming request in express.

Example:

const express = require("express");
const app = express();

app.get("/users", (req, res) => {

    console.log(req.hostname); // fun24.com
    res.send('users');
});

If you need a port number along with the hostname, you can use the req.header('host') method.

const express = require("express");
const app = express();

app.get("/users", (req, res) => {

    console.log(req.hostname); // fun24.com:3900
    res.send('users');
});

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course