We use req.ip and req.hostname to find out where a web request comes from and which website address was used. This helps us understand and control how users connect to our server.
0
0
req.ip and req.hostname in Express
Introduction
When you want to log the visitor's IP address for security or analytics.
When you need to customize responses based on the website domain used.
When you want to restrict access to certain IP addresses.
When you want to detect if a request is coming from a trusted domain.
When you want to show different content depending on the hostname.
Syntax
Express
req.ip req.hostname
req.ip gives the IP address of the client making the request.
req.hostname gives the domain name used in the request, without the port number.
Examples
This example prints the visitor's IP address in the console and sends it back in the response.
Express
app.get('/', (req, res) => { console.log(req.ip); res.send('Your IP is ' + req.ip); });
This example prints the hostname used to visit the site and sends it back in the response.
Express
app.get('/', (req, res) => { console.log(req.hostname); res.send('You visited ' + req.hostname); });
This example checks the hostname and sends a special message if it matches 'example.com'.
Express
app.get('/', (req, res) => { if (req.hostname === 'example.com') { res.send('Welcome to example.com!'); } else { res.send('Unknown host'); } });
Sample Program
This simple Express server listens on port 3000. When you visit the root URL, it shows your IP address and the hostname you used to visit.
Express
import express from 'express'; const app = express(); const port = 3000; app.get('/', (req, res) => { const clientIp = req.ip; const hostName = req.hostname; res.send(`Hello! Your IP is ${clientIp} and you visited ${hostName}`); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}/`); });
OutputSuccess
Important Notes
req.ip may show IPv6 format like ::1 for localhost.
req.hostname does not include the port number, only the domain.
If your app is behind a proxy, you may need to set app.set('trust proxy', true) to get the real client IP.
Summary
req.ip tells you the visitor's IP address.
req.hostname tells you the domain name used in the request.
Use these to customize responses or log visitor info in Express apps.