
Security News
Risky Biz Podcast: Making Reachability Analysis Work in Real-World Codebases
This episode explores the hard problem of reachability analysis, from static analysis limits to handling dynamic languages and massive dependency trees.
prerender-node
Advanced tools
express middleware for serving prerendered javascript-rendered pages for SEO
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.
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.
GET
request to the prerender service for the page's prerendered HTMLWhitelist 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 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']));
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();
}));
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 };
}
}));
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'));
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'));
Option to forward headers from request to prerender.
app.use(require('prerender-node').set('forwardHeaders', true));
Option to add options to the request sent to the prerender server.
app.use(require('prerender-node').set('prerenderServerRequestOptions', {}));
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);
}
});
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>'));
This package uses npm Trusted Publisher with GitHub Actions for secure, automated publishing.
Automatic Publishing: The workflow automatically publishes to npm when:
main
or master
branchpackage.json
is higher than the current published versionManual Publishing: Trigger via GitHub Actions "Run workflow" button
package.json
version with npm registry--provenance
flag for supply chain securityTo publish a new version:
package.json
using npm version [major|minor|patch]
This repository uses Dependabot to automatically create pull requests for:
Dependabot runs weekly and creates PRs with conventional commit messages:
deps: update package-name from x.x.x to y.y.y
- Main dependenciesdeps(express3-test): update package-name
- Express 3 test app dependenciesdeps(express4-test): update package-name
- Express 4 test app dependenciesci: update actions/checkout from v4 to v5
- GitHub Actions updatesThis middleware is tested against Express 3 and Express 4 to ensure compatibility:
test/support/express3/
- Express 3.x integration teststest/support/express4/
- Express 4.x integration testsBoth test apps have separate package.json
files with their respective Express versions to verify the middleware works correctly across different Express major versions.
For security vulnerabilities, please see our Security Policy. Do not report security issues through public GitHub issues.
We love any contributions! Feel free to create issues, pull requests, or middleware for other languages/frameworks!
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.
FAQs
express middleware for serving prerendered javascript-rendered pages for SEO
The npm package prerender-node receives a total of 19,609 weekly downloads. As such, prerender-node popularity was classified as popular.
We found that prerender-node demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 7 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
This episode explores the hard problem of reachability analysis, from static analysis limits to handling dynamic languages and massive dependency trees.
Security News
/Research
Malicious Nx npm versions stole secrets and wallet info using AI CLI tools; Socket’s AI scanner detected the supply chain attack and flagged the malware.
Security News
CISA’s 2025 draft SBOM guidance adds new fields like hashes, licenses, and tool metadata to make software inventories more actionable.