The self-signed certificate will be enough to establish a secure HTTPS connection, although browsers will complain that the certificate is self-signed and is not trusted. Nevertheless, it is still great for development purposes.
You must have installed OpenSSL installed on your machine. If not, on a Mac, you can install it using Brew. Install OpenSSL if you use Homebrew. Otherwise, search on Google “how to install OpenSSL on ”.
To upgrade your current OpenSSL version, then update the OpenSSL using the following command.
brew upgrade openssl
Once an OpenSSL is installed, hit this command.
openssl req -nodes -new -x509 -keyout server.key -out server.cert
You will prompt for some answers. Give the answers one by one.
That’s it! Now you have two files in the folder where you ran the following command.
- server.cert is the self-signed certificate file.
- server.key is the private key of the certificate.
Both files will be needed to establish the HTTPS connection, and depending on how you set up your server, the process of using them will be different.
Those files need to be reachable by the application; then, you need to configure the server to use them.
This is an example using the https core module and Express.
const https = require('https')
const app = express()
app.get('/', (req, res) => {
res.send('Hello HTTPS!')
})
https.createServer({}, app).listen(3000, () => {
console.log('Listening...')
})
Now initialize the package.json file using the following command.
npm init -y
Install Express using the following command.
npm install express --save
Finally, our code with the certificates is the following.
const https = require('https');
const express = require('express');
const fs = require('fs');
const app = express();
app.get('/', (req, res) => {
res.send('Hello HTTPS!')
})
https.createServer({
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.cert')
}, app).listen(3000, () => {
console.log('Listening...')
});
Save the file and go to the terminal.
node server
Go to the browser and hit this URL: https://localhost:3000.
At first, it will say it is insecure because it is self-signed but ignores this error, and now you can access the content. The looking is not great on the browser because it will say insecure, but it is excellent for local development purposes.
That’s it.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.