cacheable-middleware

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

Middleware for Express/Connect to set HTTP cache headers (Cache-Control, Expires) on responses. Version 1.0.0 (latest) requires Node >=6. Methods: res.cacheFor(milliseconds) or res.cacheFor(amount, unit) using Moment.js duration syntax. Can also set default cache duration for all routes in a middleware stack. Lightweight, no dependencies beyond Node built-ins. Differs from express-cache-headers by offering both per-response and global configuration.

error TypeError: cacheable is not a function
cause Importing incorrectly (e.g., named import when using default export).
fix
Use default import: const cacheable = require('cacheable-middleware');
error Error: Cannot find module 'cacheable-middleware'
cause Package not installed or typo in package name.
fix
Run npm install cacheable-middleware and verify package.json.
error TypeError: res.cacheFor is not a function
cause Middleware not applied before route handler.
fix
Ensure app.use(cacheable()) is called before defining routes that use res.cacheFor().
breaking Version 1.0.0 drops support for Node.js < 6. Requires ES6 features.
fix Upgrade Node.js to version 6 or higher.
deprecated Equivalent functionality exists in HTTP framework built-in features (Express 'static' middleware cache options) and dedicated cache-control modules.
fix Consider using express.static with maxAge option for static files: app.use('/static', express.static('public', { maxAge: '1d' })).
gotcha Duration units are parsed by Moment.js; invalid strings may throw or produce unexpected durations.
fix Use valid Moment.js duration formats: number (milliseconds) or number + string (e.g., 6, 'months', 3, 'hours').
gotcha res.cacheFor() must be called before res.send() or res.json() to set headers properly.
fix Call res.cacheFor() at the beginning of the route handler, before sending response.
npm install cacheable-middleware
yarn add cacheable-middleware
pnpm add cacheable-middleware

Demonstrates two usage patterns: global cache duration applied to a path and per-response control via res.cacheFor().

const express = require('express');
const cacheable = require('cacheable-middleware');

const app = express();

// Set default cache to 1 hour (3600000 ms) for all /static routes
app.use('/static', cacheable(3600000));

// Per-route caching using res.cacheFor()
app.get('/dynamic', (req, res) => {
  res.cacheFor(60000); // cache for 1 minute
  res.json({ message: 'this response is cached for 1 minute' });
});

// Use Moment.js duration syntax (value, unit string)
app.get('/long', (req, res) => {
  res.cacheFor(6, 'months');
  res.send('cached for 6 months');
});

app.listen(3000);