Performance: Cache middleware pattern
This pattern affects server response time and reduces client wait by serving cached content quickly.
const cache = {};
app.get('/data', (req, res, next) => {
if (cache.data) {
return res.json(cache.data);
}
next();
}, (req, res) => {
const data = fetchFromDatabase();
cache.data = data;
res.json(data);
});app.get('/data', (req, res) => {
const data = fetchFromDatabase();
res.json(data);
});| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No cache middleware | N/A (server-side) | N/A | High due to slow response delaying LCP | [X] Bad |
| Cache middleware serving cached data | N/A | N/A | Low, fast response improves LCP | [OK] Good |
cacheData is { message: 'Hello' }?
function cache(req, res, next) {
if (cacheData) {
res.json(cacheData);
} else {
next();
}
}
app.get('/greet', cache, (req, res) => {
res.json({ message: 'Hi there!' });
});let cacheData;
function cache(req, res, next) {
if (cacheData) {
res.send(cacheData);
}
next();
}Pass the test and this pattern moves unknown