Course contentsShow
← Node.js
Lesson 1334 of 1,98012. Caching Strategies and Application SpeedFree lesson

Vary Header Logic for Context-Dependent Caching

You will cache different versions of resources based on request headers like user-agent or language.

In this lesson, you will learn how to use the Vary HTTP header to instruct caches to store multiple versions of a single resource based on specific request header values.

The Problem: One URL, Multiple Faces

Normally, a cache identifies a resource solely by its URL. However, in modern web applications, the same URL might return different content depending on the user's context. For example, you might serve a mobile-optimized layout when the User-Agent suggests a phone, or a localized version of a page based on the Accept-Language header. If you don't account for these, a cache might serve the "English" version to a French user, or a "desktop" layout to a mobile device.

The Solution: The Vary Header

The Vary header is a comma-separated list of request headers that the cache should treat as part of the "cache key." When you include Vary: Accept-Language, the caching layer (like a CDN, a browser, or an intermediate proxy) knows that it shouldn't just store one object for /profile; it must store unique copies based on the value of the Accept-Language header.

In a Node.js Express application, you can set this directly on your response objects:

app.get('/dashboard', (req, res) => {
  // Tell the cache that this response depends on the language and user-agent
  res.setHeader('Vary', 'Accept-Language, User-Agent');
  
  const lang = req.headers['accept-language'] || 'en';
  res.send(renderDashboard(lang));
});

Why it Matters

By using Vary, you prevent "cache poisoning," where the wrong version of a resource is served to the wrong audience. However, proceed with caution: if you include a header with high cardinality (like User-Agent, which has thousands of possible values), you will drastically decrease your cache hit ratio because the cache will be forced to store an enormous number of unique variations. Use Vary sparingly, targeting only the headers that fundamentally change the structure or content of your response.

Key Takeaway: The Vary header forces caches to incorporate specific request header values into their lookup keys, ensuring users receive content tailored to their environment without manually managing separate URLs.