Search code examples
node.jsreactjshttpsenvironment-variablesproduction

How to deploy a react app in production over https?


I have a React App that works beautifully over HTTPS using a .env.production file containing:

HTTPS=true
SSL_CRT_FILE=/etc/ssl/certs/mycert.crt
SSL_KEY_FILE=/etc/ssl/private/mykey.key

the package.json file contains:

"scripts": {
   "start": "env-cmd -f .env.production react-scripts start",
   "build:production": "env-cmd -f .env.production react-scripts build"
}

when I do:

npm start

everything works, and I can access my server over HTTPS from anywhere. Now, this is the funny thing, now I do:

npm run build:production

which also works fine, and I get:

The build folder is ready to be deployed.
You may serve it with a static server:

serve -s build

Now, this is what fails:

1) When I use the serve command above, the environment variables in the .env.production file are not picked up! Why?

2) If I pass the environment variables manually as in:

HTTPS=true SSL_CRT_FILE=/etc/ssl/certs/mycert.crt SSL_KEY_FILE=/etc/ssl/private/mykey.key PORT=8580 serve -s build 

Only the PORT variable seems to be picked up, but the server now runs on HTTP. Any ideas why?!


Solution

  • When you run npm start, a development server is started for you under the hood that is configured to pick up the SSL_CRT_FILE, SSL_KEY_FILE and HTTPS env vars automatically.

    serve doesn't do that, you need to let it know with these CLI flags:

    serve -s build --listen 8580 --ssl-cert "/etc/ssl/certs/mycert.crt" --ssl-key "/etc/ssl/private/mykey.key"