
Security News
Browserslist-rs Gets Major Refactor, Cutting Binary Size by Over 1MB
Browserslist-rs now uses static data to reduce binary size by over 1MB, improving memory use and performance for Rust-based frontend tools.
express-cache-middleware
Advanced tools
An Express middleware designed to intercept responses and cache them.
An Express middleware designed to intercept responses and cache them.
To use this middleware, first instantiate it. The first argument to the constructor must be a cache-manager .caching()
instance, initialized with any backend you choose. The second argument is an optional object of options.
const express = require('express')
const ExpressCache = require('express-cache-middleware')
const cacheManager = require('cache-manager')
const cacheMiddleware = new ExpressCache(
cacheManager.caching({
store: 'memory', max: 10000, ttl: 3600
})
)
Then, attach it to your Express app instance or Router. Any routes attached to the app or Router after this will be intercepted and cached.
// Layer the caching in front of the other routes
cacheMiddleware.attach(app)
// Attach the routes to be cached
app.all('*', (req, res) => {
// ... do something expensive like a fetch() here ...
res.send('response')
})
app.listen()
Please see the options for important information about handling incoming and outgoing data.
A function to get the cache key from the request. Provided with one argument: the request object from Express.
By default, this is a function that returns the request URL.
You may want to customize this function if you anticipate that there are things in your URL that you don't want in your cache key. For example, you can remove irrelevant query parameters or subdirectories by parsing the URL here and returning the cache key.
Because this middleware is backend-agnostic, it makes no assumptions about what you want to do with cached data. By default, it just passes the streamed data out as the response, and what this data actually is will depend on your chosen cache-manager backend since no metadata side-channel is available.
This usually ends up as a response with Content-Type: application/octet-stream
, which is not often what people want. To fix this, hydrate
is run before the content is returned.
hydrate
is called with four arguments:
req
, the Express request objectres
, the Express response objectdata
. the data returned from cachecb
, an optional callback functionSet any headers or perform any transformations on the returned data. Then, call the callback with (err, result)
or return a Promise.
Note: hydrate
is not called for the first response, where your route returns its original content-- only for cache hits.
Example for handling image responses:
const fileType = require('file-type')
const cacheMiddleware = new ExpressCache(
cacheManager.caching({
store: 'memory', max: 10000, ttl: 3600
}), {
hydrate: (req, res, data, cb) => {
// Use file-type library to guess MIME type from Buffer.
const guess = fileType(data.slice(0, 4101))
if( guess ) {
res.contentType(guess.mime)
}
cb(null, data)
}
}
)
// or with Promises:
const hydrateWithPromise = (res, data) => {
return Promise.resolve(data)
}
// or with async/await:
const hydrateAsync = async (res, data) => {
return data
}
Example for handling mixed content responses:
const hydrateManyThings = async (req, res, data) => {
// Parse as JSON first
try {
JSON.parse(data)
res.contentType('application/json')
return data
} catch ( err ) {}
const guess = fileType(data.slice(0, 4101))
if( guess ) {
res.contentType(guess.mime)
}
return data
}
1.0.1
Removes mung's json as it was setting cache multiple times. send
will catch json as well.
Alters Promise detection from hydrate
functions-- async
was not being detected as Promises.
Updated dev dependencies, added babel-jest-assertions to ensure the tests are running properly, and minor linting
1.0.0 First full release, using fork of express-mung
FAQs
An Express middleware designed to intercept responses and cache them.
The npm package express-cache-middleware receives a total of 159 weekly downloads. As such, express-cache-middleware popularity was classified as not popular.
We found that express-cache-middleware demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Browserslist-rs now uses static data to reduce binary size by over 1MB, improving memory use and performance for Rust-based frontend tools.
Research
Security News
Eight new malicious Firefox extensions impersonate games, steal OAuth tokens, hijack sessions, and exploit browser permissions to spy on users.
Security News
The official Go SDK for the Model Context Protocol is in development, with a stable, production-ready release expected by August 2025.