HTML Rendering On Server With Node.js

- 1 answer

Suppose I've got a web page, which contains nothing but a javascript reference. When a browser loads the page it runs the javascript, which does the actual rendering. The javascript is large, complex, and makes a lot of XHR calls.

Now I need to make this page searchable, i.e. render the page on the server.

I tried to load the page in phantomJS but the it was slow and sometimes did not complete the whole page. So I'm wondering if there is an alternative.

Ideally I need a node.js script to

  • load a web page by URL
  • run the page javascript and then
  • serialize the DOM created by the javascript to HTML.

P.S. I can assume that the javascript is based on React.js



Essentially you need to configure a node.js server that for every request can respond the react component rendering result as plain string. The key is React.renderToString. An example in combination with react-router:

import express from "express";  
import React from "react";  
import Router from "react-router";  
const app = express();

// set up Jade
app.set('views', './views');  
app.set('view engine', 'jade');

import routes from "../shared/routes";

app.get('/*', function (req, res) {, req.url, Handler => {
    let content = React.renderToString(<Handler />);
    res.render('index', { content: content });

var server = app.listen(3000, function () {  
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);

React-router is helpful to load components based on url but it is not strictly necessary. Anyway if you are new to react ecosystem I suggest you to take a look at this starter kit for isomorphic react applications. As you should know what you are trying to do is called isomorphic Javascript.