Node Fetch Cache

5.1.0 · active · verified Sun Apr 19

node-fetch-cache is a robust wrapper around the popular `node-fetch` library, providing an integrated caching layer for HTTP responses. It automatically caches responses from HTTP requests, serving subsequent identical requests directly from the cache without making a network call. The current stable version is 5.1.0, and the project appears to have an active release cadence with regular updates and maintenance, as indicated by recent releases adding new features like cache clearing. Key differentiators include its seamless integration with the standard `node-fetch` API, support for multiple cache backends (in-memory, file system, Redis via an adapter), and flexible control over caching behavior through `shouldCacheResponse` options. It's designed for Node.js environments, requiring Node.js 18.19.0 or higher, and ships with TypeScript types for improved developer experience.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `node-fetch-cache` with a file system cache, including setting a TTL, filtering responses to cache, and programmatically clearing the cache directory.

import fetch from 'node-fetch-cache';
import { FileSystemCache } from 'node-fetch-cache';
import * as path from 'path';

async function fetchData() {
  // Create a custom fetch instance that caches to disk with a 1-hour TTL
  const diskCacheFetch = NodeFetchCache.create({
    cache: new FileSystemCache({
      cacheDirectory: path.join(process.cwd(), '.node-fetch-cache'),
      ttl: 3600000 // 1 hour in milliseconds
    }),
    shouldCacheResponse: (response) => response.ok // Only cache successful responses
  });

  console.log('Fetching Google homepage (first time - network request)...');
  const firstResponse = await diskCacheFetch('http://google.com');
  console.log('Status:', firstResponse.status);
  console.log('Cached:', firstResponse.headers.get('x-nf-cache-status')); // Should be 'MISS'

  console.log('\nFetching Google homepage (second time - from cache)...');
  const secondResponse = await diskCacheFetch('http://google.com');
  console.log('Status:', secondResponse.status);
  console.log('Cached:', secondResponse.headers.get('x-nf-cache-status')); // Should be 'HIT'

  // Demonstrate clearing the cache
  const fileCache = new FileSystemCache({ cacheDirectory: path.join(process.cwd(), '.node-fetch-cache') });
  console.log('\nClearing file system cache...');
  await fileCache.clear();
  console.log('Cache cleared. Subsequent fetch will be a MISS again.');

  const thirdResponse = await diskCacheFetch('http://google.com');
  console.log('Status:', thirdResponse.status);
  console.log('Cached:', thirdResponse.headers.get('x-nf-cache-status')); // Should be 'MISS' again
}

fetchData().catch(console.error);

view raw JSON →