Performance: req.ip and req.hostname
Accessing req.ip and req.hostname affects server-side request handling speed and can impact response time if used inefficiently.
app.use((req, res, next) => {
req.clientIp = req.ip;
req.clientHostname = req.hostname;
// Avoid DNS lookup or perform async caching if needed
next();
});app.use((req, res, next) => {
const ip = req.ip;
const hostname = req.hostname;
// Synchronous DNS lookup for hostname
const dns = require('dns');
let address;
try {
address = dns.lookupSync(hostname);
} catch (err) {
return next(err);
}
req.resolvedAddress = address;
next();
});| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Access req.ip and req.hostname directly | N/A (server-side) | N/A | N/A | [OK] Good |
| Perform synchronous DNS lookup on req.hostname | N/A | N/A | N/A | [X] Bad |
req.ip represent in an Express app?req.ipreq.ip provides the IP address of the client making the request.req.hostnamereq.hostname gives the domain name, not the IP address.req.ip = visitor's IP [OK]req.ip with req.hostnamereq.ip is server IPreq.ip gives HTTP methodreq.hostname.req.host, req.domain, and req.hostName are not valid Express properties.req.hostname [OK]req.hostname [OK]req.host instead of req.hostnamereq.domain existshttp://example.com from IP 192.168.1.5, what will be the response text?req.ip and req.hostname valuesreq.ip gives the visitor's IP, which is 192.168.1.5. req.hostname gives the domain, which is example.com.IP: 192.168.1.5, Hostname: example.com.reqreq.ipAddress does not exist in Express; the correct property is req.ip.next(), so chain continues correctly.req.ipAddress is not a valid property; should use req.ip -> Option Breq.ip for IP address [OK]req.ip [OK]req.ipAddress instead of req.ipnext()res objecttrusted.com. Which code snippet correctly uses req.hostname to allow this?req.hostname to check exact domainreq.hostname to the string 'trusted.com'.req.ip to a domain string. app.use((req, res, next) => { if (req.host === 'trusted.com') next(); else res.status(403).send('Forbidden'); }); uses invalid req.host. app.use((req, res, next) => { if (req.hostname.includes('trusted.com')) next(); else res.status(403).send('Forbidden'); }); uses includes which may allow subdomains, not exact match.req.hostname = app.use((req, res, next) => { if (req.hostname === 'trusted.com') next(); else res.status(403).send('Forbidden'); }); [OK]req.hostname === 'domain' [OK]req.hostPass the test and this pattern moves unknown