veliovgroup / spiderable-middleware

πŸ€– Prerendering for JavaScript powered websites. Great solution for PWAs (Progressive Web Apps), SPAs (Single Page Applications), and other websites based on top of front-end JavaScript frameworks
https://www.npmjs.com/package/spiderable-middleware
BSD 3-Clause "New" or "Revised" License
38 stars 4 forks source link
crawler meteor meteor-package middleware nodejs npm npm-package seo seo-optimization spiderable

Spiderable middleware

Google, Facebook, Twitter, Yahoo, and Bing and all other crawlers and search engines are constantly trying to view your website. If your website is built on top of the JavaScript framework like, but not limited to - Angular, Backbone, Ember, Meteor, React, MEAN most of the front-end solutions returns basic HTML-markup and script-tags to crawlers, but not content of your page. The mission of spiderable-middleware and ostr.io are to boost your SEO experience without a headache.

Why Pre-render?

ToC

About Package

This package acts as middleware and intercepts requests to your Node.js application from web crawlers. All requests proxy passed to the Prerendering Service, which returns static, rendered HTML.

This is SERVER only package. For NPM make sure you're importing library only in Node.js. For Meteor.js please make sure library imported and executed only on SERVER.

We made this package with developers in mind. It's well written in a very simple way, hackable, and easily tunable to meet your needs, can be used to turn dynamic pages into rendered, cached, and lightweight static pages, just set botsUA to ['.*']. This is the best option to offload servers unless a website gets updated more than once in 4 hours.

This middleware was tested and works like a charm with:

All other frameworks which follow Node's middleware convention - will work too.

This package was originally developed for ostr.io service. But it's not limited to, and can proxy-pass requests to any other rendering-endpoint.

Installation

Install spiderable-middleware package from NPM for Node.js usage, alternatively see Meteor.js specific setup documentation

npm install spiderable-middleware --save

Usage

Get ready in a few lines of code

Basic usage

See all examples.

First, add fragment meta-tag to your HTML template:

<html>
  <head>
    <meta name="fragment" content="!">
    <!-- ... -->
  </head>
  <body>
    <!-- ... -->
  </body>
</html>
// Make sure this code isn't exported to the Browser bundle
// and executed only on SERVER (Node.js)
const express = require('express');
const Spiderable = require('spiderable-middleware');

const spiderable = new Spiderable({
  rootURL: 'http://example.com',
  auth: 'APIUser:APIPass'
});

const app = express();
app.use(spiderable.handler).get('/', (req, res) => {
  res.send('Hello World');
});

app.listen(3000);

We provide various options for serviceURL as "Rendering Endpoints", each endpoint has its own features to fit every project needs.

Return genuine status code

To pass expected response code from front-end JavaScript framework to browser/crawlers, you need to create specially formatted HTML-comment. This comment can be placed in any part of HTML-page. head or body tag is the best place for it.

Format

html:

<!-- response:status-code=404 -->

jade:

// response:status-code=404

This package support any standard and custom status codes:

Speed-up rendering

To speed-up rendering, you should tell to the Spiderable engine when your page is ready. Set window.IS_RENDERED to false, and once your page is ready set this variable to true. Example:

<html>
  <head>
    <meta name="fragment" content="!">
    <script>
      window.IS_RENDERED = false;
    </script>
  </head>
  <body>
    <!-- ... -->
    <script type="text/javascript">
      //Somewhere deep in your app-code:
      window.IS_RENDERED = true;
    </script>
  </body>
</html>

Detect request from Pre-rendering engine during runtime

Pre-rendering engine will set window.IS_PRERENDERING global variable to true. Detecting requests from pre-rendering engine are as easy as:

if (window.IS_PRERENDERING) {
  // This request is coming from Pre-rendering engine
}

Note: window.IS_PRERENDERING can be undefined on initial page load, and may change during runtime. That's why we recommend to pre-define a setter for IS_PRERENDERING:

let isPrerendering = false;
Object.defineProperty(window, 'IS_PRERENDERING', {
  set(val) {
    isPrerendering = val;
    if (isPrerendering === true) {
      // This request is coming from Pre-rendering engine
    }
  },
  get() {
    return isPrerendering;
  }
});

JavaScript redirects

If you need to redirect browser/crawler inside your application, while a page is loading (imitate navigation), you're free to use any of classic JS-redirects as well as your framework's navigation, or History.pushState()

window.location.href = 'http://example.com/another/page';
window.location.replace('http://example.com/another/page');

Router.go('/another/page'); // framework's navigation !pseudo code

Note: Only 4 redirects are allowed during one request after 4 redirects session will be terminated.

API

Constructor new Spiderable([opts])

