The Vary: Accept HTTP header is used to specify the request headers that influence content negotiation for a given response. More specifically, Vary: Accept indicates that the response selection is based on the Accept header, which describes the media types the client expects to receive.
Function
When a server provides multiple representations of the same resource, it selects the appropriate content type based on the Accept header in the request. For example, a resource may be available in both JSON and XML formats, and the server determines which format to return based on the value of the Accept header.
Caching Impact
The Vary: Accept header is crucial for HTTP caching. It specifies that the validity of a cached response depends on the value of the Accept header. This means that if a cache previously stored a response for a request with Accept: application/json, when another request arrives with Accept: application/xml, the cache should recognize that these requests require different response versions and must not serve the previously cached response to requests expecting XML.
Example Scenario
Suppose there is an API endpoint /api/data that returns data in JSON or XML format. When the first client sends a request GET /api/data with the header Accept: application/json, the server detects the Accept header, returns JSON-formatted data, and includes Vary: Accept in the response headers. This ensures that any caching service understands the response is only valid for subsequent requests expecting JSON.
If another client then requests GET /api/data with the header Accept: application/xml, even though the URL is identical, the cache recognizes that it must provide a different response based on the Accept header's value or fetch new data from the server in the correct format.
In this way, Vary: Accept ensures the correct content version is properly stored and served, optimizing network resource usage and enhancing user experience.