Running HTTPS locally is a must for certain types of development.
During development, you may want to set up your web server to establish secure connections with browsers. Node.js makes this a straightforward process, even in a non-production environment, with its built-in https module.
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.
You may get the error “Error: listen EACCES: permission denied 0.0.0.0:443” when you try to start your server, this is due to your machine denying the application access to port 443 which is the default behavior in most devices. To fix this, run the node index.js command as the root user in Linux (sudo node index.js), or open your terminal as an administrator in Windows.
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.