Bird
Raised Fist0
Expressframework~10 mins

req.ip and req.hostname in Express - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - req.ip and req.hostname
Incoming HTTP Request
↓
Express Middleware
↓
Access req.ip
→Get Client IP Address
↓
Access req.hostname
→Get Hostname from Request
↓
Use IP and Hostname in App Logic
When Express receives a request, you can get the client's IP using req.ip and the hostname using req.hostname to use in your app.
Execution Sample
Express
app.get('/', (req, res) => {
  const clientIp = req.ip;
  const host = req.hostname;
  res.send(`IP: ${clientIp}, Hostname: ${host}`);
});
This code gets the client's IP and hostname from the request and sends them back in the response.
Execution Table
StepActionreq.ipreq.hostnameResult
1Request arrives from clientundefinedundefinedWaiting for middleware
2Express parses request192.168.1.10example.comreq.ip and req.hostname set
3Handler reads req.ip192.168.1.10example.comClient IP captured
4Handler reads req.hostname192.168.1.10example.comHostname captured
5Response sent192.168.1.10example.comResponse: 'IP: 192.168.1.10, Hostname: example.com'
6Request processing ends192.168.1.10example.comDone
💡 Request handled and response sent with client IP and hostname
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
req.ipundefined192.168.1.10192.168.1.10192.168.1.10192.168.1.10
req.hostnameundefinedexample.comexample.comexample.comexample.com
Key Moments - 2 Insights
Why is req.ip available only after Express parses the request?
Because Express needs to read the incoming request headers and connection info first to determine the IP, as shown in step 2 of the execution_table.
Can req.hostname be different from the actual domain the client typed?
Yes, req.hostname is taken from the Host header sent by the client, so if the client spoofs it, it can differ. See step 2 where req.hostname is set from the request.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of req.ip at step 3?
Aundefined
B192.168.1.10
Cexample.com
Dlocalhost
💡 Hint
Check the 'req.ip' column at step 3 in the execution_table.
At which step does Express set req.hostname?
AStep 2
BStep 1
CStep 4
DStep 5
💡 Hint
Look at the 'req.hostname' column and see when it changes from undefined.
If the client sends a request with Host header 'myapp.local', what changes in the execution_table?
Areq.ip changes to 'myapp.local'
Breq.ip and req.hostname both become 'myapp.local'
Creq.hostname changes to 'myapp.local'
DNo changes, values stay the same
💡 Hint
req.hostname reflects the Host header from the client, as shown in step 2.
Concept Snapshot
req.ip and req.hostname in Express

- req.ip gives the client's IP address
- req.hostname gives the hostname from the Host header
- Both are available after Express parses the request
- Use them to customize responses or logging
- req.hostname depends on client-sent headers
- req.ip can be affected by proxies or network setup
Full Transcript
When an HTTP request arrives in Express, the framework reads the request details. It sets req.ip to the client's IP address and req.hostname to the hostname from the Host header. These values are undefined before parsing. After parsing, handlers can access req.ip and req.hostname to know who sent the request and what hostname was used. This is useful for logging, security, or customizing responses. The IP is usually the client's network address, while hostname is what the client typed or sent in headers. Both are available during request handling.

Practice

(1/5)
1. What does req.ip represent in an Express app?
easy
A. The visitor's IP address
B. The domain name used in the request
C. The server's IP address
D. The HTTP method of the request

Solution

  1. Step 1: Understand the purpose of req.ip

    req.ip provides the IP address of the client making the request.
  2. Step 2: Differentiate from req.hostname

    req.hostname gives the domain name, not the IP address.
  3. Final Answer:

    The visitor's IP address -> Option A
  4. Quick Check:

    req.ip = visitor's IP [OK]
Hint: Remember: IP is address, hostname is domain name [OK]
Common Mistakes:
  • Confusing req.ip with req.hostname
  • Thinking req.ip is server IP
  • Assuming req.ip gives HTTP method
2. Which of the following is the correct way to access the hostname in an Express route handler?
easy
A. req.host
B. req.domain
C. req.hostname
D. req.hostName

