The assumption that I am making is that you have a React app that you want to run locally with a custom domain and with HTTPS. This is useful for testing purposes, for example, if you want to test the Facebook login or if you want to test the Google Analytics integration.
According to the create-react-app
documentation, you can run your React app locally with HTTPS using the HTTPS=true
environment variable.
However, this is not enough to run your app locally with a custom domain and with certificates.
For Windows, the hosts file is located at C:\Windows\System32\drivers\etc\hosts
.
For Mac, the hosts file is located at /etc/hosts
.
Add the following line to your hosts file:
... 127.0.0.1 yourdomain.com ...
So far, we have enabled HTTPS and we have added a custom domain to our hosts file.
You can now run your React app locally with HTTPS and with a custom domain. By default, the React app will be available at https://yourdomain.com:3000
.
However, you will get a warning in your browser because the certificate is not trusted.
To fix this, we need to install a certificate on our machine. We will use mkcert to do this.
For Windows, you can install mkcert using Chocolatey:
choco install mkcert
For Mac, you can install mkcert using Homebrew:
brew install mkcert
After installing mkcert, create a folder in your root react project directory where you will store your certificates, for example, certs
.
Open a terminal and navigate to this folder. Then, run the following command:
mkcert -install
This will install the mkcert root certificate in your system's certificate store. This will allow you to use the certificates that you will create with mkcert. Finally, create a certificate for your domain:
mkcert yourdomain.com
This will create two files: yourdomain.com.pem
and yourdomain.com-key.pem
.
Add the following scripts to your package.json
file:
{ "scripts": { "start": "HTTPS=true react-scripts start", "start:cert": "HTTPS=true SSL_CRT_FILE=certs/yourdomain.com.pem SSL_KEY_FILE=certs/yourdomain.com-key.pem react-scripts start" } }
Please note the environment variable declrations differ between Windows and Mac. You can install the cross-env package to make the environment variables work on both Windows and Mac.