Secure Sockets Layer (SSL) is a security protocol that establishes a secure link between a server and a client. It is part of the HTTPS protocol that performs data encryption. SSL is important because it protects data from eavesdropping and related attacks.

By default, if you create a React application using create-react-app, the application does not use HTTPS. Enabling HTTPS for your app is useful especially if you plan to proxy requests to an API that serves them via HTTPS.

Using HTTPS in React

When you create an app using create-react-app, it runs on HTTP by default. To use SSL and serve pages over HTTPS, you will need to set the HTTPS variable to true in package.json. Do so by modifying the scripts.start value to look like this:

        "scripts": {
    "start": "<strong>HTTPS=true</strong> react-scripts start",
},

Alternatively, you can set the HTTPS environment variable to true when you start your app.

On Linux/macOS:

        HTTPS=true npm start

On Windows cmd:

        set HTTPS=true&&npm start

On Windows Powershell:

        ($env:HTTPS = "true") -and (npm start)

However, each approach is just the first step. If you try starting your React application at this point, you’ll get an error. To complete the process, you’ll need to set up a valid SSL certificate.

Create a Certificate Authority on Your Machine

One of the tools you can use to generate an SSL certificate is mkcert. It allows you to create locally tested development certificates without configuring anything.

It is cross-platform compatible and works on Windows, Linux, and macOS. This article uses Linux.

Find the installation guide of the platform you are using from the mkcert GitHub page.

Start by installing certutil.

        sudo apt install libnss3-tools

Then you can install mkcert using Homebrew

        brew install mkcert

Create a local certificate authority(Ca) by running the following command.

        mkcert -install

After the CA is successfully created, you can now start generating SSL certificates.

Generate SSL Certificate

Navigate to the root folder of your React app and generate an SSL certificate.

First, create a folder for the certificate.

        mkdir reactcert

Run the following to generate the certificate and store it in the folder you just created.

        mkcert -key-file ./reactcert/key.pem -cert-file ./reactcert/cert.pem "localhost"

Configure React to Use SSL

In package.json, add a path that points to the SSL certificates.

        "scripts": {
    "start":
        "HTTPS=true <strong>SSL_CRT_FILE=./reactcert/cert.pem SSL_KEY_FILE=./reactcert/key.pem</strong> react-scripts start"
}

Secure Your React Site Using SSL

This article showed you how you can use SSL certificates in a React local environment. SSL certificates are however essential for all web applications. They protect your website from hackers and protect the data of the users visiting your site.