{"id":11418,"library":"node-fetch-cache","title":"Node Fetch Cache","description":"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.","status":"active","version":"5.1.0","language":"javascript","source_language":"en","source_url":"https://github.com/mistval/node-fetch-cache","tags":["javascript","node","fetch","node-fetch","cache","cached","typescript"],"install":[{"cmd":"npm install node-fetch-cache","lang":"bash","label":"npm"},{"cmd":"yarn add node-fetch-cache","lang":"bash","label":"yarn"},{"cmd":"pnpm add node-fetch-cache","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core dependency; this package wraps node-fetch to add caching functionality. Its API is a superset of node-fetch's.","package":"node-fetch","optional":false},{"reason":"Optional dependency for using Redis as a cache backend.","package":"@node-fetch-cache/redis","optional":true}],"imports":[{"note":"The primary way to use node-fetch-cache, mimicking `node-fetch`'s default import. Node.js >=18.19.0 supports ESM natively, so CJS `require` is generally incorrect or requires bundler setup.","wrong":"const fetch = require('node-fetch-cache');","symbol":"fetch","correct":"import fetch from 'node-fetch-cache';"},{"note":"Used for creating custom fetch instances with specific caching configurations, e.g., `NodeFetchCache.create({ cache: new FileSystemCache() })`.","symbol":"NodeFetchCache","correct":"import NodeFetchCache from 'node-fetch-cache';"},{"note":"Correctly imported as a named export. Incorrectly using it as a default export or incorrectly assuming it's part of the default export `NodeFetchCache` is a common mistake.","wrong":"import NodeFetchCache, { FileSystemCache } from 'node-fetch-cache';","symbol":"FileSystemCache","correct":"import { FileSystemCache } from 'node-fetch-cache';"},{"note":"Used for explicit in-memory caching with TTL configuration. Note that the default cache is also `MemoryCache` but without a TTL.","symbol":"MemoryCache","correct":"import { MemoryCache } from 'node-fetch-cache';"}],"quickstart":{"code":"import fetch from 'node-fetch-cache';\nimport { FileSystemCache } from 'node-fetch-cache';\nimport * as path from 'path';\n\nasync function fetchData() {\n  // Create a custom fetch instance that caches to disk with a 1-hour TTL\n  const diskCacheFetch = NodeFetchCache.create({\n    cache: new FileSystemCache({\n      cacheDirectory: path.join(process.cwd(), '.node-fetch-cache'),\n      ttl: 3600000 // 1 hour in milliseconds\n    }),\n    shouldCacheResponse: (response) => response.ok // Only cache successful responses\n  });\n\n  console.log('Fetching Google homepage (first time - network request)...');\n  const firstResponse = await diskCacheFetch('http://google.com');\n  console.log('Status:', firstResponse.status);\n  console.log('Cached:', firstResponse.headers.get('x-nf-cache-status')); // Should be 'MISS'\n\n  console.log('\\nFetching Google homepage (second time - from cache)...');\n  const secondResponse = await diskCacheFetch('http://google.com');\n  console.log('Status:', secondResponse.status);\n  console.log('Cached:', secondResponse.headers.get('x-nf-cache-status')); // Should be 'HIT'\n\n  // Demonstrate clearing the cache\n  const fileCache = new FileSystemCache({ cacheDirectory: path.join(process.cwd(), '.node-fetch-cache') });\n  console.log('\\nClearing file system cache...');\n  await fileCache.clear();\n  console.log('Cache cleared. Subsequent fetch will be a MISS again.');\n\n  const thirdResponse = await diskCacheFetch('http://google.com');\n  console.log('Status:', thirdResponse.status);\n  console.log('Cached:', thirdResponse.headers.get('x-nf-cache-status')); // Should be 'MISS' again\n}\n\nfetchData().catch(console.error);","lang":"typescript","description":"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."},"warnings":[{"fix":"For in-memory caching with expiration, create a custom fetch instance: `NodeFetchCache.create({ cache: new MemoryCache({ ttl: 60000 }) })`. For persistent caching, consider `FileSystemCache` or `@node-fetch-cache/redis`.","message":"By default, `node-fetch-cache` uses an in-memory cache with no Time-To-Live (TTL). This means cached responses will persist indefinitely within the process's lifetime, potentially leading to stale data or excessive memory consumption if not explicitly configured with a `MemoryCache` instance and a `ttl`.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Implement a periodic cleanup mechanism by calling the `.clear()` method on your `FileSystemCache` instance, which will delete the entire cache directory. For example, `new FileSystemCache(options).clear()` in a cron job or scheduled task.","message":"When using `FileSystemCache` with a `ttl`, expired cache entries are not automatically deleted from disk. This can lead to significant disk bloat over time as invalid files accumulate in the cache directory.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Consult the `node-fetch` documentation and release notes for relevant breaking changes when upgrading the underlying `node-fetch` version or `node-fetch-cache` itself.","message":"`node-fetch-cache` is a wrapper around `node-fetch`. Any breaking changes introduced in major versions of `node-fetch` (e.g., changes to its API or underlying mechanisms) will inherently affect `node-fetch-cache` users. Always review `node-fetch`'s release notes when upgrading.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Be explicit about where you define your caching options. If an option is present in both `create()` and `fetch()`, the `fetch()`-level option will override the `create()`-level option for that specific request.","message":"When configuring caching behavior, options passed directly to the `fetch()` call take precedence over options configured via `NodeFetchCache.create()`. This merging behavior might lead to unexpected caching if not understood.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Use ESM `import fetch from 'node-fetch-cache';` instead of `const fetch = require('node-fetch-cache');`.","cause":"Attempting to use `require()` to import `node-fetch-cache` in an environment configured for ESM or when `type: module` is set in `package.json`.","error":"TypeError: fetch is not a function"},{"fix":"Ensure the `cacheDirectory` path is valid and accessible by the Node.js process. The library should create the directory if it doesn't exist, but permission issues or invalid root paths can prevent this. Check permissions and path correctness.","cause":"The specified `cacheDirectory` for `FileSystemCache` does not exist and the process lacks permissions to create it, or an incorrect path was provided.","error":"ENOENT: no such file or directory, scandir '/path/to/.node-fetch-cache'"}],"ecosystem":"npm"}