Express res.set() Method
What you’ll learn
- How to set response headers using
res.set(). - How to set multiple headers in one call.
- How header-setting order affects responses.
- How to avoid header overwrite/late-write issues.
Syntax
javascript
res.set(field, value)
res.set({ field1: value1, field2: value2 })1
Set a single response header
javascript
app.get('/cache-demo', function (req, res) {
res.set('Cache-Control', 'public, max-age=60');
res.send('Cached for 60 seconds');
});2
Set multiple headers together
javascript
app.get('/meta', function (req, res) {
res.set({
'X-App-Version': '1.0.0',
'X-Request-Source': 'tutorial'
});
res.send('Header metadata set');
});3
Set header before JSON response
javascript
app.get('/api/data', function (req, res) {
res.set('X-Trace-Id', 'req-101');
res.json({ ok: true });
});⚠️ Common pitfalls
- Set headers before response is sent; late header changes are ignored or error out.
- Be careful with repeated
res.set()calls that overwrite earlier values. - Use clear header naming conventions for custom headers (
X-*or standardized names).
❓ FAQ
It sets HTTP response headers on the outgoing response.
Yes, pass an object with header-name and value pairs.
They are aliases in Express and behave the same way.
Yes, headers should be set before calling methods like res.send(), res.json(), or res.end().
Yes, res.set() replaces the value for that header key.
Did you know?
res.set() supports setting one header at a time or multiple headers through an object map.
4 people found this page helpful
