Performance: Why understanding req matters
Understanding the request object affects server response time and resource usage, impacting how fast the server can handle incoming requests.
app.use((req, res, next) => {
const { headers, url, method } = req;
const userAgent = headers['user-agent'];
const authorization = headers['authorization'];
// Use cached variables instead of repeated property access
if (authorization) {
// do something
}
next();
});app.use((req, res, next) => {
const userAgent = req.headers['user-agent'];
const url = req.url;
const method = req.method;
// Accessing req multiple times without caching
if (req.headers['authorization']) {
// do something
}
next();
});| Pattern | CPU Overhead | Memory Usage | Response Time Impact | Verdict |
|---|---|---|---|---|
| Repeated req property access | Higher due to multiple lookups | Minimal | Increases slightly under load | [X] Bad |
| Cached req properties via destructuring | Lower due to single lookup | Minimal | Improves response speed | [OK] Good |
req object represent?req in Expressreq object contains all the information sent by the user to the server, such as URL parameters, query strings, and request body.req from other objectsres, not req. Database connections and middleware are separate concepts.req = user info [OK]req.params, which holds key-value pairs from the route.req.body holds POST data, req.query holds query strings, and req.url is a string, not an object with params.req.params [OK]app.get('/user/:id', (req, res) => {
console.log(req.query.name);
res.send('Done');
});
// Request URL: /user/123?name=Alicereq.query.name accessesreq.query holds query string parameters from the URL, so req.query.name gets the value of the 'name' query parameter.?name=Alice, so req.query.name is 'Alice'.app.post('/submit', (req, res) => {
const data = req.query.body;
res.send(data);
});req.body, not req.query.req.query.body, which is wrong; it should be req.body.req.body, not req.query [OK]type and a query parameter sort. Which code correctly accesses both parameters?type are in req.params, and query parameters like sort are in req.query.req.params.type and req.query.sort. app.get('/items/:type', (req, res) => { const t = req.query.type; const s = req.params.sort; res.send(`${t} sorted by ${s}`); }); swaps them incorrectly. app.get('/items', (req, res) => { const t = req.params.type; const s = req.query.sort; res.send(`${t} sorted by ${s}`); }); misses the URL param in route. app.get('/items/:type', (req, res) => { const t = req.body.type; const s = req.body.sort; res.send(`${t} sorted by ${s}`); }); wrongly uses req.body which is for POST data.Pass the test and this pattern moves unknown