Express res.vary() Method
What you’ll learn
- What the HTTP
Varyheader does in cached responses. - How to use
res.vary()in Express handlers. - How to combine content negotiation with cache-safe headers.
- How to avoid stale or incorrect cached content.
Syntax
javascript
res.vary(field)1
Vary by Accept header
javascript
app.get('/profile', function (req, res) {
res.vary('Accept');
if (req.accepts('html')) return res.type('html').send('<h1>Profile</h1>');
res.json({ name: 'Mari' });
});2
Vary by Accept-Encoding
javascript
app.get('/bundle.js', function (req, res) {
res.vary('Accept-Encoding');
res.type('application/javascript');
res.send('console.log("bundle");');
});3
Add multiple vary fields safely
javascript
app.get('/greeting', function (req, res) {
res.vary('Accept-Language');
res.vary('Accept');
res.send('Hello');
});⚠️ Common pitfalls
- Skipping
Varywith negotiated responses can cause wrong cached variants. - Call
res.vary()before sending the response body. - Avoid adding irrelevant fields to
Varybecause it can reduce cache efficiency.
❓ FAQ
It adds one or more field names to the Vary response header.
It tells caches which request headers affect the response representation.
Yes. Express appends safely and avoids duplicate entries.
Use it when the same URL can return different content types based on the Accept header.
No. It only sets headers; you still send with res.send/res.json/res.end.
Did you know?
res.vary(field) updates the Vary header so caches know which request headers can change a response.
4 people found this page helpful