Solution

  1. Step 1: Recall Express request object properties

    The correct property for the domain name is req.hostname.
  2. Step 2: Check other options for validity

    req.host, req.domain, and req.hostName are not valid Express properties.
  3. Final Answer:

    req.hostname -> Option C
  4. Quick Check:

    Hostname property = req.hostname [OK]
Hint: Hostname is all lowercase: req.hostname [OK]
Common Mistakes:
  • Using req.host instead of req.hostname
  • Capitalizing property names incorrectly
  • Assuming req.domain exists
3. Consider this Express route handler: <pre>app.get('/', (req, res) => { res.send(`IP: ${req.ip}, Hostname: ${req.hostname}`); }); If a user visits http://example.com from IP 192.168.1.5, what will be the response text?
medium
A. IP: undefined, Hostname: example.com
B. IP: example.com, Hostname: 192.168.1.5
C. IP: 127.0.0.1, Hostname: localhost
D. IP: 192.168.1.5, Hostname: example.com

Solution

  1. Step 1: Identify req.ip and req.hostname values

    req.ip gives the visitor's IP, which is 192.168.1.5. req.hostname gives the domain, which is example.com.
  2. Step 2: Substitute values into the response string

    The response string becomes: IP: 192.168.1.5, Hostname: example.com.
  3. Final Answer:

    IP: 192.168.1.5, Hostname: example.com -> Option D
  4. Quick Check:

    IP and hostname match request info [OK]
Hint: Match IP to visitor, hostname to domain in response [OK]
Common Mistakes:
  • Swapping IP and hostname values
  • Assuming localhost IP instead of visitor IP
  • Using undefined or wrong properties
4. You wrote this Express middleware: <pre>app.use((req, res, next) => { console.log(req.ipAddress); next(); }); What is the problem with this code?
medium
A. Middleware must be declared after routes
B. req.ipAddress is not a valid property; should use req.ip
C. Logging should be done with res.ip instead
D. Missing call to next() to continue middleware chain

Solution

  1. Step 1: Check property names on req

    req.ipAddress does not exist in Express; the correct property is req.ip.
  2. Step 2: Verify middleware correctness

    The middleware calls next(), so chain continues correctly.
  3. Final Answer:

    req.ipAddress is not a valid property; should use req.ip -> Option B
  4. Quick Check:

    Use req.ip for IP address [OK]
Hint: Use exact property names: IP is req.ip [OK]
Common Mistakes:
  • Using req.ipAddress instead of req.ip
  • Forgetting to call next()
  • Trying to log IP from res object
5. You want to restrict access to your Express app only to requests coming from the domain trusted.com. Which code snippet correctly uses req.hostname to allow this?
hard
A. app.use((req, res, next) => { if (req.hostname === 'trusted.com') next(); else res.status(403).send('Forbidden'); });
B. app.use((req, res, next) => { if (req.ip === 'trusted.com') next(); else res.status(403).send('Forbidden'); });
C. app.use((req, res, next) => { if (req.host === 'trusted.com') next(); else res.status(403).send('Forbidden'); });
D. app.use((req, res, next) => { if (req.hostname.includes('trusted.com')) next(); else res.status(403).send('Forbidden'); });

Solution

  1. Step 1: Use req.hostname to check exact domain

    app.use((req, res, next) => { if (req.hostname === 'trusted.com') next(); else res.status(403).send('Forbidden'); }); correctly compares req.hostname to the string 'trusted.com'.
  2. Step 2: Evaluate other options for correctness

    app.use((req, res, next) => { if (req.ip === 'trusted.com') next(); else res.status(403).send('Forbidden'); }); wrongly compares 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.
  3. Final Answer:

    Option A code snippet -> Option A
  4. Quick Check:

    Exact match with req.hostname = app.use((req, res, next) => { if (req.hostname === 'trusted.com') next(); else res.status(403).send('Forbidden'); }); [OK]
Hint: Check exact domain with req.hostname === 'domain' [OK]
Common Mistakes:
  • Comparing IP to domain string
  • Using invalid property req.host
  • Using partial match instead of exact domain
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard