Server-Side Rendering (SSR)
Server-Side Rendering allows us to take our frontend JavaScript application and render it to static HTML on the server. This is important as it allows us to significantly speed up our application as the browser only has to parse the critical HTML/CSS. Maximizing performance is a key component of modern day web applications and the expectation continues to grow with progressive web applications and projects such as AMP. Both React, Angular and Vue are capable of SSR using a variety of different patterns.
Let's take a look at how we can achieve a simple Server-Side rendered Vue application:
# Create a new folder named vue-ssr:
$ mkdir vue-ssr
$ cd vue-ssr
# Create a new file named server.js
$ touch server.js
# Install dependencies
$ npm install vue vue-server-renderer express
Inside server.js, we can create a new Vue instance and use the Vue renderer to output the content of our instance as an HTML:
const Vue = require("vue");
const server = require("express")();
const renderer = require("vue-server-renderer").createRenderer();
server.get("*", (req, res) => {
const app = new Vue({
data: {
date: new Date()
},
template: `
<div>
The visited time: {{ date }}
</div>`
});
renderer.renderToString(app, (err, html) => {
if (err) {
res.status(500).end("Internal Server Error");
return;
}
res.end(`
<!DOCTYPE html>
<html lang="en">
<head><title>Hello</title></head>
<body>${html}</body>
</html>
`);
});
});
server.listen(8080);
To run the application, type the following in the Terminal:
$ node server.js
We can then open this in our browser at http://localhost: 8080 and we'd see the current date and time on screen. This is a simple example but we were able to see our application rendered using the vue-server-renderer. Notice how we're not defining a target element to render content within our Vue instance; this is handled by the renderer.renderToString function.
You'll also notice that we have the data-server-rendered="true" attribute on our DOM node, which isn't present on a client-side rendered Vue application. This allows us to hydrate our client-side instance with our server-side instance, something we'll be looking at more detail in the later chapter(s) on Nuxt (https://nuxtjs.org/).