How to Create an SSL Certificate to Securely Access a NestJS Backend App using HTTPS

Rihem Larbi
2 min readFeb 28, 2024

--

In this tutorial, I will show you how to create an SSL certificate to securely Access a NestJS backend server (PS: you can follow this tutorial: create a backend server side for react native app using NestJS connected to mongodb atlas)

1- Generate a private key

To generate a private key we need to install OpenSSl for transport Layer Security (TLS) and Secure Socket Layer (SSL) protocols on our local machine after installing OpenSSl you should add the environment variables. In user variables you should add this:

OPENSSL_CONF: C:\Program Files\OpenSSL-Win64\bin\openssl.cfg

Then, in Path section you should add this :

C:\Program Files\OpenSSL-Win64\bin

After the installation, we need first to create a cert folder and then we should run the command bellow to generate the private key. The command will generate the private key and save it in key.pem file inside cert directory

mkdir -p cert
openssl genrsa -out key.pem

2- Create a CSR (Certificate Signing Request)

Since we are our own certificate authority, we need to use CSR to generate our certificate. The command bellow will generate a csr.pem file inside cert folder.

openssl req -new -key key.pem -out csr.pem

3- Generate the SSL certificate

To generate the SSL certificate, we need to use the key.pem and csr.pem files.

Let’s run the bellow command to generate it.

openssl x509 -req -days 365 -in csr.pem -signkey key.pem -out cert.pem

We are using x509 because it is the standard defining the format of the public key certificate. We set the validity of the certificate as 365 days.

The above command will save the certificate in the cert.pem file inside cert folder.

4- Integration of the SSL certificate in NestJS

Now let’s use these certificates inside our app using the file system (fs) and path module. To do so we need to edit a few lines in our app as bellow.

 const fs = require('fs');
const keyFile = fs.readFileSync(__dirname + '/../ssl/mydomain.com.key.pem');
const certFile = fs.readFileSync(__dirname + '/../ssl/mydomain.com.crt.pem');
const app = await NestFactory.create(AppModule,{
httpsOptions: {
key: keyFile,
cert: certFile,
}});

Once it’s done save it and run the server using the command bellow

npm run start 

Congratulation, now you should be able to access your data using ‘https://’

Thank you,

--

--