How to deploy a react app in production over https?
Asked Answered
S

2

5

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?!

Serigraph answered 4/6, 2020 at 6:37 Comment(2)
react-scripts start starts the development server. Never use that for production. To use React in production, build the project and server over a proper web server.Isolationism
Where did you find the key? I got one certificate file from the provider. Does the key the ssh key of your local computer?Vibraharp
G
13

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"
Gluck answered 4/6, 2020 at 9:26 Comment(3)
Quite late but how did you know this? I couldn't find it in the documentationYapon
@Laif For CRA right here create-react-app.dev/docs/…. For serve you run serve --help to get a list of CLI optionsGluck
serve documentation is very very badBurp
G
0

Something to keep in mind regarding env variables in the build process.

Note: You must create custom environment variables beginning with REACT_APP_. Any other variables except NODE_ENV will be ignored to avoid accidentally exposing a private key on the machine that could have the same name. Changing any environment variables will require you to restart the development server if it is running.

React documentation

Gorlin answered 6/7 at 22:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.