DEV Community

Cover image for Use environment variables in create-react-app projects
Garrone Joseph
Garrone Joseph

Posted on

Use environment variables in create-react-app projects

cra-envs is a module that help you safely bundle server environment variables into statically served React SPA.


We want to be able to do docker run --env FOO="xyz" my-org/my-create-react-app
then access FOO in the app like process.env["FOO"].

Create react app provides no official way to inject environment variable from the server into the page.

When you run yarn build create react app does bundle all the variables prefixed by REACT_APP_
and expose them under process.env (see here).

The problem, however, is that you likely don't want to build your app on the server.

For this use case the CRA team suggests to introduce placeholders in the public/index.html
and do the substitution on the server before serving the app. This solution involves a lot of hard to maintain scripting.

This module abstract away the burden of managing environment variable injection as well as providing a type-safe way
to access them in your code.

Discussion (0)