Using HTTPS on Next.js local development server

March 10, 2023

The Next.js development server runs on HTTP by default. In this post, we will discuss how to run the Next.js development server on HTTPS.

Using HTTPS on Next.js local development server

Prerequisite:

we need to install mkcert.

After installing, we will generate a CA i.e Certificate Authority first.
mkcert -install will do this.

Then, we have to generate a certificate for specific servers.
let we want to generate a certificate for localhost since most of the time we use this as a server.
Here, mkcert localhost will do this.
This will generate a certificate and a key named as *.pem and *-key.pem respectively.

Creating the Next.js Custom Server(which runs on HTTPS!)

First copy the certificate( *.pem ) and key( *-key.pem ) to a directory on the next.js project. Let the directory is on the project root and named as https_cert.

Now create a file named server.js on the project root and paste the following configuration. Don’t forget to change the certificate and key name according to your certificate and key on httpsOptions.

Server.js

const { createServer } = require("https");
const { parse } = require("url");
const next = require("next");
const fs = require("fs");
const port = 3000;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();

const httpsOptions = {
    key: fs.readFileSync("./src//SSL/localhost-key.pem"),
    cert: fs.readFileSync("./src//SSL/localhost.pem")
};

app.prepare().then(() => {
    createServer(httpsOptions, (req, res) => {
        const parsedUrl = parse(req.url, true);
        handle(req, res, parsedUrl);
    }).listen(port, (err) => {
        if (err) throw err;
        console.log("ready - started server on url: https://localhost:" + port);
    });
});

Now on the terminal, run node server.js.
This will start a server on https://localhost:3000.

If there are API routes, then these will be available on https://localhost:3000/api/*.

Ref by : https://dev.to/


Written by Manoj Bhardwaj who lives and works in Dharamshala Himachal Pradesh (India). My stackoverflow