Skip to content
jshacks.dev
Performance

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.

1 min read
Summarize in AI

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.

server.jsJavaScript
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);
Text
rendering
GET / -> x-cache: miss
GET / -> x-cache: hit

The 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.

Also inNode.js
Share

More snippets

Testing

Group tests with describe in node test

Group related tests with describe and it from node:test, nest suites, and run setup with beforeEach, all without installing a framework.

1 min read
Performance

Time code with performance.now

Time a block of code with performance.now, which returns a monotonic high-resolution timestamp in milliseconds, and avoid the clock jumps Date.now can have.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.