Bright Labs

How to cache prerender-node responses in Redis without caching 500 errors

Your Express app runs prerender-node, and you want Redis to cache the rendered HTML without freezing temporary 500 or 504 errors for crawlers. Add a beforeRender hook that reads body and status with client.hmget, and an afterRender hook that only writes to Redis when prerender_res.statusCode matches 200, 302, or 404.

Why a plain Redis string cache breaks status codes

By default, prerender-node intercepts crawler requests on your Node.js website. It calls the external Prerender Service for static HTML and returns that HTML to the crawler. The middleware is ready to use with Redis or Memcached to return prerendered pages in milliseconds. You add a beforeRender function and an afterRender function for caching.

The catch with the basic client.get and client.set example is easy to miss. That setup calls client.set with prerender_res.body only and does not store a status code. If you return a string from beforeRender, the middleware serves it to the crawler with status 200 instead of calling the prerender service, so you cannot pass back status codes like 302 or 404.

Writing to Redis unconditionally in afterRender brings a second issue. The middleware calls afterRender after the prerender service returns HTML, and the basic client.set example writes prerender_res.body straight out. Without checking prerender_res.statusCode, you can store responses that might be temporary like 500 or 504.

Cache body and status together in Redis

Install the Redis client in your Node.js project before wiring up the middleware hooks.

Install Redis client (from prerender-node README)
$ npm install redis

Use client.hmget and client.hmset keyed by req.url to store body and status together. Restrict writes in afterRender to 200, 302, and 404 with cacheableStatusCodes.

Redis caching with status filtering (from prerender-node README)
var redis = require("redis"),
client = redis.createClient(),
cacheableStatusCodes = {200: true, 302: true, 404: true};

prerender.set('beforeRender', function(req, done) {
  client.hmget(req.url, 'body', 'status', function (err, fields) {
    if (err) return done(err);
    done(err, {body: fields[0], status: fields[1]});
  });
}).set('afterRender', function(err, req, prerender_res) {
  // Don't cache responses that might be temporary like 500 or 504.
  if (cacheableStatusCodes[prerender_res.statusCode]) {
    client.hmset(req.url, 'body', prerender_res.body, 'status', prerender_res.statusCode);
  }
});

You can also use afterRender to handle Prerender errors or HTML that is missing expected content. Return an object containing cancelRender: true from afterRender to cancel the prerendered response and skip to the next middleware. That lets you implement your own fallback behaviour when Prerender returns errors or if the HTML is missing expected content.

Cancel a failed render in afterRender (from prerender-node README)
app.use(require('prerender-node').set('afterRender', function(err, req, prerender_res) {
	if (err) {
		return { cancelRender: true };
	}
}));

Keep unwanted routes out of your cache

Before prerender-node makes a GET request to the prerender service, it checks the incoming request.

Both whitelist and blacklist options compare using regex, so be specific when possible. Filtering out unwanted paths upfront keeps them from hitting the prerender service or your cache.

Test cached pages and status codes locally

Test the setup directly in a browser before deploying your caching hooks, using Chrome DevTools (the web developer tools built directly into the Google Chrome browser) to override the user agent. If you're testing locally, you'll need to run the prerender server locally so that it has access to your server.

How local caching fits with an external prerender service

When beforeRender serves a cached object, prerender-node skips the request to the external prerender service. That cuts repeat calls to the prerender service and preserves your upstream render allowance for pages that are not cached yet.

At Bright Labs, we run RenderSwap as a hosted prerender service built for unmodified prerender-node middleware. If you point prerender-node at the default prerender.io service, your middleware and Redis hooks stay as they are: when a search engine, AI crawler, or social crawler requests a page, Prerender loads it in a real browser, runs the JavaScript, and returns the complete HTML while visitors still get your normal site. To point prerender-node at a different service endpoint, set the PRERENDER_SERVICE_URL environment variable (or pass prerenderServiceUrl in options during initialization) and configure prerenderToken.

Keeping the status check inside afterRender ensures your Redis layer stays resilient regardless of which prerender endpoint answers. Because beforeRender reads stored {body, status} hashes from Redis before making a GET request to the prerender service, repeat crawler requests for cached 200, 302, and 404 pages do not trigger new upstream renders. When the prerender service returns a temporary 500 or 504 response, cacheableStatusCodes skips client.hmset so bad responses are never persisted, and returning cancelRender: true lets your Express app fall back to the next middleware.

Sources

Questions

Can I use Memcached instead of Redis with prerender-node?

Yes. The prerender-node middleware is ready to be used with Redis or Memcached to return prerendered pages in milliseconds, and you can add beforeRender and afterRender functions for caching.

Why does returning a string from beforeRender cause wrong HTTP status codes?

When beforeRender returns a plain string, prerender-node serves it with status 200 instead of calling the prerender service. Returning an object with status and body lets the middleware serve status codes like 302 and 404, defaulting to 200 and an empty string if omitted.

How do I handle errors or missing HTML in afterRender without caching them?

Check cacheableStatusCodes[prerender_res.statusCode] before calling client.hmset so 500 or 504 responses are not written to Redis. When Prerender returns an error or HTML missing expected content, you can also return { cancelRender: true } from afterRender to cancel the prerendered response and skip to the next Express middleware.

Related