How to use SSL in a Create-React-App

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 which performs data encryption. SSL is important because it protects data from eavesdropping and related attacks.

By default, if you create a React app using create-react-app, the app doesn’t use HTTPS. Enabling HTTPS for your app is useful, especially if you plan to proxy requests to an API that serves them over HTTPS.


Use HTTPS in React

When you create an app using create-react-app, it runs over 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 this by modifying the scripts.start value to look like this:

"scripts": {
"start": "HTTPS=true react-scripts start",
},

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

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 only a first step. If you try to start your React application at this point, you will get an error. To complete the process, you will need to configure 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 for 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

Once the CA has been successfully created, you can now start generating SSL certificates.

Generate an 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 SSL certificates.

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

Secure your React site using SSL

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



Source link

Comments are closed.