Express res.vary() Method

Beginner
⏱️ 7 min read
📚 Updated: May 2026
🎯 3 Code Examples

What you’ll learn

  • What the HTTP Vary header 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 Vary with negotiated responses can cause wrong cached variants.
  • Call res.vary() before sending the response body.
  • Avoid adding irrelevant fields to Vary because 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.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

4 people found this page helpful