express-cache-headers

raw JSON →
0.1.4 verified Sat Apr 25 auth: no javascript

An Express middleware for setting response cache headers. Version 0.1.4 is the latest stable release. It allows you to control cache behavior per-route by providing options such as TTL (time-to-live), nocache, private, and mustrevalidate. Unlike more complex caching solutions like apicache or express-cache-ctrl, this package focuses solely on setting cache HTTP headers (Cache-Control, Pragma, Expires) with minimal configuration. It is lightweight and does not require a store, making it ideal for simple caching scenarios where only headers are needed.

error TypeError: cache is not a function
cause Using ES import syntax with this CJS-only package.
fix
Replace import cache from 'express-cache-headers' with const cache = require('express-cache-headers');
error Error: cache is not a function
cause Calling `app.use(cache())` without a default option or incorrect call.
fix
Pass a number or options object: app.use(cache(10)); or app.use(cache({ttl: 10}));
error Warning: Cache-Control headers might be overwritten by res.set()
cause User sets custom Cache-Control after middleware.
fix
Set custom Cache-Control headers before the cache middleware or avoid overriding them.
gotcha When using cache as global middleware, subsequent per-route cache calls will merge/override the global settings, but the global middleware still runs and may set headers before the route-specific middleware.
fix Do not use both global and per-route cache middleware simultaneously; choose one pattern.
gotcha The middleware sets Cache-Control, Pragma, and Expires headers. It does not integrate with any store; cached responses are not actually stored or served from cache—only headers are set.
fix If actual response caching is needed, use a package like apicache or express-cache-ctrl instead.
gotcha The `nocache` option sets Cache-Control: no-cache but also sets Pragma: no-cache and Expires to a past date. This may not be appropriate for all scenarios (e.g., HTTP/1.0 compatibility).
fix Review if you need HTTP/1.0 compatibility; if not, consider manually setting Cache-Control headers.
npm install express-cache-headers
yarn add express-cache-headers
pnpm add express-cache-headers

Demonstrates global and per-route use of cache middleware with ttl, nocache, and private options.

const express = require('express');
const cache = require('express-cache-headers');

const app = express();
const port = process.env.PORT || 3000;

// Global middleware: cache all routes for 10 seconds
app.use(cache(10));

// Override per route: no cache
app.get('/nocache', cache({nocache: true}), (req, res) => {
  res.send('This response is not cached');
});

// Route with custom TTL and private directive
app.get('/private', cache({ttl: 300, private: true}), (req, res) => {
  res.send('Private, cached for 5 minutes');
});

app.listen(port, () => console.log(`Server listening on port ${port}`));