In production, you might set up your application behind a reverse proxy like NGINX, which usually serves certificates for you. But you may still need to test your application using https in development.

How can you use an SSL certificate in a Node.js application?

How to Use an SSL Certificate to Develop a Secure Node.js Server

You can easily create a self-signed SSL certificate in Linux, and follow the steps below to configure your Node application to use https.

Create a server entry point file e. g index. js. Import the https and fs modules in the file like this: const https = require(‘https’); const fs = require(‘fs’) Define the options object for the https server you are about to create. Remember to replace my-server-key. pem and my-server-cert. pem with the correct paths of your private key and certificate files. const options = {     key: fs. readFileSync(“my-server-key. pem”),   cert: fs. readFileSync(“my-server-cert. pem”) } To use a real SSL certificate, which you can get for free at letsencrypt. org, use the following options: const options = {     key: fs. readFileSync("/path/to/private. key"),     cert: fs. readFileSync("/path/to/ssl_certificate. crt"),     ca: [              fs. readFileSync("/path/to/ca_root_file. crt"),              fs. readFileSync("/path/to/ca_bundle_certificate. crt")     ] } Now initialize your server using the options and set it to listen on port 443.  https. createServer(options, (req, res) => {     res. writeHead(200);     res. end(“hello world”);   })   . listen(443);

You may now start your server in the terminal using node index.js. When you test the connection by opening https://localhost or https://localhost:443/ in your browser, you should see ‘hello world’ displayed.

Your browser may also warn you about an insecure connection when using the self-signed certificate. This is normal as self-signed certificates are generally considered insecure by web browsers.

Using SSL Certificates in Node.js Applications

Most of the time, you’ll only want to add SSL certificates during the development phase. Production requirements usually call for the installation of security tools like firewalls and reverse proxies anyway.

In this manner, using an SSL certificate for your application is no longer required. You may only want to add an SSL certificate in production if your application communicates with external services.