If you have developed a React application using create-react-app
and are running it on your localhost, it is served over the HTTP protocol by default. However, in production, applications are typically served over HTTPS for enhanced security.
While deploying your app on platforms like Netlify or Vercel automatically enables HTTPS, configuring it locally requires some additional steps. Let’s walk through the process!
Step 1: Updating the package.json
File
Open the package.json
file of your create-react-app
project and locate the line in the scripts
section that begins with "start": "react-scripts start"
. Replace it with the following:
"start": "HTTPS=true react-scripts start"
The above modification sets the HTTPS
environment variable to true
, enabling HTTPS for your app.
Step 2: Generating a Local Certificate
To use HTTPS locally, you need to generate a local certificate. Follow these steps to generate the certificate:
Note: The following commands are for macOS, but they should work similarly on Linux. The commands may differ on Windows platforms.
-
Open your project’s root folder in the terminal.
-
Run the following command:
openssl req -x509 -newkey rsa:2048 -keyout keytmp.pem -out cert.pem -days 365
This command generates two files,
cert.pem
andkeytmp.pem
, in your project folder. -
Run the following command to convert the temporary key file to the required format:
openssl rsa -in keytmp.pem -out key.pem
This command creates a file named
key.pem
in your project folder.
You now have the necessary certificate files (cert.pem
and key.pem
) to enable HTTPS locally.
Step 3: Modifying the package.json
File Again
Update the start
script in the package.json
file as follows:
"start": "export HTTPS=true&&SSL_CRT_FILE=cert.pem&&SSL_KEY_FILE=key.pem react-scripts start"
This modification ensures that your app uses the generated certificate files for HTTPS.
Now, if you run npm start
and access https://localhost:3000
(or the port your app uses), you may encounter a warning message. To resolve this issue on macOS, refer to my tutorial on how to install a local certificate in macOS.
Once you have installed the local certificate, your app will be served over HTTPS without any problems.
That’s it! You have successfully configured HTTPS in your React app on localhost.