Vuejs app on CleverCloud + HTTPS redirection in few minutes
Tags: vue, node, devops
Published: 2020-04-18 11:09:30

# Scaling 🐳 🐳 🐳

Nowadays a lot of solutions exists so as to freely host small application, such as Firebase, Netlifly, S3, Heroku, Github Pages. They give us the power of massive production in few seconds by scaling automatically (with some cost of course...).

I have been playing with Clever Cloud for side projects and I wanted to share with you how to deploy a Vuejs Application with HTTPS redirection.
Before continuing, I'm not sponsored by Clever Cloud at all. I'm just happy to share this.

Let's start a 1960 funky groovy music:

![dancing](https://dev-to-uploads.s3.amazonaws.com/i/bv7c912kxibqf2ujii9j.gif)

## Generate the beast with vue-cli 🐥

If you already have an application, [jump to the next section](#setup-express-%EF%B8%8F).
To generate the Vue application, make sure to have vue-cli installed:
```bash
$ npm install -g @vue/cli
## To check if it is installed
$ vue --version
```

The vue application created in this example is the default template from vue-cli:
```bash
$ vue create super-vue-app
```
Follow the setup, open project workplace, run the application and go to your favorite browser the URL `http://localhost:8080`
```$
 $ cd super-vue-app
 $ npm run serve
```

To anticipate the production stage, let's build the application with:
```
$ npm run build
```

When a vue app is built with the `vue-cli-service build` command, it creates a production-ready bundle in the `dist` folder which will be used later.

## Setup express ⚡️

The goal is to serve the application from express and properly access the corresponding route. A single-page application is based on a single file `index.html` and it uses HTML5 History API to manage navigation.
However, by default, a server bypasses `index.html` and will serve the location requested.
A middleware called [connect-history-api-fallback](https://github.com/bripkens/connect-history-api-fallback) is solving the issue by redirecting all the requests to the index.html.

Install server dependency:
```bash
$ npm install express connect-history-api-fallback dotenv --save
```

After creating the file `server.js`, the following code must be added to run an Express server:
```js
require("dotenv").config();
var express = require("express");
var app = express();
var history = require("connect-history-api-fallback");

// Synchronize vuejs history mode
app.use(
  history({
    // Enable logging
    verbose: true
  })
);

// Serve all the files in the '/dist' directory
app.use(express.static("dist"));

app.listen(process.env.PORT, "0.0.0.0", function() {
  console.log("My super vue app is listening on port 8080");
});
```
To run the server, add a new `start` command to the package.json:
```json
{
  scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint",
    "start": "node server.js"
  }
}
```
To check if the server is working locally, let's run the command and the logger should print `My super vue app is listening on port 8080`.
```bash
$ npm run start
```
Visit the page `http://localhost:8080/about`, make a refresh and it should work!

Now it's time to set up the automatic HTTPS redirection, there are 2 possible ways provided by the Clever Cloud [documentation](https://www.clever-cloud.com/doc/nodejs/nodejs/#automatic-https-redirection): 
- Use a middleware called [express-sslify](https://github.com/florianheinemann/express-sslify)
- Create our middleware and read the `X-Forwarded-Proto` header.

For this example, the second option was used. The following code was added just before `the app.listen`.
```js
// Force HTTPS redirection
app.use(function(req, res, next) {
  if (
    req.secure ||
    req.headers["x-forwarded-proto"] === "https"
  ) {
    return next();
  } else {
    return res.redirect("https://" + req.headers.host + req.url);
  }
});
```
The application is ready to be deployed. The code is available on Github: https://github.com/steevepay/vue-clever-app

## CLI & Deployment 🚀

Clever Cloud is providing a CLI called [clever-tools](https://www.clever-cloud.com/doc/clever-tools/getting_started/) to speed up deployment. First, install the CLI:
```bash
$ npm install -g clever-tools
## Command to check if everything is working
$ clever version
```
By running the following command, it will open the browser to perform a login/registration on Clever Cloud:
```bash
$ clever login
```
You will be provided 2 environment variables `CLEVER_TOKEN` and `CLEVER_SECRET`. This variable can be added in your `.bashrc` or be exported in your terminal:
```bash
$ export CLEVER_TOKEN=...
$ export CLEVER_SECRET=...
```
Clever Cloud needs to be initialized to receive the application. To achieve so, use the [`clever create`](https://www.clever-cloud.com/doc/clever-tools/create/) command to define an application.
```bash
$ clever create super-vue-app --type node
```
After running the command, a success message appears: `Your application has been successfully created!`, it is good news.
To build the application for production the command `npm run build` needs to be executed. Clever cloud has a deployment [life cycle](https://www.clever-cloud.com/doc/clever-cloud-overview/hooks/) and environment variable hooks can be injected to run commands at a specific time. In our case, `CC_POST_BUILD_HOOK` is used because it is executed just after the "npm install" where dependencies are fetched. Here is the command:
```bash
$ clever env set CC_POST_BUILD_HOOK "npm run build"
```
Lastly, the following command is used to deploy:
```bash
$ clever deploy
```
Logs are printed in the terminal and the npm commands are executed in the order: `install`, `build` and `start`! Now visit the application at the domain returned by the following command:
```bash
$ clever domain
```
Congratulations, you have just deployed your first app on Clever Cloud 👏

🎁 Bonus: if you need more details about the deployment status:
```bash
$ clever status
```

🎁 A second bonus: to stop the application: 
```bash
$ clever stop
```

🎁 A third bonus: If something went wrong during deployment, you can run the following command to restart. It may show more details about errors:
```bash
$ clever restart
```

## Conclusion 🎶

Lately, I find it easy to create and deploy applications, POC or anything you want to build. Using tools that make the deployment easy are really valuable as they save lots of your time and energy.

And as always, feel free to reach out to me! 😊

Thanks for reading!

 \* funky groovy music fades out... 🎶 * 

![groovy dance](https://dev-to-uploads.s3.amazonaws.com/i/w2s8esezpssrzpy6djy1.gif)