Skip to main content

Serve an Angular app on localhost via HTTPS

2 min read

Older Article

This article was published 7 years ago. Some information may be outdated or no longer applicable.

Everything should be served over HTTPS these days. It’s not just a trend; there are solid reasons behind it. During testing, you’ll often want HTTPS on localhost too. Some scenarios demand it: testing Progressive Web Apps with Lighthouse tanks your score without HTTPS. Other features like getUserMedia require a secure context, even locally.

Here’s how to enable HTTPS on localhost for Angular applications using the Angular CLI.

Creating a certificate via the Angular CLI

The Angular CLI has three flags for serving over HTTPS: --ssl true, --ssl-cert and --ssl-key. The full command looks like this: ng serve --ssl true --ssl-cert "/path/to/file.crt" --ssl-key "/path/to/file.key"

The --ssl-cert and --ssl-key options are not required - if you leave them out Angular will auto-create both of them.

The catch: the auto-created certificate won’t be trusted. Safari throws a “This Connection Is Not Private” warning. Chrome does the same with “Your connection is not private.”

Let’s generate a trusted certificate instead.

Create a certificate

On macOS, run this command: openssl req -newkey rsa:2048 -x509 -nodes -keyout server.key -new -out server.crt -sha256 -days 365

You’ll be prompted for a few details about the certificate. Fill those in. The result: a server.crt and a server.key file.

It doesn’t really matter where these files live, as long as the Angular CLI can reach them.

Trust the certificate

The generated certificate needs to be installed to be trusted. On macOS, you add it to the keychain. Here’s the step-by-step:

  • Double click server.crt
  • Select the login keychain in Keychain Access
  • You should see an entry called localhost - double click that
  • Expand the ‘Trust’ section and select ‘Always Trust’ under ‘When using this certificate’
  • This step may be optional: Save the changes by adding your password

On Windows, the steps are similar. Refer to this article for details.

With the trusted certificate installed, fire up the dev server: ng serve --ssl true --ssl-cert "./server.crt" --ssl-key "./server.key"

Note that your paths may be different.

Open the browser. No more certificate warnings.