September 3, 2024 • ☕️ 1 min read
日本語

Enabling HTTPS in Next.js is actually easy. Currently, it’s an experimental feature, but you can set it up with just one flag.

Copy
next dev --experimental-https

When you run this, Next.js will use mkcert to automatically create a certificate for localhost in the certificates folder.

However, there may be cases where you need to use a domain other than localhost for work. In such cases, you will often be required to register the domain in your hosts file and access the development environment using domain:3000 instead of localhost:3000.

Today, I want to introduce the detailed steps for that.

Manually Creating Certificates

When left to Next.js, only certificates for localhost are created, so you need to manually create a certificate for the domain.

Installing mkcert

First, let’s install mkcert. With this, you can easily create certificates for your local environment.

Copy
brew install mkcert
# Create the rootCA. You will be asked for your admin password, so please enter it
mkcert -install

Creating a Certificate for the Domain

Next, create a certificate for the domain that you will use in the development environment. Let’s create a certificate valid for 10 years this time.

Copy
export MKCERT_VALIDITY=3650 && mkcert -key-file certificates/key.pem -cert-file certificates/cert.pem your-project.com localhost 127.0.0.1 ::1

If you see a message like the one below, the certificate creation was successful.

Copy
Created a new certificate valid for the following names 📜

- "your-project.com"
- "localhost"
- "127.0.0.1"
- "::1"

The certificate is at "certificates/cert.pem" and the key at "certificates/key.pem" ✅

It will expire on 3 December 2026 🗓

Adding Settings to package.json

To use the created certificate, add the following setting to your package.json.

Copy
"scripts": {
  "dev:https": "next dev --experimental-https --experimental-https-key ./certificates/key.pem --experimental-https-cert ./certificates/cert.pem"
}

Complete

That’s it for the setup. Once you run pnpm dev:https, you’ll be able to access https://localhost:3000 or https://your-project.com:3000 without warnings. Enjoy a safe and smooth development environment!


Relative Posts

Improving Cold Start issues in Next.js Serverless Functions

May 7, 2023

ThunderMiracle

Blog part of ThunderMiracle.com