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:
Alternatively, you can set the HTTPS environment variable to true when you start your app.
On Linux/macOS:
On Windows cmd:
On Windows Powershell:
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.
Then you can install mkcert using Homebrew
Create a local certificate authority(Ca) by running the following command.
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.
Run the following to generate the certificate and store it in the folder you just created.
Configure React to Use SSL
In package.json, add a path that points to the SSL certificates.
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.