Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

prerender-node

prerender111.4kMIT3.8.0

express middleware for serving prerendered javascript-rendered pages for SEO

angular, backbone, emberjs, seo

readme

Prerender Node Build Status NPM version

Google, Facebook, Twitter, and Bing are constantly trying to view your website... but Google is the only crawler that executes a meaningful amount of JavaScript and Google even admits that they can execute JavaScript weeks after actually crawling. Prerender allows you to serve the full HTML of your website back to Google and other crawlers so that they don't have to execute any JavaScript. Google recommends using Prerender.io to prevent indexation issues on sites with large amounts of JavaScript.

Prerender is perfect for Angular SEO, React SEO, Vue SEO, and any other JavaScript framework.

This middleware intercepts requests to your Node.js website from crawlers, and then makes a call to the (external) Prerender Service to get the static HTML instead of the JavaScript for that page. That HTML is then returned to the crawler.

via npm:

$ npm install prerender-node --save

And when you set up your express app, add:

app.use(require('prerender-node'));

or if you have an account on prerender.io and want to use your token:

app.use(require('prerender-node').set('prerenderToken', 'YOUR_TOKEN'));

Note If you're testing locally, you'll need to run the prerender server locally so that it has access to your server.

This middleware is tested with Express3 and Express4, but has no explicit dependency on either.

Testing

The best way to test the prerendered page is to set the User Agent of your browser to Googlebot's user agent and visit your URL directly. If you View Source on that URL, you should see the static HTML version of the page with the <script> tags removed from the page. If you still see <script> tags then that means the middleware isn't set up properly yet.

Note If you're testing locally, you'll need to run the prerender server locally so that it has access to your server.

How it works

  1. The middleware checks to make sure we should show a prerendered page
    1. The middleware checks if the request is from a crawler by checking the user agent string against a default list of crawler user agents
    2. The middleware checks to make sure we aren't requesting a resource (js, css, etc...)
    3. (optional) The middleware checks to make sure the url is in the whitelist
    4. (optional) The middleware checks to make sure the url isn't in the blacklist
  2. The middleware makes a GET request to the prerender service for the page's prerendered HTML
  3. Return that HTML to the crawler from your server

Customization

Whitelist

Whitelist a single url path or multiple url paths. Compares using regex, so be specific when possible. If a whitelist is supplied, only urls containing a whitelist path will be prerendered.

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

Blacklist

Blacklist a single url path or multiple url paths. Compares using regex, so be specific when possible. If a blacklist is supplied, all url's will be prerendered except ones containing a blacklist path.

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

beforeRender

This method is intended to be used for caching, but could be used to save analytics or anything else you need to do for each crawler request. If you return a string from beforeRender, the middleware will serve that to the crawler (with status 200) instead of making a request to the prerender service. If you return an object the middleware will look for a status and body property (defaulting to 200 and "" respectively) and serve those instead.

app.use(require('prerender-node').set('beforeRender', function(req, done) {
    // do whatever you need to do
    done();
}));

afterRender

This method is intended to be used for caching, but could be used to save analytics or anything else you need to do for each crawler request. This method is called after the prerender service returns HTML.

app.use(require('prerender-node').set('afterRender', function(err, req, prerender_res) {
    // do whatever you need to do
}));

You can also use afterRender to cancel the prerendered response and skip to the next middleware. For example, you may want to implement your own fallback behaviour for when Prerender returns errors or if the HTML is missing expected content. To cancel the render, return an object containing cancelRender: true from afterRender:

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

protocol

Option to hard-set the protocol. Useful for sites that are available on both http and https.

app.use(require('prerender-node').set('protocol', 'https'));

host

Option to hard-set the host. Useful for sites that are behind a load balancer or internal reverse proxy. For example, your internal URL looks like http://internal-host.com/ and you might want it to instead send a request to Prerender.io with your real domain in place of internal-host.com.

app.use(require('prerender-node').set('host', 'example.com'));

forwardHeaders

Option to forward headers from request to prerender.

app.use(require('prerender-node').set('forwardHeaders', true));

prerenderServerRequestOptions

Option to add options to the request sent to the prerender server.

app.use(require('prerender-node').set('prerenderServerRequestOptions', {}));

Caching

This express middleware is ready to be used with redis or memcached to return prerendered pages in milliseconds.

When setting up the middleware, you can add a beforeRender function and afterRender function for caching.

Here's an example testing a local redis cache:

$ npm install redis
var redis = require("redis"),
    client = redis.createClient();

prerender.set('beforeRender', function(req, done) {
    client.get(req.url, done);
}).set('afterRender', function(err, req, prerender_res) {
    client.set(req.url, prerender_res.body)
});

or

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);
  }
});

Using your own prerender service

We host a Prerender server at prerender.io so that you can work on more important things, but if you've deployed the prerender service on your own... set the PRERENDER_SERVICE_URL environment variable so that this middleware points there instead. Otherwise, it will default to the service already deployed by prerender.io.

$ export PRERENDER_SERVICE_URL=<new url>

Or on heroku:

$ heroku config:set PRERENDER_SERVICE_URL=<new url>

As an alternative, you can pass prerenderServiceUrl in the options object during initialization of the middleware

app.use(require('prerender-node').set('prerenderServiceUrl', '<new url>'));

Contributing

We love any contributions! Feel free to create issues, pull requests, or middleware for other languages/frameworks!

License

The MIT License (MIT)

Copyright (c) 2013 Todd Hooper <todd@prerender.io>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

