Serving with HTTPS/SSL

For local development, especially when working with features that require a secure context (like Service Workers or certain Web APIs), you may need to run your server over HTTPS. serve provides an easy way to do this using your own SSL certificates.

CLI Flags for SSL

You can enable HTTPS by providing the path to your certificate files using these command-line flags:

  • --ssl-cert <path>: Path to the SSL certificate file.
  • --ssl-key <path>: Path to the SSL certificate's private key file.
  • --ssl-pass <passphrase>: The passphrase for the certificate or key, if it's encrypted.

serve supports two common certificate formats: PEM and PKCS12 (PFX).

Using PEM Certificates

PEM is a widely used format where the certificate and private key are stored in separate files (e.g., cert.pem, key.pem).

To use a PEM certificate, you must provide both the --ssl-cert and --ssl-key flags.

serve --ssl-cert path/to/my-cert.pem --ssl-key path/to/my-key.pem

If your private key is encrypted with a passphrase, add the --ssl-pass flag:

serve --ssl-cert cert.pem --ssl-key encrypted-key.pem --ssl-pass mysecretphrase

The server will start using https, and the local URL will look like https://localhost:3000.

Using PKCS12/PFX Certificates

PKCS12 is a format that bundles the certificate and private key into a single file, usually with a .pfx or .p12 extension.

To use a PFX certificate, you only need to provide the --ssl-cert flag.

serve --ssl-cert path/to/my-cert.pfx

If the PFX file is protected by a password, use the --ssl-pass flag to provide it.

serve --ssl-cert path/to/my-cert.pfx --ssl-pass mysecretpassword

Note: The tests/server.ssl.test.ts file demonstrates these use cases with fixture certificates, confirming the expected behavior.

Generating Local Certificates

For development purposes, you'll typically use a self-signed certificate. Browsers will show a warning for these, but you can usually proceed after acknowledging the risk.

Tools like mkcert are highly recommended for creating locally-trusted development certificates that avoid browser warnings.

Example using mkcert:

  1. Install mkcert.
  2. Run mkcert -install to install its local CA.
  3. Generate a certificate for localhost:

    mkcert localhost

    This will create localhost.pem and localhost-key.pem files.

  4. Start serve with the generated files:

    serve --ssl-cert localhost.pem --ssl-key localhost-key.pem