In this guide, we will set up an SSL certificate for a localhost React project using OpenSSL, making it HTTPS secure.
Step 1: Install OpenSSL
First, you need to have OpenSSL installed on your machine. You can download it from OpenSSL Official Site for Windows or install it via the package manager:
- Windows: Download and install OpenSSL from the official website.
- Mac: Run the following command:
1 |
brew install openssl |
Linux: Run the following command:
1 |
sudo apt install openssl |
Step 2: Generate a Self-Signed SSL Certificate
Navigate to a directory where you want to store your certificates and run the following OpenSSL commands:
1 2 |
mkdir ssl && cd ssl openssl req -newkey rsa:2048 -nodes -keyout localhost.key -x509 -days 365 -out localhost.crt |
You will be prompted to enter information such as country, state, city, organization, etc. You can leave them blank or enter dummy data.
Step 3: Trust the Certificate (Mac and Windows)
To prevent browser warnings, you need to trust the self-signed certificate.
- Mac: Open
Keychain Access
, drag and droplocalhost.crt
into theSystem
keychain, then double-click it and setAlways Trust
.
- Windows: Open
certmgr
, import thelocalhost.crt
intoTrusted Root Certification Authorities
.
Step 4: Configure React Development Server
Modify your package.json
to include HTTPS settings. Update the scripts
section:
1 2 3 |
"scripts": { "start": "HTTPS=true SSL_CRT_FILE=./ssl/localhost.crt SSL_KEY_FILE=./ssl/localhost.key react-scripts start" } |
For Create React App (CRA), the react-scripts start
command will now use HTTPS.
Step 5: Run the React Project with HTTPS
Start the development server with:
1 |
npm start |
Your React app will now run on https://localhost:3000
with an SSL certificate.