changelog

3.8.0 (2024-02-20)

Added:

  • Add X-Prerender-Int-Type to recognized user integration type

3.7.0 (2023-05-22)

Added:

  • Add Google-InspectionTool to the recognized user agents

3.6.0 (2023-03-15)

Added:

  • .webp, .woff2 extensions to the list of extensions that are not prerendered
  • Add AhrefsBot to the recognized user agents
  • Add AhrefsSiteAudit to the recognized user agents
  • Add Iframely to the recognized user agents
  • Add screaming frog to the recognized user agents

3.5.0 ()

Added:

  • cancelRender flag in afterRender callback

3.4.2 (2022-03-21)

Fixed:

3.4.1 (2022-01-17)

Added:

  • Add seznam.cz bot to the recognized user agents

3.4.0 (2021-11-09)

Changed:

  • Replace requests lib with the native nodejs http and https modules

3.3.0 (2021-11-04)

Changed:

  • Add telegram bot to the recognized user agents

3.2.5 (2019-07-30)

Changed:

  • Updated lodash and mocha to resolve security vulnerability warning

3.2.4 (2019-04-08)

Changed:

  • Updated devDependencies to latest versions for running tests

3.2.3 (2019-04-08)

Changed:

  • Modified request dependency from ^2.83.0 to ^2.88.0 and added package-lock.json file

3.2.2 (2019-03-27)

Added:

  • Added Chrome-Lighthouse user agent so Google page speed insight tool will show prerendered pages

3.2.1 (2018-08-29)

Added:

  • Looks like I accidentally added yahoo instead of yandex in the last commit. Fixing that by adding yandex now

3.2.0 (2018-07-18)

Added:

  • Added Googlebot, Bingbot, and Yandex to user agent check for new Dynamic Rendering and phase-out of escaped fragment URLs
  • Added check for x-prerender header for mobile adaptive feature for websites that serve different HTML to mobile vs desktop crawlers

3.1.1 (2018-03-01)

Changed:

  • Fixing test that checked for the old endpoint

3.1.0 (2018-03-01)

Changed:

  • Point to https endpoint for prerender service instead of http

3.0.0 (2018-03-01)

Removed:

  • Node 0.10 support
  • Node 0.12 support

Changed:

  • Bumped request dependency version

Added:

  • Node 8 to travis.yml

2.8.0 (2018-02-21)

Added:

  • Added Bitrix24 and Xing user agents.

2.7.4 (2017-09-22)

Changed:

  • Fixing wrong version of request. :)

2.7.3 (2017-09-22)

Changed:

  • Pinned node request module to 2.81.1 since they bumped a dependency version that required a newer version of node. prerender-node still supports older versions of node so pinned an earlier version of request until we officially dont support older versions of node.

2.7.2 (2017-07-05)

New features:

  • Added pinterestbot to user agents being checked.

2.7.1 (2017-04-13)

New features:

  • Added Qwantify to user agents being checked.

Changed

  • Added host parameter documentation to README

2.7.0 (2016-12-20)

New features:

  • Adds an option to be able to pass options to the request sent to the prerender.

2.6.0 (2016-12-13)

New features:

  • Check for Google Page Speed user agent in order to send prerendered pages when URLs are tested through their tool

Changed

  • extensionsToIgnore check is now case insensitive

2.5.0 (2016-10-26)

Changed

  • When creating the URL to send to Prerender, check to see if x-forwarded-host is set and use that before using the host header.

2.4.0 (2016-8-30)

New features:

  • Check for Skype user agent in order to send prerendered pages when URLs are shared through Skype chat
  • Check for nuzzel user agent
  • Check for discordbot user agent

Changed

  • Don't send the host header if forwardHeaders is enabled to prevent issues with servers that take the Host header and apply it to the URL

2.3.0 (2016-6-1)

New features:

  • Check for Tumblr user agent in order to send prerendered pages when URLs are shared through Tumblr
  • Check for bitlybot user agent in order to send prerendered pages when URLs are shared through Bitly

2.2.2 (2016-5-8)

Bugfixes:

  • fix compatibility with Node.js v6.0.0

2.2.1 (2016-3-21)

Bugfixes:

  • Check for more specific pinterest crawler user agent since their iOS app changes the browser user agent to include "pinterest"
  • Added svg to list of extensions to check

2.2.0 (2015-12-29)

New features:

  • Check for Whatsapp user agent in order to send prerendered pages when URLs are shared through Whatsapp

2.1.0 (2015-09-17)

New features:

  • Check for Applebot user agent in order to send prerendered pages to apple for Siri on iOS9

2.0.2 (2015-07-24)

Bugfixes:

  • Make sure we pass through the error, request, and Prerender response to afterRender

    Fixed an issue where the original request and Prerender response wasn't getting passed to afterRender after recent change to pass err through. Now works correctly: afterRender(err, req, prerenderResponse)

2.0.1 (2015-07-20)

Bugfixes:

  • Send HTTPS URLs through correctly.

    Fixed an issue where http was always added to the URLs sent to Prerender even if the URL was https.

2.0.0 (2015-07-15)

Bugfixes:

  • Stop swallowing errors if the prerender service fails.

    Before: If the prerender service errors out (e.g., not available and the request times out), the error is swallowed and next called with no args.

    After: error is passed through to next, and prerender.afterRenderFn is handed err as the first arg. Makes it much easier to know if you're misconfiguring something or forgot to start the prerender server locally when testing.