Bright Labs

How to limit which URLs prerender-node renders

Limit which URLs prerender-node sends to the external Prerender Service by chaining .whitelisted(patterns) to render only matching paths, .blacklisted(patterns) to skip matching paths or referrers, and beforeRender/afterRender hooks to serve cached HTML from Redis or Memcached while storing 200, 302, and 404 status codes instead of temporary 500 or 504 errors.

Check what prerender-node already skips

Because prerender-node is an Express middleware for serving prerendered JavaScript-rendered pages for SEO, it sits in your Express request pipeline and decides on each incoming request whether to serve prerendered HTML or hand control back to your application. Before you write custom rules, check what prerender-node already skips on its own inside shouldShowPrerenderedPage. Every incoming request runs through a fixed set of checks, and if any check returns false, the middleware calls next() immediately without touching your cache or calling the external service:

You don't need extra rules for anything already handled by those checks. If you need to recognize an additional crawler, call prerender.addUserAgents with a string or array instead of rewriting user-agent matching yourself.

Restrict routes with whitelisted and blacklisted

If only part of your site needs prerendering, supply a whitelist. When a whitelist is supplied, only URLs containing a whitelist path get prerendered. Both whitelisted and blacklisted accept either a single pattern string or an array of pattern strings.

Whitelisting paths in prerender-node
app.use(require('prerender-node').whitelisted(['/search', '/users/.*/profile']));

If you want the opposite behavior—rendering most of your site while excluding admin dashboards, checkout pages, or internal endpoints—use blacklisted instead. When a blacklist is supplied, all URLs get prerendered except ones containing a blacklist path.

Blacklisting paths in prerender-node
app.use(require('prerender-node').blacklisted(['/search', '/users/.*/profile']));

This one is easy to miss: both options compare using regex, so be specific when possible. Whitelist patterns test new RegExp(whitelisted) against req.url, meaning a pattern like '/search' matches any URL containing /search anywhere in the path or query string. Anchor a prefix with a caret like '^/search' when you only want URLs starting with that path.

Here's the second catch for blacklisted routes: blacklist patterns test both req.url and req.headers['referer']. If req.headers['referer'] matches a blacklist pattern, the request is treated as blacklisted too. That means a bot request arriving with a blacklisted referer header gets skipped even when the target URL itself isn't blacklisted.

Cache rendered HTML in beforeRender and afterRender

Route rules filter paths, while local caching saves repeat calls. Because shouldShowPrerenderedPage runs before beforeRender, skipped routes and ignored extensions never trigger a cache lookup. For routes that do qualify, prerender-node can be used with Redis or Memcached to return prerendered pages in milliseconds instead of waiting on a fresh external render.

Check your cache in beforeRender first. If you return a string from beforeRender, prerender-node serves it to the crawler with status 200 without calling the prerender service. If you return an object, it looks for status and body properties (defaulting to 200 and "") and serves those instead. On a cache miss, prerender-node calls the external prerender service.

Caching 200, 302, and 404 responses with Redis
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);
  }
});

Checking cacheableStatusCodes in afterRender matters. The example caches 200, 302, and 404 responses as Redis hash fields so both the HTML body and status code are stored, while avoiding temporary responses like 500 or 504. If you only store a plain string via client.set and client.get, every cached response is served with status 200—even if the page originally returned a 404.

You can also handle errors in afterRender when the prerender service fails or returns unusable output. Returning cancelRender: true from afterRender cancels the prerendered response and skips to the next middleware so your Express app can fall back cleanly.

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

Test your setup and service URL

After updating your rules, set your browser's User-Agent to Googlebot's user agent and visit your URL directly. Run View Source on an allowed URL: you should see static HTML with the <script> tags removed. If you still see <script> tags, the middleware isn't set up properly yet. When testing locally, run the prerender server locally so it has access to your server.

If you want prerender-node to use a different prerender service instead, set the PRERENDER_SERVICE_URL environment variable or pass prerenderServiceUrl in the options object during middleware initialization so the middleware points there.

Sources

Questions

How do whitelisted and blacklisted match URLs in prerender-node?

Both whitelisted and blacklisted compare using regex. Whitelist patterns test new RegExp(whitelisted) against req.url, while blacklist patterns test both req.url and req.headers['referer'].

Which HTTP status codes should I cache in afterRender?

The prerender-node Redis caching example caches 200, 302, and 404 responses via cacheableStatusCodes and avoids caching temporary responses like 500 or 504.

How do I test whether a page is being prerendered?

Set your browser's User-Agent to Googlebot's user agent, visit the URL directly, and check View Source. You should see static HTML with the <script> tags removed; if you still see <script> tags, the middleware isn't set up properly yet.

Related