#ASKTHEINDUSTRY 16: How do you implement Server Side Rendering in Node?

Alessandro Menduni
West Wing Solutions
2 min readFeb 26, 2017

When I first heard of Server Side Rendering, I thought some dark magic was involved. Now, there are a lot of ways you can do Server Side Rendering, and none of those is particularly complex or hard to deal with. Quite the opposite, you just need a couple of components set into place:

  • A back end framework that allows you to customize the way your app responds to specific URLs. In my case, my go to is Express for Node.
  • A templating system that allows you to easily fill the front end with data. Usually, such a system is comprised of a templating language and a library to compile and render the language.
  • A way to store and retrieve data, typically a Database or a JSON store. I usually rely on MongoDB via the handy mongoose library.

After you’ve got this, SSR is nothing more than this simple sequence of events:

  • The client requests for an URL, say a product page: /products/123456
  • The back end framework extracts the parameter (id = 123456) and hands control back to you
  • You query your Database for the product with id = 123456
  • You tell the templating system to fill in the product page template with the data of that specific product
  • The server sends an HTML page to the client, whose content has already been filled in. No need for JavaScript to kick in.

Let’s see an example with Express:

// Create an Express app
var express = require('express');
var app = express();
// Require your template engine
var jade = require('jade' );
// Compile your product.jade template
var renderProductPage = jade.compileFile('path/to/product.jade');
// Handle requests for /products/123456
app.get('/products/:id', function(req, res){
// Extract the product's ID from the URL
var productId = req.params.id;
// Query your Database
var productData = Database.getProductById(productId);
// Render the HTML from the data
var html = renderProductPage(productData);

// Send the HTML to the client
res.send(html);
});

That’s literally it. Nothing too fancy, just simple logic with the goal of preparing that HTML document so that all the necessary content is already in place when the it arrives to the client.

I read each and every comment, and look forward to answer to your questions! This piece is part of the #ASKTHEINDUSTRY project, which is supposed to be about your questions :) Drop a comment if there is anything I can help you with!

--

--

Alessandro Menduni
West Wing Solutions

JavaScript Engineer, passionate about testing JavaScript and software architecture