Cache rendered HTML in Node.js
Store the HTML of an expensive page in memory with a short expiry and serve it directly on repeat requests, in an Express 5 route on Node.js 24.
Rendering a page that reads a database and a template engine on every request is often wasted work if the content changes once a minute. A tiny cache serves the finished HTML.
import express from 'express';
const app = express();
const pages = new Map();
async function renderHome() {
console.log('rendering');
return `<h1>Home</h1><p>Rendered at ${new Date().toISOString()}</p>`;
}
app.get('/', async (req, res) => {
const hit = pages.get('/');
if (hit && hit.expires > Date.now()) {
return res.set('x-cache', 'hit').type('html').send(hit.html);
}
const html = await renderHome();
pages.set('/', { html, expires: Date.now() + 30_000 });
res.set('x-cache', 'miss').type('html').send(html);
});
app.listen(3000);rendering
GET / -> x-cache: miss
GET / -> x-cache: hitThe first request renders and stores the result for 30 seconds, and the next ones return it directly. The x-cache header makes the behaviour easy to check with curl -i.
Only cache pages that are the same for every visitor. A page with a user's name or a cart must not be shared, so key by what changes the output or skip the cache. A Map lives in one process and has no size limit, so for several servers or many pages use Redis or a CDN with Cache-Control. See Express response methods.