HTTP Vary Header Manipulator

1.1.2 · active · verified Tue Apr 21

`vary` is a focused Node.js utility library designed for manipulating the HTTP `Vary` response header. It provides a simple API to append fields to the `Vary` header of a Node.js `http.ServerResponse` object or directly to an existing `Vary` header string. Currently at version 1.1.2, the package maintains a stable and slow release cadence, primarily focusing on performance improvements and input validation rather than frequent feature additions. Its key differentiator is its singular purpose, offering a reliable and minimal solution for ensuring correct cache behavior when content varies based on request headers, without introducing additional HTTP framework overhead. It is a foundational utility used by many HTTP servers and middleware in the Node.js ecosystem.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use `vary(res, field)` to add a field to the Vary header of an HTTP response and `vary.append(header, field)` to manipulate a header string.

const http = require('http');
const vary = require('vary');

http.createServer(function onRequest (req, res) {
  // About to user-agent sniff, so add User-Agent to Vary header
  vary(res, 'User-Agent');

  const ua = req.headers['user-agent'] || '';
  const isMobile = /mobi|android|touch|mini/i.test(ua);

  // Serve site, depending on isMobile
  res.setHeader('Content-Type', 'text/html');
  res.end('You are (probably) ' + (isMobile ? '' : 'not ') + 'a mobile user');
}).listen(3000, () => {
  console.log('Server listening on http://localhost:3000');
});

// Example of using vary.append directly on a string
const initialVaryHeader = 'Accept, Accept-Encoding';
const newVaryHeader = vary.append(initialVaryHeader, 'Origin');
console.log('Appended Vary header:', newVaryHeader); // 'Accept, Accept-Encoding, Origin'

view raw JSON →