If we need to start our node.js server, then to be able to serve a site on HTTPS from localhost, you need to create a self-signed certificate.
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.
Let us say you are working with React Native or other iOS development, then you need an API point, and if the API point is served via HTTPs, then it will be straightforward; otherwise, it gets complicated to get the response from the server.
I have found it very painful while developing frontend and backend apps. So it can be beneficial in these scenarios.
Create Express HTTPS Server With A Self-Signed Certificate
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.
// server.js 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
Okay, now install Express using the following command.
npm install express --save
Finally, our code with the certificates is the following.
// server.js 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 trust me, it is excellent for local developing purposes.
That’s it.