Registry / http-networking / cacheable-request

cacheable-request

JSON →
library13.0.18jsnpmunverified

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.

npm install cacheable-request
INSTALL
IMPORT
SIG · CACHEABLE-REQUEST
C
cacheable-request
http-networkingjavascriptv13.0.18
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

CacheableRequest
import CacheableRequest from 'cacheable-request';
const CacheableRequest = require('cacheable-request');
Package is pure ESM since v9. CommonJS `require` is not supported. Use dynamic `import()` for CJS contexts.
Request
import CacheableRequest, { Request } from 'cacheable-request';
The `Request` type can be imported for TypeScript usage when defining custom request wrappers or extending functionality.
Options
import { Options } from 'cacheable-request';
Import `Options` type for configuring `CacheableRequest` instances in TypeScript.

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.')); });
Debug
Known issues
breakingStarting with v13.0.0, the `CacheableRequest` constructor no longer accepts a direct connection string for Keyv. Instead, you must pass an already instantiated Keyv instance or a Keyv storage adapter instance.
fix
Initialize `Keyv` separately and pass the instance: `import Keyv from '@keyv/redis'; const cache = new Keyv('redis://...'); new CacheableRequest(http.request, { cache }).request();`
affects: >=13.0.0
breakingAs of v10.0.0, after instantiating `new CacheableRequest(http.request)`, you must explicitly call the `.request()` method on the instance to get the callable function. Direct instantiation no longer returns the request function.
fix
Change `const cacheableRequest = new CacheableRequest(http.request);` to `const cacheableRequest = new CacheableRequest(http.request).request();`
affects: >=10.0.0
breakingVersion 9 and higher of `cacheable-request` are pure ESM modules. CommonJS `require()` is no longer supported and will result in an `ERR_REQUIRE_ESM` error.
fix
Migrate your project to use ES Modules (e.g., set `"type": "module"` in `package.json` and use `import`). For existing CommonJS projects, consider staying on v8 or lower, or use dynamic `import()` for `cacheable-request`.
affects: >=9.0.0
gotchaThis package is a low-level wrapper for Node.js's native `http.request` and `https.request`. It is not a high-level HTTP client library like `axios` or `node-fetch`. It provides caching functionality but does not abstract away the complexities of native HTTP requests.
fix
Understand that you will still interact with Node's native `IncomingMessage` and `ClientRequest` objects. If you need a higher-level API, integrate `cacheable-request` with a compatible client library or use a different client that offers built-in caching.
affects: *
breakingIn the monorepo, `node-cache` (which can be used as a storage adapter for `cacheable-request`) removed the `maxKeys` limit feature in a recent patch version within the v13 series. If you relied on this limit for in-memory NodeCacheStore, it's no longer available.
fix
Review your cache eviction strategies if using `node-cache` storage. Consider implementing alternative memory management or switching to a Keyv adapter with explicit size limits if `maxKeys` functionality is critical.
affects: >=13.0.0
Errors
Common errors & fixes
ERR_REQUIRE_ESM: require() of ES Module .../node_modules/cacheable-request/index.js from ... not supported.
`cacheable-request` is an ES Module, but you are trying to import it using CommonJS `require()`.
fix
Update your project to use ES Modules (e.g., `"type": "module"` in `package.json` and `import CacheableRequest from 'cacheable-request';`) or use dynamic `import()` if you must remain in a CommonJS context: `const { default: CacheableRequest } = await import('cacheable-request');`
TypeError: cacheableRequest is not a function
After `new CacheableRequest(...)`, you did not call the `.request()` method, so `cacheableRequest` is an object, not the callable request function.
fix
Change `const cacheableRequest = new CacheableRequest(http.request);` to `const cacheableRequest = new CacheableRequest(http.request).request();`
KeyvConnectionError: Invalid connection string
Attempting to pass a connection string directly to the `CacheableRequest` constructor in v13+.
fix
Instantiate Keyv with the connection string first, then pass the Keyv instance to `CacheableRequest`: `const cache = new Keyv('redis://localhost:6379'); const cacheableRequest = new CacheableRequest(http.request, { cache }).request();`
Argument of type 'string' is not assignable to parameter of type 'ClientRequestArgs'
Attempting to pass a URL string directly to the `cacheableRequest` function expecting `ClientRequestArgs` in TypeScript without proper overload.
fix
Ensure you are using the correct function signature, or cast the argument if you are certain of its compatibility, e.g., `cacheableRequest('http://example.com', { /* options */ }, callback);` or ensure the `request` function is correctly typed if you've wrapped it.
Upgrade
Version history
13.0.18latest on npm
Audit
Dependencies
keyvrequiredUsed as the primary storage mechanism and adapter for various cache backends. Required for custom storage configurations.
Agent activity
17 hits · last 30 days
node
14
Amazon
1
OpenAI (training)
1
Resources
cacheable-request — npm install cacheable-request · libregistry