What is cacheable-request?
The cacheable-request npm package is a wrapper for the native HTTP/HTTPS request functionality in Node.js, providing an easy-to-use cache layer for repeat requests. It is designed to cache responses based on their Cache-Control header and supports the caching of GET and HEAD requests.
What are cacheable-request's main functionalities?
Caching GET and HEAD requests
This feature allows you to cache GET and HEAD requests. The code sample shows how to create a cacheable request using the cacheable-request package with a custom cache adapter.
const CacheableRequest = require('cacheable-request');
const http = require('http');
const cacheAdapter = require('./some-cache-adapter');
const cacheableRequest = new CacheableRequest(http.request, cacheAdapter);
const req = cacheableRequest('http://example.com', response => {
// Use the response here
});
req.on('request', request => request.end());
Custom cache adapters
This feature allows the use of custom cache adapters to store and retrieve cached responses. The code sample demonstrates how to use a custom cache adapter with the cacheable-request package.
const CacheableRequest = require('cacheable-request');
const http = require('http');
const myCacheAdapter = {
get: (key) => { /* custom get implementation */ },
set: (key, value) => { /* custom set implementation */ }
};
const cacheableRequest = new CacheableRequest(http.request, myCacheAdapter);
HTTP and HTTPS support
The package supports both HTTP and HTTPS protocols. The code sample illustrates how to create a cacheable HTTPS request.
const CacheableRequest = require('cacheable-request');
const https = require('https');
const cacheAdapter = require('./some-cache-adapter');
const cacheableRequest = new CacheableRequest(https.request, cacheAdapter);
const req = cacheableRequest('https://secure.example.com', response => {
// Use the response here
});
req.on('request', request => request.end());
Other packages similar to cacheable-request
axios-cache-adapter
axios-cache-adapter is a cache adapter for the Axios HTTP client. It allows you to easily add caching capabilities to your Axios requests. Unlike cacheable-request, which is a standalone request wrapper, axios-cache-adapter is specifically designed to work with Axios and provides more advanced features like cache invalidation and per-request cache configuration.
node-fetch-cache
node-fetch-cache is a caching layer for node-fetch, a lightweight module that brings window.fetch to Node.js. It provides similar caching functionality to cacheable-request but is tailored for use with node-fetch. It also offers features like cache size limits and custom cache keys.
got
got is a powerful HTTP request library for Node.js that includes caching as one of its features. It is more feature-rich than cacheable-request, offering a wide range of HTTP capabilities such as retries, streams, and more. got's caching is built-in and does not require a separate adapter, making it a more integrated solution.
cacheable-request
Wrap native HTTP requests with RFC compliant cache support
RFC 7234 compliant HTTP caching for native Node.js HTTP/HTTPS requests. Caching works out of the box in memory or is easily pluggable with a wide range of storage adapters.
Note: This is a low level wrapper around the core HTTP modules, it's not a high level request library.
Features
- Only stores cacheable responses as defined by RFC 7234
- Fresh cache entries are served directly from cache
- Stale cache entries are revalidated with
If-None-Match
/If-Modified-Since
headers - 304 responses from revalidation requests use cached body
- Updates
Age
header on cached responses - Can completely bypass cache on a per request basis
- Official support for Redis, MongoDB, SQLite, PostgreSQL and MySQL storage adapters
- Easily plug in your own or third-party storage adapters
- Adds cache support to any existing HTTP code with minimal changes
- Uses http-cache-semantics internally for HTTP RFC 7234 compliance
Install
npm install --save cacheable-request
Usage
const http = require('http');
const CacheableRequest = require('cacheable-request');
const req = http.request('http://example.com', cb);
req.end();
const cacheableRequest = new CacheableRequest(http.request);
const cacheReq = cacheableRequest('http://example.com', cb);
cacheReq.on('request', req => req.end());
const cacheableRequest = new CacheableRequest(https.request);
const cacheableRequest = new CacheableRequest(electron.net);
Storage Adapters
cacheable-request
uses Keyv to support a wide range of storage adapters.
For example, to use Redis as a cache backend, you just need to install the official Redis Keyv storage adapter:
npm install --save @keyv/redis
And then you can pass CacheableRequest
your connection string:
const cacheableRequest = new CacheableRequest(http.request, 'redis://user:pass@localhost:6379');
View all official Keyv storage adapters.
Keyv also supports anything that follows the Map API so it's easy to write your own storage adapter or use a third-party solution.
e.g The following are all valid storage adapters
const storageAdapter = new Map();
const storageAdapter = require('./my-storage-adapter');
const QuickLRU = require('quick-lru');
const storageAdapter = new QuickLRU({ maxSize: 1000 });
const cacheableRequest = new CacheableRequest(http.request, storageAdapter);
View the Keyv docs for more information on how to use storage adapters.
API
new cacheableRequest(request, [storageAdapter])
Returns the provided request function wrapped with cache support.
request
Type: function
Request function to wrap with cache support. Should be http.request
or a similar API compatible request function.
storageAdapter
Type: Keyv storage adapter
Default: new Map()
A Keyv storage adapter instance, or connection string if using with an official Keyv storage adapter.
Instance
cacheableRequest(opts, [cb])
Returns an event emitter.
opts
Type: object
, string
Any of the default request functions options plus:
opts.cache
Type: boolean
Default: true
If the cache should be used. Setting this to false will completely bypass the cache for the current request.
opts.strictTtl
Type: boolean
Default: false
If set to false
, after a cached resource's TTL expires it is kept in the cache and will be revalidated on the next request with If-None-Match
/If-Modified-Since
headers.
If set to true
once a cached resource has expired it is deleted and will have to be re-requested.
cb
Type: function
The callback function which will receive the response as an argument.
The response can be either a Node.js HTTP response stream or a responselike object. The response will also have a fromCache
property set with a boolean value.
.on('request', request)
request
event to get the request object of the request.
Note: This event will only fire if an HTTP request is actually made, not when a response is retrieved from cache. However, you should always handle the request
event to end the request and handle any potential request errors.
.on('response', response)
response
event to get the response object from the HTTP request or cache.
.on('error', error)
error
event emitted in case of an error with the cache.
Note: You should still handle request errors in the request
event. e.g:
cacheableRequest('example.com', cb)
.on('error', handleCacheError)
.on('request', req => {
req.on('error', handleRequestError);
req.end();
});
License
MIT © Luke Childs