Create a Localhost HTTPS Server on NodeJS with Express and CreateServer

Posted November 16, 2023
LocaLHost HTTPS Server on NodeJS with Express and CreateServer

Learn how to set up an Express HTTPS server in Node.js on localhost. Gain insights on creating your local HTTPS server with NodeJS, Express, and CreateServer in easy steps.

You’ll learn everything from creating a local SSL certificate for your localhost domain to handling incoming HTTPS requests and redirecting HTTP to HTTPS.

The goal is to have a secure local NodeJS Express server that supports HTTPS requests, allowing you to test your applications locally with SSL encryption.

Dive and use HTTPS to create an Express server in Node.js

Key Takeaways

  • Setting up an HTTPS server on your localhost using NodeJS and Express.
  • Create SSL certificates to enable HTTPS on your local server.
  • Configuring Node.js Express to use HTTPS server with CreateServer and expose secure routes.
  • Redirecting HTTP to HTTPS to automatically redirect incoming requests to the secure HTTPS version.

Step 1: Getting Started with HTTPS Express Server and NodeJS

To start with Express and NodeJS, you must install both technologies on your machine. Once installed, you’re ready to start building your local HTTPS server.

  • First, run the following command to initialize Express:
npm init -y

Then install your Express package using the following command:

npm install express

Now that you have Express and NodeJS installed, it’s time to move on to the next step in setting up your local HTTPS server.

Step 2: Creating SSL Certificates for Localhost

Before we can enable HTTPS on your Node.js local server, you need an SSL certificate for your localhost. This way, you can use a valid HTTPS certificate and encrypt connections between your browser and the server.

To generate SSL certificates, use OpenSSL. Follow the steps below to create a self-signed SSL certificate for localhost.

  • For macOS, ensure you have OpenSSL installed
brew install openssl
  • On Linux, distros have OpenSSL installed by default.
  • On Windows, use Git for Windows to run your commands:

Let’s generate SSL certificates that HTTPS NodeJS API will use to create an Express HTTPS localhost server.

In your working directory (where you initialized Node.js), create a cert directory to store your SSL certificates. Make sure you cd based on the terminal you are using:

mkdir cert
cd cert
  • Generate a new private key by entering the following command:
openssl genrsa -out localhost.key 2048

This will generate a private key for the SSL certificate as follows:

$ openssl genrsa -out localhost.key 2048
Generating RSA private key, 2048 bit long modulus (2 primes)
...........+++++
.........................+++++
e is 65537 (0x010001)
  • Generate a certificate signing request (CSR) by entering the following command:
openssl req -new -key localhost.key -out localhost.csr

LocaLHost HTTPS Server on NodeJS with Express and CreateServer

  • Generate a self-signed SSL certificate by entering the following command:
openssl x509 -req -in localhost.csr -signkey localhost.key -out localhost.crt

Your self-signed SSL certificate will be generated as follows:

$ openssl x509 -req -in localhost.csr -signkey localhost.key -out localhost.crt
Signature ok
subject=C = AU, ST = Some-State, O = Internet Widgits Pty Ltd
Getting Private key

These commands will generate two files, localhost.key and localhost.crt, which contain your private key and SSL certificate, respectively.

LocaLHost HTTPS Server on NodeJS with Express and CreateServer

Step 3: Setting Up HTTPS on Node.JS using Express Server with HTTPS Localhost

Now that you have generated your SSL certificates, it’s time to configure Express to use HTTPS. To achieve this, you need to update your server configuration in the Express application to support HTTPS requests.

Create an index.js file and, use the https module to create a new instance of the https.Server object.

The https.Server object takes a configuration object that specifies the SSL certificates and other relevant options, such as the port to listen on.

Here is an example of how to set up the https.Server:

const https = require('https');
const fs = require('fs');
const express = require('express');
const app = express();

const options = {
  key: fs.readFileSync('./cert/localhost.key'),
  cert: fs.readFileSync('./cert/localhost.crt')
};

const server = https.createServer(options, app);

You need the fs module to read the SSL certificates from the file system using the fs.readFileSync() method.

You can now create a configuration object containing the SSL certificates using https.createServer() and an instance of the https.Server.

Step 4: Creating the HTTPS Express Server and Use CreateServer

Now that you have configured Express to use HTTPS and created your SSL certificates, it’s time to create the HTTPS server itself. This is where the NodeJS https module comes in handy.

Use the https module and call its createServer method as follows:

const https = require('https');
const fs = require('fs');
const express = require('express');
const app = express();

const keys = {
  key: fs.readFileSync('./cert/localhost.key'),
  cert: fs.readFileSync('./cert/localhost.crt')
};

const server = https.createServer(keys, app);

const port = 3000;
server.listen(port, () => {
  console.log(`Server is listening on https://localhost:${port}`);
});

Now you listen for incoming HTTPS requests binding the server to port 3000.

Step 5: Handling Node.js HTTPS Requests with Express on localhost

Now that your HTTPS server is running, you can handle incoming requests.

Let’s define HTTPS routes on Node.js so The Express server can now use localhost HTTPS with createServer.

The following code sample will add GET and POST requests to your HTTPS Node.js server:

const https = require('https');
const fs = require('fs');
const express = require('express');
const app = express();

const keys = {
  key: fs.readFileSync('./cert/localhost.key'),
  cert: fs.readFileSync('./cert/localhost.crt')
};

const server = https.createServer(keys, app);

