Joshua Bemenderfer
Server side rendering (SSR) is one of those things that’s long been touted as one of the greatest strengths of React, Angular 2+, and Vue 2. It allows you to render your apps on the server, then hydrate them with client side reactivity after the page loads, greatly increasing the responsiveness and improving the load time of your pages.
Unfortunately, it’s not the most obvious thing to set up, and the documentation for rendering Vue.js apps on the server is spread across several places. Hopefully this guide should help clear things up for you. :)
We’ll start with vue-cli’s webpack-simple template to give us a common base to work with.
We’ll also need three other packages, express for the server, vue-server-renderer to render the bundle, which is produced by vue-ssr-webpack-plugin.
The webpack-simple template doesn’t come with SSR capability right out of the box. There are a few things we’ll have to configure first.
The first thing to do is create a separate entry file for the server. Right now the client entry is in main.js. Let’s copy that and create main.server.js from it. The modifications are fairly simple. We just need to remove the el reference and return the app in the default export.
We also need to modify index.html a bit to prepare it for SSR.
Replace <div id=“app”></div> with , like so:
Now, we need a separate webpack configuration file to render the server bundle. Copy webpack.config.js into a new file, webpack.server.config.js.
There are a few changes we’ll need to make:
To simplify development, let’s update the build scripts in package.json to build both the client and server webpack bundles.
Replace the single build script with these three. Usage stays the same, but you can now build the client or server bundles individually with build:client and build:server, respectively.
Now, we need the server script to, well, render the application.
If all goes well, you should be able build the bundle and run the server with:
If you visit http://localhost:8080, everything should look… the same. However, if you disable JavaScript, everything will still look the same, because the app is being rendered on the server first.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!