Serving your Angular CLI App Locally over HTTPS

When creating an Angular CLI app using the ng new command, the CLI itself will create some scripts in the packages.json relating to the building, testing, and local serving of your app.

2018-03-13_21-45-49

When running npm start it will subsequently run ng serve which by default runs the web server on localhost in HTTP (e.g. http://localhost:4200). This is all well and good for local debugging of a standalone app, but if you need to run this inside an iframe on a site running HTTPS (like an Office Add-in or even a VSTS Extension), this becomes a challenge as your local app needs to be served over HTTPS as well.

Below is what you would see if you attempt to serve your content in HTTP when in an iframe of a document served over HTTPS:

2018-03-12_23-20-33
Mixed Content: The page at ‘X’ was loaded over HTTPS, but requested an insecure resource ‘http://localhost:4200/index.html’ This request has been blocked; the content must be served over HTTPS.

Now you are more than able to run the Angular CLI web server in HTTPS through the --ssl--ssl-cert, and --ssl-key switches, where you point to the location of a valid self-signed certificate/key for localhost. But, where do you get said certificates?

The easiest method I can find is to install browser-sync as a dev dependency.

npm install browser-sync --save-dev

This will install a self-signed certificate and key for localhost, which you can now point to when adding the --ssl switches mentioned above.

Change the start script in packages.json to the following

ng serve --ssl true --ssl-key /node_modules/browser-sync/lib/server/certs/server.key --ssl-cert /node_modules/browser-sync/lib/server/certs/server.crt

Now, when you call ng start NPM will run ng serve with the additional SSL switches, and serve your site under HTTPS (e.g. https://localhost:4200). From here on it should be smooth sailing.

 

 

Feature Photo by Joshua Sortino

One thought on “Serving your Angular CLI App Locally over HTTPS

Comments are closed.

Blog at WordPress.com.

Up ↑

%d bloggers like this: