Server Side Rendering with Vue and Express
May 5, 2019
Vue has solid support for server-side rendering in Node.js. This means that, given a Vue app,
you can render the app in an Express endpoint using the vue-server-renderer
library.
Below is an example of rendering a Vue app using Express.
const { renderToString } = require('vue-server-renderer').createRenderer();
const expressApp = require('express')();
expressApp.get('*', (req, res) => {
const app = new Vue({
// Initialize with data from the request.
data: { content: req.query.content },
template: '<div>{{content}}</div>'
});
renderToString(app).
// Sends '<div data-server-rendered="true">Hello, World</div>'
then(html => res.send(html)).
catch(err => res.status(500).send(err.stack));
});
const server = await expressApp.listen(3000);
Note that the renderToString()
function returns a promise. Make sure you handle errors.
Notice that the above div
has a data-server-rendered
attribute. The data-server-rendered
attribute marks this div for client-side hydration. In other words, you can then use the $mount()
function to make your Vue client pick up your static HTML and start reacting to client-side events.
Vue School has some of our favorite Vue
video courses. Their Vue.js Master Class walks you through building a real
world application, and does a great job of teaching you how to integrate Vue
with Firebase.
Check it out!