When you create a Project using create-react-app
and start the project you will see http://localhost:3000
. When you want to test your app on https
, what should I do?
To solve the above problem, today I will talk about the problem of creating an SSL certificate
to be able to use https
on localhost
create-react-app
is a quick and simple way to create React projects.
1 2 3 4 | npx create-react-app https-local-app cd https-local-app npm start |
After finishing the steps above. Our app will run at http://localhost:3000
1. Add HTTPS
In the package.json
file, update the start script
1 2 3 4 5 | "scripts": { "start": "HTTPS=true react-scripts start", ... } |
Rerun npm start
and your browser screen should display like this:
2. Create an SSL Certificate
In the previous step, we have set to allow the app to run https. But you don’t yet have an SSL Certificate
, so your connection shown on the screen is not secure. So now we create an SSL Certificate
that works on localhost
. The easiest way to get an SSL Certificate
is to use a tool
called mkcert
Refer to the mkcert link to install the tool for each operating system. Here I use macOS
1 2 3 4 5 6 | # Cài đặt mkcert tool brew install mkcert # Thiết lập mkcert trên máy tính của bạn (Tạo a CA) mkcert -install |
After running the above command, you will be able to create a CA
(certificate authority) on your computer. The CA ensures that you generate many certificates
for all future projects
From the project’s root directory. Run the following command:
1 2 3 4 5 6 | # tạo thư mục .cert nếu nó chưa tồn tại mkdir -p .cert # Tạo một certificate (chạy từ thư mục root của dự án) mkcert -key-file ./.cert/key.pem -cert-file ./.cert/cert.pem "localhost" |
We will save the generated certificate
in the .cert
directory. This directory will not commit on the repo, so you need to ignore this directory in the .gitignore
file
3. Add the SSL Certificate in the start script
Next, we need to update the start script
with the newly created certificate
:
1 2 3 4 5 6 7 | "scripts": { "start": "HTTPS=true SSL_CRT_FILE=./.cert/cert.pem SSL_KEY_FILE=./.cert/key.pem react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" } |
When you run npm start
again, you should see your connection is secure and use https
at localhost
as shown below.