Performance: Request object properties
Accessing request object properties affects server response time and can impact how quickly the server processes incoming data.
Jump into concepts and practice - no test required
const { headers } = req;
const userAgent = headers['user-agent'];
const contentType = headers['content-type'];
const host = headers['host'];
// Access headers once and reuseconst userAgent = req.headers['user-agent']; const contentType = req.headers['content-type']; const host = req.headers['host']; // Accessing headers multiple times separately
| Pattern | CPU Usage | Lookup Count | Response Time Impact | Verdict |
|---|---|---|---|---|
| Repeated nested property access | High | Multiple per property | Increases response time under load | [X] Bad |
| Single nested object access with reuse | Low | One per request | Minimal impact on response time | [OK] Good |
method, url, headers, and body that describe the client's request.req.method.req.url.req.path is not standard in Node.js core, req.route is used in some frameworks but not for URL path, and req.address is invalid.const http = require('http');
const server = http.createServer((req, res) => {
res.end(req.headers['content-type']);
});
server.listen(3000);
If a client sends a request with header Content-Type: application/json, what will be the output?req.headers. So content-type is the correct key.req.headers['content-type'], which matches the header sent by the client: application/json.const http = require('http');
const server = http.createServer((req, res) => {
const data = req.body;
res.end(data);
});
server.listen(3000);req.body is not automatically populated. You must collect data chunks and parse them manually or use middleware.req.body directly, which will be undefined, causing the response to send undefined.req.socket.remoteAddress or req.connection.remoteAddress. The req.socket is the modern standard.req.url. Other options like req.path or req.route are not standard in Node.js core.req.socket.remoteAddress and req.url, which is correct and modern.