Using HTTPS in Development
When you're developing a website using Create React App (CRA), you might need to serve your pages over HTTPS instead of HTTP. This is especially important if you're using the "proxy" feature to send requests from your development server to an API server that requires HTTPS.
Starting the Development Server with HTTPS
To start the development server with HTTPS, follow these steps:
Open your command prompt or terminal.
Set the
HTTPS
environment variable totrue
. This tells the development server to use HTTPS.Windows (cmd.exe):
set HTTPS=true
Windows (PowerShell):
$env:HTTPS = "true"
Linux, macOS (Bash):
export HTTPS=true
Start the development server by running the following command:
npm start
After executing this command, the development server will serve your pages over HTTPS using a self-signed certificate. It's important to note that self-signed certificates are not trusted by default, so your web browser will display a warning when accessing the page. You can safely proceed past the warning to view your site.
Using a Custom SSL Certificate
If you prefer to use a custom SSL certificate instead of the self-signed certificate, you can follow these additional steps:
Set the
HTTPS
environment variable totrue
, as explained in the previous section.Set the
SSL_CRT_FILE
andSSL_KEY_FILE
environment variables to the paths of your custom certificate and key files.- Linux, macOS (Bash):
export HTTPS=true
export SSL_CRT_FILE=path/to/cert.crt
export SSL_KEY_FILE=path/to/cert.key
Replace
path/to/cert.crt
with the actual path to your SSL certificate file, andpath/to/cert.key
with the path to your SSL key file.- Linux, macOS (Bash):
Start the development server by running the following command:
npm start
With these environment variables set, the development server will use your custom SSL certificate for HTTPS connections.
To avoid having to set the environment variables every time you start the development server, you have two options:
Update the
start
script in yourpackage.json
file to include the environment variables. Here's an example of how thestart
script could look:{
"start": "HTTPS=true SSL_CRT_FILE=path/to/cert.crt SSL_KEY_FILE=path/to/cert.key react-scripts start"
}Replace
path/to/cert.crt
with the actual path to your SSL certificate file, andpath/to/cert.key
with the path to your SSL key file.Create a
.env
file in your project's root directory and set theHTTPS
variable totrue
:HTTPS=true
This approach is useful if you want to keep your environment variables separate from the
package.json
file. However, remember to keep your.env
file private and never commit it to a public repository.
For more detailed information on using environment variables in Create React App (CRA), you can refer to the official CRA documentation on adding custom environment variables.