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.
$ 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.
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);
}
});
- In beforeRender, returning an object tells prerender-node to look for status and body properties and serve those instead of making a request to the prerender service.
- If either property is omitted, the middleware defaults status to 200 and body to an empty string.
- Inside client.hmget, if (err) return done(err); returns the error early before calling done(err, {body: fields[0], status: fields[1]}).
- In afterRender, checking cacheableStatusCodes[prerender_res.statusCode] skips client.hmset for responses that might be temporary like 500 or 504.
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.
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.
- It checks if the request is from a crawler by matching the user agent string against a default list of crawler user agents.
- It checks to make sure the request is not asking for a resource such as js or css.
- If you supply a whitelist with whitelisted, only URLs containing a whitelist path will be prerendered.
- If you supply a blacklist with blacklisted, all URLs will be prerendered except ones containing a blacklist path.
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.
- Set the User Agent of your browser to Googlebot's user agent and visit your URL directly.
- Open View Source on that URL and check that you see the static HTML version of the page with the tags removed.</li> <li>If you still see <script> tags, the middleware isn't set up properly yet.</li> <li>Check a URL that returns 404 on the first visit and again after it caches to confirm it keeps status 404.</li> </ul> <h2> <a name="how-local-caching-fits-with-an-external-prerender-service" href="#how-local-caching-fits-with-an-external-prerender-service" class="anchor"> </a> How local caching fits with an external prerender service </h2> <p>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.</p> <p>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.</p> <p>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.</p> <h3> <a name="sources" href="#sources" class="anchor"> </a> Sources </h3> <ul> <li>{'text': 'prerender-node README: middleware setup, hooks, and Redis caching', 'url': '<a href="https://raw.githubusercontent.com/prerender/prerender-node/master/README.md'">https://raw.githubusercontent.com/prerender/prerender-node/master/README.md'</a>}</li> <li>{'text': 'Chrome DevTools documentation', 'url': '<a href="https://developer.chrome.com/docs/devtools/'">https://developer.chrome.com/docs/devtools/'</a>}</li> <li>{'text': 'Prerender.io default prerender service', 'url': '<a href="https://prerender.io/'">https://prerender.io/'</a>}</li> </ul> <h2> <a name="frequently-asked-questions" href="#frequently-asked-questions" class="anchor"> </a> Frequently Asked Questions </h2> <p><strong>Can I use Memcached instead of Redis with prerender-node?</strong></p> <p>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.</p> <p><strong>Why does returning a string from beforeRender cause wrong HTTP status codes?</strong></p> <p>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.</p> <p><strong>How do I handle errors or missing HTML in afterRender without caching them?</strong></p> <p>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.</p> <hr> <p><em>Originally published on <a href="https://brightlabs.app/blog/cache-prerender-node-redis-status-codes/">Bright Labs</a>.</em></p>
Top comments (0)