Shahar
Shahar

Reputation: 488

NodeJS HTML rendering strategy

We want to build a production-ready social network website (Facebook or Instagram style). We plan to use Node on the server side and are looking for the best technology for rendering view components on the server side.

SEO friendliness is a must, so Angular doesn’t seem like a good fit (unless anyone can advocate for Prerender.io as a solid choice).

We also wish to support AJAX so that most of the rendering would be done on the server, but updates would be done on the client.

Having looked at React, it seems like a good choice, but there’s one thing I’m worried about - the fact that out of the box, you would need to load all data at the route level as opposed to the component level (since renderToString is synchronous - see the discussion here

I don't really understand what would be a robust alternative for server side rendering if we're passing on React.

If I understnd correctly, the basic way (which does allow async loading from within sub components) would be something like:

  // The main page route
app.get('/',function(){
  var html = renderBase();
  renderHeader(html)
    .then(
    renderFeed(html)
  ).then(
    renderFooter(html)
  );
})

renderBase = function(){
  return = "<html><body>..."
}

renderHeader = function(){

  someIoFunction(function(){

    // build HTML based on data

  })

}

Seemingly using a template engine such as Jade might relieve us of some of the burden, but I can't seem to find anything on this "React vs. Templating engine" so-called issue, so probably I'm not seeing it correctly.

Thanks.

Upvotes: 1

Views: 306

Answers (1)

Brigand
Brigand

Reputation: 86260

Basically the solutions come down to using a convention where each component has a static function which returns the data it needs, and it calls the function of the same name on the components it needs. This is roughly how it looks:

class CommentList {
  static getData = (props) => {
    return {
      comments: api.getComments({page: props.page})
    };
  }
}

class CommentApp {
  static getData = (props) => {
    return {
      user: api.getUser(),
      stuff: CommentList.getData({page: props.commentPage})
    };
  }
  render(){
    return <CommentList comments={this.props.stuff.comments} />
  }
}

Or you can figure out all of the data requirements at the top of the tree, but while simpler to start out, it's more fragile. This is what you do with templates.

Upvotes: 1

Related Questions