Performance: req.headers for HTTP headers
Accessing req.headers affects server-side request processing speed and can indirectly impact response time.
app.get('/', (req, res) => { const userAgent = req.headers['user-agent']; // simple check or cache results if possible const isMobile = userAgent.includes('Mobile'); res.send(`Mobile: ${isMobile}`); });
app.get('/', (req, res) => { const userAgent = req.headers['user-agent']; // parsing userAgent multiple times or complex regex const isMobile = /Mobile/.test(userAgent); const isChrome = /Chrome/.test(userAgent); res.send(`Mobile: ${isMobile}, Chrome: ${isChrome}`); });
| Pattern | CPU Usage | Request Latency | Memory Impact | Verdict |
|---|---|---|---|---|
| Complex regex parsing on headers | High | Increased by ms | Low | [X] Bad |
| Simple string checks on headers | Low | Minimal increase | Low | [OK] Good |
req.headers represent in an Express app?req.headersreq.headers holds all headers sent by the client in the HTTP request.req.headers containsreq.headers = client headers [OK]req.headers?req.headersreq.headers.req.headers['content-type'].app.get('/', (req, res) => {
const userAgent = req.headers['user-agent'];
res.send(userAgent);
});req.headers['user-agent'] containsres.send().req.headers['user-agent'] = client info [OK]app.get('/data', (req, res) => {
const auth = req.headers.Authorization;
if (!auth) {
res.status(401).send('Unauthorized');
} else {
res.send('Access granted');
}
});req.headersreq.headers.authorization to access the Authorization header properly.req.headersreq.headers['x-client-id'].req.headers.get('X-Client-Id') which doesn't exist on req.headers.Pass the test and this pattern moves unknown