Nocache Middleware

4.0.0 · active · verified Wed Apr 22

The `nocache` package is an Express/Connect middleware designed to aggressively disable client-side caching by setting specific HTTP response headers. It is currently at stable version 4.0.0. As a component of the Helmet.js suite, its release cadence is generally tied to Helmet's, focusing on stability and security rather than frequent feature additions, with major version updates typically aligning with Node.js EOLs or significant breaking changes. Its primary differentiator is its simplicity and integration within the broader Helmet.js ecosystem, providing a straightforward, opinionated way to ensure clients always request fresh resources. This is crucial for applications sensitive to stale data, enforcing immediate updates, or handling sensitive information that should never reside in a browser cache. It effectively sets `Cache-Control`, `Expires`, and `Surrogate-Control` headers.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to initialize an Express application and apply the `nocache` middleware globally, ensuring all HTTP responses include headers designed to disable client-side caching.

import express from 'express';
import nocache from 'nocache';

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

// Apply the nocache middleware globally to all routes.
// This ensures that all responses from this server attempt to disable client-side caching.
app.use(nocache());

app.get('/', (req, res) => {
  res.send('<h1>Welcome!</h1><p>This content should not be cached by your browser.</p>');
});

app.get('/api/data', (req, res) => {
  // Even API endpoints will have caching headers applied, forcing fresh requests.
  res.json({ message: 'Dynamic data from API', timestamp: new Date().toISOString() });
});

app.listen(port, () => {
  console.log(`Nocache server listening on port ${port}`);
  console.log('Inspect network requests in your browser to see Cache-Control, Expires, and Surrogate-Control headers set to disable caching.');
});

view raw JSON →