0
0
Expressframework~20 mins

req.ip and req.hostname in Express - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Express IP & Hostname Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
Understanding req.ip in Express

What will be the value of req.ip when a client makes a request to an Express server running locally?

Express
app.get('/', (req, res) => {
  res.send(req.ip);
});
A"localhost"
B"::1"
C"127.0.0.1"
D"example.com"
Attempts:
2 left
💡 Hint

Think about how IPv6 localhost address is represented.

component_behavior
intermediate
2:00remaining
Behavior of req.hostname in Express

If a client accesses an Express app via http://myapp.example.com, what will req.hostname return?

Express
app.get('/', (req, res) => {
  res.send(req.hostname);
});
A"myapp.example.com"
B"example.com"
C"localhost"
D"undefined"
Attempts:
2 left
💡 Hint

Consider what part of the URL req.hostname extracts.

component_behavior
advanced
2:00remaining
Accessing non-existent req.ipAddress

What happens when executing this code to get the client's IP address in Express?

Express
app.get('/', (req, res) => {
  const clientIp = req.ipAddress;
  res.send(clientIp);
});
AReturns the client's IP address as a string
BReferenceError because req.ipAddress is undefined
CReturns undefined without error
DSyntaxError due to invalid property access
Attempts:
2 left
💡 Hint

Check what happens when accessing a non-existent property on an object.

state_output
advanced
2:00remaining
Output of req.hostname with port in Host header

What will req.hostname return if the client sends a request with the Host header set to myapp.example.com:3000?

Express
app.get('/', (req, res) => {
  res.send(req.hostname);
});
A"localhost"
B"myapp.example.com:3000"
C"example.com"
D"myapp.example.com"
Attempts:
2 left
💡 Hint

Remember how Express parses the Host header for hostname.

🔧 Debug
expert
3:00remaining
Debugging incorrect req.ip behind a proxy

An Express app is behind a proxy. The developer notices req.ip always shows the proxy's IP, not the client's. What is the correct fix?

Express
app.set('trust proxy', false);
app.get('/', (req, res) => {
  res.send(req.ip);
});
ASet app.set('trust proxy', true) to trust the proxy headers
BUse req.hostname instead of req.ip to get client IP
CDisable the proxy to get the real client IP
DManually parse req.headers['x-forwarded-for'] without changing trust proxy
Attempts:
2 left
💡 Hint

Express needs to trust the proxy to get the real client IP.