Express.js is a web application framework for Node.js designed for building web applications, in this series of articles I will explain step by step how i realized an express server with some advanced functions that i use for my single page application made with Angular 7.

I will discuss the 7 main problem that i solved in different articles:

In this fourth article I will discuss how to redirect http to https requests.

Reference repository

A working example of this project is available at:

https://github.com/mzuccaroli/express_server_for_angular_example the master branch contain the final full project but there’s a dedicated branch for every single article, for this one the reference is: https://github.com/mzuccaroli/express_server_for_angular_example/tree/feature/http_to_https_redirects

A quick note about environments

Handling https request and redirect http ones is a must-have for a modern application, but https could be tricky to handle while developing the application on your local machine. I solved this problem with some environment variables: with node you can easily handle environment variables and set an “_environment” variable, then you can deactivate the redirect options for local development.

You can set environment variables manually by running your application like this:

ENVIRONMENT=dev node server.js

then use the variable in your code by adding:

const _environment = process.env.ENVIRONMENT;

you can handle this variables via docker or set them in your IDE, the following image is my webstorm setting.

Redirect http request to https

Once you have made your decisions about environment variables you can add this code to your server:

note that you need to enable the trust proxy in your application and then you will be able to distinct https request from http.

This is a simple improvement that you can add to your server and worry no more about not secure requests.

In the next article I will discuss an improvement similar to this one, how to handle www and non-www urls.