Note: Setting .onlyRE and/or .only rules are highly recommended. Otherwise, all routes, including randomly generated by bots will be subject of Pre-rendering and may cause unexpectedly higher usage.

// CommonJS
// const Spiderable = require('spiderable-middleware');

// ES6 import
// import Spiderable from 'spiderable-middleware';

const spiderable = new Spiderable({
  rootURL: 'http://example.com',
  auth: 'APIUser:APIPass'
});

// More complex setup (recommended):
const spiderable = new Spiderable({
  rootURL: 'http://example.com',
  serviceURL: 'https://render.ostr.io',
  auth: 'APIUser:APIPass',
  only: [
    /\/?/, // Root of the website
    /^\/posts\/?$/, // "/posts" path with(out) trailing slash
    /^\/post\/[A-z0-9]{16}\/?$/ // "/post/:id" path with(out) trailing slash
  ],
  // [Optionally] force ignore for secret paths:
  ignore: [
    '/account/', // Ignore all routes under "/account/*" path
    '/billing/' // Ignore all routes under "/billing/*" path
  ]
});

Configuration via env.vars

Same configuration can get achieved via setting up environment variables:

ROOT_URL='http://example.com'
SPIDERABLE_SERVICE_URL='https://render.ostr.io'
SPIDERABLE_SERVICE_AUTH='APIUser:APIPass'

alternatively if you're migrating from other pre-rendering service you can keep using existing variables, we support it for compatibility

ROOT_URL='http://example.com'
PRERENDER_SERVICE_URL='https://render.ostr.io'
PRERENDER_SERVICE_AUTH='APIUser:APIPass'

spiderable.handler(req, res, next)

Middleware handler. Alias: spiderable.handle.

// Express, Connect:
app.use(spiderable.handler);

// Meteor:
WebApp.connectHandlers.use(spiderable.handler.bind(spiderable));

// HTTP(s) Server
http.createServer((req, res) => {
  spiderable.handler(req, res, () => {
    // Callback, triggered if this request
    // is not a subject of spiderable pre-rendering
    res.writeHead(200, {'Content-Type': 'text/plain; charset=UTF-8'});
    res.end('Hello vanilla NodeJS!');
    // Or do something else ...
  });
}).listen(3000);

AMP Support

To properly serve pages for Accelerated Mobile Pages (AMP) we support following URI schemes:

# Regular URIs:
https://example.com/index.html
https://example.com/articles/article-title.html
https://example.com/articles/article-uniq-id/article-slug

# AMP optimized URIs (prefix):
https://example.com/amp/index.html
https://example.com/amp/articles/article-title.html
https://example.com/amp/articles/article-uniq-id/article-slug

# AMP optimized URIs (extension):
https://example.com/amp/index.amp.html
https://example.com/amp/articles/article-title.amp.html

All URLs with .amp. extension and /amp/ prefix will be optimized for AMP.

Rendering Endpoints

To change default endpoint, grab integration examples code and replace render.ostr.io, with endpoint of your choice. For NPM/Meteor integration change value of serviceURL option.

Note: Described differences in caching behavior related to intermediate proxy caching, Cache-Control header will be always set to the value defined in "Cache TTL". Cached results at the "Pre-rendering Engine" end can be purged at any time.

Debugging

To make sure a server can reach our rendering endpoint run cURL command or send request via Node.js to (replace example.com with your domain name) https://test:test@render-bypass.ostr.io/?url=http://example.com.

In this example we're using render-bypass.ostr.io endpoint to avoid any possible cached results, read more about rendering endpoints. As API credentials we're using test:test, this part of URL can be replaced with auth option from Node.js example. Your API credentials and instructions can be found at the very bottom of Pre-rendering Panel of a host, click on "Integration Guide".

# cURL example:
curl -v "https://test:test@render-bypass.ostr.io/?url=http://example.com"
// Node.js example:
const https = require('https');

https.get('https://test:test@render-bypass.ostr.io/?url=http://example.com', (resp) => {
  let data = '';

  resp.on('data', (chunk) => {
    data += chunk.toString('utf8');
  });

  resp.on('end', () => {
    console.log(data);
  });
}).on('error', (error) => {
  console.error(error);
});

Running Tests

  1. Clone this package
  2. In Terminal (Console) go to directory where package was cloned
  3. Then run:

Node.js/Mocha

# Install development NPM dependencies:
npm install --save-dev
# Install NPM dependencies:
npm install --save
# Run tests:
ROOT_URL=http://127.0.0.1:3003 npm test

# Run same tests with extra-logging
DEBUG=true ROOT_URL=http://127.0.0.1:3003 npm test
# http://127.0.0.1:3003 can be changed to any local address, PORT is required!