# Serve an Angular app on localhost via HTTPS

Source: https://tpiros.dev/blog/serve-an-angular-app-on-localhost-via-https

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`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Exceptions) 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](https://zeropointdevelopment.com/how-to-get-https-working-in-windows-10-localhost-dev-environment/) 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.
