Server Side Rendering with Vue and Express

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({ data: { content : req.query.content }, template : '<div>{{content}}</div>' }); renderToString(app). 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.

More Vue Tutorials