Cacheable HTTP/HTTPS Requests

13.0.18 · active · verified Tue Apr 21

cacheable-request provides RFC 7234 compliant HTTP caching for Node.js's native HTTP and HTTPS modules. It is a low-level wrapper, not a high-level request library, designed to add caching capabilities directly to `http.request` or `https.request`. The current stable version is 13.0.18, with frequent patch and minor updates, and occasional breaking changes between major versions as seen in recent changelogs. Key differentiators include its strict adherence to RFC 7234 for cache validation and storage logic, out-of-the-box in-memory caching, and a highly pluggable architecture for various storage adapters, prominently featuring Keyv for flexible backend integration. It handles fresh and stale cache entries, revalidation with `If-None-Match`/`If-Modified-Since`, and 304 responses, updating the `Age` header accordingly.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to wrap Node.js native `http.request` with `cacheable-request` to add RFC-compliant caching. It includes a small server to serve cacheable content and then performs multiple requests to show caching in action, distinguishing between initial requests and cached responses.

import http from 'http';
import CacheableRequest from 'cacheable-request';

// Create a basic HTTP server to simulate responses
const server = http.createServer((req, res) => {
  if (req.url === '/cached') {
    res.setHeader('Cache-Control', 'max-age=10');
    res.setHeader('ETag', '"abc"');
    res.end('Hello from cacheable server!');
  } else {
    res.end('Not cached content');
  }
});

server.listen(3000, async () => {
  console.log('Server listening on http://localhost:3000');

  // Instantiate CacheableRequest with Node's native http.request
  const cacheable = new CacheableRequest(http.request).request();

  const makeRequest = (url) => {
    return new Promise((resolve, reject) => {
      const req = cacheable(url, (response) => {
        let data = '';
        response.on('data', (chunk) => (data += chunk));
        response.on('end', () => {
          console.log(`
URL: ${url}`);
          console.log(`Status: ${response.statusCode}`);
          console.log(`From Cache: ${response.fromCache ? 'Yes' : 'No'}`);
          console.log(`Data: ${data}`);
          resolve({ statusCode: response.statusCode, fromCache: response.fromCache, data });
        });
      });
      req.on('request', (req) => req.end());
      req.on('error', reject);
    });
  };

  console.log('--- First request ---');
  await makeRequest('http://localhost:3000/cached');

  console.log('\n--- Second request (should be from cache) ---');
  await makeRequest('http://localhost:3000/cached');

  console.log('\n--- Request to non-cached path ---');
  await makeRequest('http://localhost:3000/non-cached');

  server.close(() => console.log('\nServer closed.'));
});

view raw JSON →