Performance: res.set for response headers
Setting response headers affects how the browser processes and caches the response, impacting load speed and rendering behavior.
app.get('/data', (req, res) => { res.set({ 'Cache-Control': 'public, max-age=3600', 'Content-Type': 'application/json' }); res.send(JSON.stringify({ message: 'Hello' })); });
app.get('/data', (req, res) => { res.set('Cache-Control', 'no-cache'); res.set('Content-Type', 'application/json'); res.send(JSON.stringify({ message: 'Hello' })); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No caching headers (Cache-Control: no-cache) | N/A | N/A | Higher due to repeated downloads | [X] Bad |
| Proper caching headers (Cache-Control: public, max-age=3600) | N/A | N/A | Lower due to cached resources | [OK] Good |
res.set do in an Express response?res.set is used to add or modify HTTP headers in the response before sending it.res.send, not res.set. Logging or closing connections are unrelated.res.set?res.set(name, value) where both are strings.Content-Type (hyphen requires quotes). res.set('Content-Type', application/json); misses quotes around value.Content-Type header after this code runs?
res.set({
'Content-Type': 'text/html',
'Cache-Control': 'no-cache'
});
res.set('Content-Type', 'application/json');Content-Type is set to 'text/html' via object. Then it is overwritten by res.set('Content-Type', 'application/json').Content-Type is 'application/json', so that is the final header value.app.get('/data', (req, res) => {
res.send('Hello');
res.set('X-Custom-Header', '123');
});res.send because sending the body finalizes the response.res.send is called first, then res.set, which is too late to add headers.Content-Type and Cache-Control in one call, but only if a condition is true. Which code correctly uses res.set with condition?res.set allows setting many headers at once. Wrapping in an if statement applies condition.Pass the test and this pattern moves unknown