app.get('/', (req, res) => {
  const { queryParam } = req.query;
  //Do something with queryParam
  res.status(200).send('GET request received');
});

const bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.post('/', (req, res) => {
  const { bodyParam } = req.body;
  //Do something with bodyParam
  res.send('POST request received');
});

const port = 3000;
server.listen(port, () => {
  console.log(`Server is listening on https://localhost:${port}`);
});

Step 6: Testing Your HTTPS Node.js Express Localhost Server using cURL

The local HTTPS server on NodeJS with Express, let’s test it out. Run the following command to start the server:

node index.js

LocaLHost HTTPS Server on NodeJS with Express and CreateServer

This will expose the server on https://localhost:3000. Note that this must be HTTPS and not HTTP.

Now send the following cURL request to test the server:

$ curl --insecure https://localhost:3000

This should return the Node.js Express HTTPS GET requests as follows:

LocaLHost HTTPS Server on NodeJS with Express and CreateServer

Step 7: Testing HTTPS in Node.js Using Browser

To test the same, use the browser and send HTTPS requests to your localhost domain https://localhost:3000. However, this will give you the following warning message:

LocaLHost HTTPS Server on NodeJS with Express and CreateServer

You can, however, proceed and access your HTTPS NodeJS Express server as follows:

LocaLHost HTTPS Server on NodeJS with Express and CreateServer

If you want to eliminate the above warning message, follow this Add localhost Domain HTTPS with Let’s Encrypt SSL Certificate Issuer - SelfSigned guide, and you will have the following results.

LocaLHost HTTPS Server on NodeJS with Express and CreateServer

Step 8: Redirecting Express Server HTTP Requests to HTTPS

To ensure all traffic to your local server is secure, let’s redirect HTTP requests to HTTPS.

You need to modify your Express server configuration as follows:

  • First, check if the request is coming through HTTP, then redirect it to the corresponding HTTPS location.

  • Use Express middleware to detect incoming HTTP requests and redirect them to HTTPS.

Here is how to redirect all HTTP traffic to HTTPS for your Express application:

// Redirect HTTP to HTTPS
app.use((req, res, next) => {
  if (req.secure) {
    // If a request is already secure (HTTPS), move to the next middleware
    next();
  } else {
    // Redirect HTTP to HTTPS
    res.redirect(`https://${req.headers.host}${req.url}`);
  }
});

This middleware will check if the incoming request uses HTTPS (req.secure). If it’s not secure (HTTP), it redirects the request to the HTTPS equivalent using res.redirect.

Your whole HTTPS on Node.js Express server should be as follows:

const https = require('https');
const fs = require('fs');
const express = require('express');
const app = express();

const keys = {
  key: fs.readFileSync('./cert/localhost.key'),
  cert: fs.readFileSync('./cert/localhost.crt')
};

// Redirect HTTP to HTTPS
app.use((req, res, next) => {
  if (req.secure) {
    // If a request is already secure (HTTPS), move to the next middleware
    next();
  } else {
    // Redirect HTTP to HTTPS
    res.redirect(`https://${req.headers.host}${req.url}`);
  }
});

const server = https.createServer(keys, app);

// Rest of your existing routes
app.get('/', (req, res) => {
  const { queryParam } = req.query;
  //Do something with queryParam
  res.status(200).send('GET request received');
});

const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/', (req, res) => {
  const { bodyParam } = req.body;
  //Do something with bodyParam
  res.send('POST request received');
});

const port = 3000;
server.listen(port, () => {
  console.log(`Server is listening on https://localhost:${port}`);
});

Conclusion

Voila! You have successfully created a local HTTPS server on NodeJS with Express. In summary, you have learned:

  • Setting up an HTTPS server on your localhost using NodeJS and Express.
  • Created SSL certificates for your localhost domain to enable HTTPS on your local server.
  • Configured Express to use HTTPS server configuration and handle secure routes.
  • Created the HTTPS server using the NodeJS https module and bind it to the Express application.
  • Redirected HTTP to HTTPS to automatically redirect incoming requests to the secure HTTPS version.

If you are want to use a zero-config setup to create local trusted development certificates, check this guide and learn how to use Mkcert on Windows|Linux|Ubuntu with Localhost SSL HTTPS Certificates

FAQ

How do I create a local HTTPS server on NodeJS with Express?

To create a local HTTPS server on NodeJS with Express, use Express and OpenSSL to generate SSL certificates for your localhost domain using OpenSSL. Now, create the HTTPS server using the NodeJS https module and bind it to your Express application.

What are the best practices for securing a local HTTPS server?

Use strong encryption SSL certificates, and add security headers in your app.

How can I handle HTTPS requests in my Node.js Express application?

Configure Express to use HTTPS with secure routes. Update the server configuration to use the SSL certificates and serve incoming requests as HTTPS.

How do I redirect HTTP requests to HTTPS?

Use Express middleware and instruct it on redirecting HTTP requests to HTTPS on your server configuration.

What tools can I use to test my localhost Express and Node.js HTTPS server?

cURL is good, alongside web browsers such as Chrome and Firefox.

How can I ensure the security of my Nodejs HTTPS server?

Use strong encryption algorithms and regularly update SSL certificates. For more, follow this how-to Add localhost Domain HTTPS with Let’s Encrypt SSL Certificate.

Create a Localhost HTTPS Server on NodeJS with Express and CreateServer

Written By:

Joseph Chege