How I deployed My Vue SPA on Heroku 🚀
It was an exceeding finger aching day for me today when I tried deploying my app on Heroku. After trying some “known” methods that were in articles and docs, I finally was able to do get it deployed! (With some tweaking on my end though 😏). So let’s see how I did it.
Psst: I am assuming you’ve already got a VueJS app and created an Heroku app either via CLI or the heroku dashboard. Don’t know how to do either? Check out these resources
It is also worth noting that my source code was being deployed to Heroku via Github.
With all that said and cleared off my chest, let's get to the deployment shall we eh? 😀
Getting Started
Install the following dependencies on your project:
- Express(good ol’ Express)
- Serve-Static (Read more about the dependency here)
This could be achieved by running:
npm install express serve-static --save
Note: In my case, I found out that installing Express and serve-static as dependencies instead of development dependencies works.
Server.js
Create a server.js file in your project root and add the following to it:
const express = require('express');const serveStatic = require("serve-static");const path = require('path');const app = express();app.use(serveStatic(path.join(__dirname, 'dist')));const port = process.env.PORT || 80;app.listen(port);
So what the above code is doing is creating a NodeJS server via Express and serving the content in the dist folder(which is your production build after running npm run build). So when some visit your Heroku app, dist/index.html would be served!
Note: The process.env.PORT bit is very important cause Heroku would need it in assigning a port for your application so do not hard code it alright? 😉
Package.json
In package.json add the following to the scripts section:
"postinstall": "if test \"$NODE_ENV\" = \"production\" ; then npm run build ; fi ","start": "node server.js",
So both lines of codes above are called NPM Scripts and the short gist is that:
- postinstall would run after NPM installs project’s dependencies
- start would be used to start the server we created a while back with Express.
So together, the NPM scripts would tell Heroku: “Hey dude, could you please build my Vue application when the NODE_ENV is set to production then after that be a good lad and start my Express Server so my application can be live to the world!” 😆
Note: Heroku would get NODE_ENV from it’s configuration variables which you would set on your app’s dashboard under settings > config vars. Just add NODE_ENV as the Key and Production as the value.
Wrapping Up
After all that’s done, push to Github and deploy your Heroku app(either manually or automatically — anyone goes.
You should be able to see your application when you visit your Heroku app URL.
So that’s how I did it and I hope it could help you do it too when the need arises.
Happy Deploying!