The Best Way to use Vue.js with Express – Server Side Rendering

Server Side Rendering made easy with Express-Vue.

Posted by daksh on May 6, 2017

Vue Server Side Rendering

Vue is an aspiring Front-end Framework which is a very high performant and clean framework in terms of the code and the problem with Front-end Frameworks built on javascript always remain the same. They render on client side just like Angular 1 which runs on client side and is very slow on average connections (Less than 5Mbps)

To Tackle the Problem, Vue was launched with Server-Side Rendering and It’s not necessary to use Server-Side Rendering with Vue as we can use it directly with Client Side as well. Vue comes with other pros as well such as Virtual DOM which is a representation of the Real DOM (Document Object Model) which allows us to make faster changes to it as we all know that the Real DOM was slow, Hence Virtual DOM took an edge over it.

Virtual DOM Representation Vue.js Representation of the Virtual DOM, Credit - Vuejs.org

Today, here we are going to talk about using Vue with Express for Server-Side Rendering which is usually faster and better than client side rendering. Express is a module built on top of the http module from Node.js, It allows us to easily make a web-server and render views using templating engines such as - Ejs (embedded javascript), Pug (formerly Jade), etc.

In the same way, we can use Express-Vue module as a templating engine for express and render the views on the server-side and serve them to the client / user. Express makes the process easy in general and there’s no necessity of using it, you can use vue with other kinds of backend modules as well. Just depends on your choice.

Let’s dive into some code and explore the glory of Server-Side Rendering with Express and Vue!

Firstly, We’ll install Node.js as Express relies on top of node. You can download Node.js from their website and they have installers available for most of the Operating Systems such as Windows, OS X and Linux.

Once you’ve installed it, Now you just need to open your terminal or command prompt in case you are using Windows and write the following -

npm init -y

This will initialize the application by creating a package.json file in the directory, where you executed the code.

Now, We’ll install the necessary modules to run express with vue and to perform server side rendering in general. You need to write the following code, in the terminal window -

npm install -S express express-vue

At this point of time, it will start installing modules one-by-one and Once, It’s done you can jump into your code editor and start writing some code in javascript. Let’s start writing it by creating the file index.js and writing into it.

var express = require('express'),
    app = express(),
    expressVue = require('express-vue')

app.engine('vue', expressVue)
app.set('views', __dirname + '/views');
app.set('expressVue', {
    componentsDir: __dirname + '/components',
    defaultLayout: 'layout'
})
app.set('view engine', 'vue');

let title = 'Hello, Vue'

app.get('/', (req, res) => {
    let scope = {
	data: {
		title: title
	},
        vue: {
            head: {
                title: title,
                meta: [{
                        property: 'og:title',
                        'Hello, Vue'
                    },
                    {
                        property: 'twitter:title',
                        'Hello, Vue'
                    }
                ]
            }
        }
    }
    res.render('index', scope)
})

let port = process.env.PORT || 3000;
app.listen(port, () => {
    console.log(`App is running over ${port}`)
})

That’s the barebones of our server, now we need to write some Vue code and We’ll start by creating a folder in the same directory called as views and then We’ll make two files named as layout.vue and index.vue after that we would make a new folder named as components where our Vue components will live.

Now, Let’s fill the file layout.vue with the following code for injecting our components into that base file and Here we begin -

	<template lang="html">
    <div>
        <h1></h1>
    </div>
</template>

<script>
    export default {
        data: function() {
            return {}
        }
    }
</script>

<style lang="css">

</style>

Now, We’ll add the following code to index.vue for serving as the container of components.

	<template>
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
            <script src="https://unpkg.com/vue/dist/vue.js"></script>
        </head>
        <body>
            
            
        </body>
    </html>
</template>

<script>
</script>

<style>

</style>

Once you’re done, get back to the terminal and write the following node index.js in the main directory of the project to run the application and Once, It started running. It will return an output message that the app is running at some port on your machine. For me the port was 3000 and I went to localhost:3000 in the browser and saw the "Hello, Vue" message.

Now, you can start writing server (backend) in express and writing front-end code in vue.js which allows you to render it on the server side.

Thanks for Watching, I hope you have learnt something new :)