create-react-app icon indicating copy to clipboard operation
create-react-app copied to clipboard

Runtime environment variables

Open kmalakoff opened this issue 7 years ago • 80 comments

Regarding this pull request around the improvements to environment variables, based on @gaearon's suggestion, I wanted to start a discussion on how to handle a docker-centric, 12 factor app-based workflow where environment variables are provided externally at runtime rather than at build time so that the exact same assets can be run in multiple environments.

Constraints / design goals mentioned is:

It's important though to note that CRA always produces static bundles, and they are expected to work in any environment regardless of server, container, etc.

In the past, I have implemented the following two solutions:

  1. render environment variables into the HTML and then hoist them into an application at initialization
  2. fetch environment variables from a server (for example, before creating the store and rendering the app with some static content during the initial fetch)

The first solution's benefit is that there is no delay before initial render, but with create react app dynamically modifying the html file, it becomes a little more tricky to implement since you would need to parse or search / replace within the rendered html before serving the file.

I'm just wondering if there is a better / best way to provide runtime environment variables to CRA applications and if we can get agreement on an approach, if it can be integrated into the CRA pipeline.

Thank you for all the great work and hoping for something awesome here! :pray:

kmalakoff avatar May 24 '17 17:05 kmalakoff

Environment variables have to be compiled in because things like NODE_ENV lead to tons of dead code elimination, so whatever solution you're looking for will probably need to coexist with env vars as they are today.

And I feel like you've hit the right solution: a script tag in the head of public/index.html that defines the variables, either inline or as an external js file. You've got the tradeoffs right as well; an extra request vs a slightly more complex release-creation process. Really not hard to do today, and in my opinion out of the scope of create-react-app. What's wrong with just rebuilding for configuration changes?

But if we're brainstorming...

Maybe env vars could somehow be denoted as being dynamic/runtime injected. A prefix of REACT_APP_RUNTIME or something. They get compiled into global variable references, something like window.runtimeEnvVars.<varname>, and instead of an index.html you get an index.html.template and a little script that can combine your partial build with a .env configuration into a full release.

heyimalex avatar May 25 '17 23:05 heyimalex

Interesting and totally understand if this might be out scope for CRA.

The main problem is that when I consult, I need to tell clients who deploy via docker and 12 factor app principles to ignore the environment variable solution in CRA which is a bit confusing since one would expect that CRA's environment variables solution would meet this common use case. To be honest, I'm actually not sure of why anyone would want build time environment variables, but it could be that I've been using and advocating for 12 factor app principles to clients for too long...

In your brainstorming ideas, is there a way to inject code into the CRA index.html at runtime currently? If not, that sounds like an interesting line of potential solutions.

kmalakoff avatar May 26 '17 01:05 kmalakoff

What's wrong with just rebuilding for configuration changes?

@heyimalex: for instance if you deploy your apps using docker, having to rebuild the app for configuration changes has some drawbacks:

  • you have to include node and all the build toolchain in your image
  • the startup time for your container increases significantly
  • your container resource requirements increase significantly

Proposal

I suggest an approach similar to the one I used for sd-builder, a tool conceptually very similar to CRA that I've built back when CRA didn't yet exist (and that I would like to discontinue in favour of CRA).

sd-builder's approach

In apps built with sd-builder, configuration is loaded from a file - app-config.js - that you include in your app's index.html. The file defines the global variable window.APP_CONFIG, which holds the configuration object.

During development, the sd-builder dev server generates the file from the variables listed in the .env file.

sd-builder also provides a command - sd-builder config - to generate the file from (scoped) environment variables.

Creating the production bundle is therefore a two-step process:

  • first you run sd-builder build, that builds the app
  • then you run sd-builder config, which only generates the configuration file

When deploying with docker, you'd typically run the first step when building the docker image, and the second step when running the container.

This solves the last two drawbacks listed above. It doesn't solve the first one because you still need sd-builder to generate the config file, but that could be remedied by extracting the generation logic (30 lines of js) into a separate, smaller utility (maybe even with a C/bash port to cut down on runtime dependencies).

Suggestion for CRA

The above approach could be used in CRA without touching CRA. You add app-config.js in your index.html and develop a script that:

  • during development, you run before react-scripts start. The script generates app-config.js from .env, and places it in the public/ folder (I guess you should then .gitignore it)
  • at "production runtime", you run before starting your static server. The script generates app-config.js from environment variables and places it in the build/ folder

However this approach has some issues:

  • it's a bit hackish
  • it doesn't allow to use environment variables in index.html
  • it cannot be used to set process.env.PUBLIC_URL at runtime (and PUBLIC_URL feels to me like a runtime variable)

So I would suggest to bring that behaviour into CRA: in development, by making react-script start generate the config file and the configured index.html, in non-development, by providing a react-script config script that does it. (You could actually do without app-config.js, and simply embed the configuration in the index.html).


Thoughts? (@kmalakoff @gaearon @Timer)

pscanf avatar Jun 07 '17 17:06 pscanf

Here's a build script to do this. Usage:

  • Define some variables in your .env with the prefix REACT_APP_RUNTIME_
  • Run the build script. It should run the regular react-script build process and create an extra file in the build directory called gen-index.js.
  • Run that gen-index script with your runtime env vars set and it'll generate an index.html with those variables defined.

It's pretty hacky but should be a good proof-of-concept for how the experience could be.

  • ✔️ Development mode works exactly the same as today: runtime variables are only aliased in production builds.
  • ✔️ Build-time env vars are not going away, so any new runtime configuration system must coexist with what's already there. This strategy allows users to opt in without breaking the old system or creating an entirely new separate system.
  • ✔️ Rebuilding the index is fast.
  • ✔️ All of the static assets are still static.
  • ❌ Doesn't do PUBLIC_URL. Didn't try it, haven't put any thought into it.
  • ❌ It's one more thing to think about. How many people would really use this feature? How much confusion could it cause? Does this get in the way of wider uses of env vars?
  • ❌ This current take is hacky, relies on string replacement/manipulation and so may not be hygenic, messes up source maps, messes up file hashes. All of that can be fixed with enough work I think. Which brings me to...
  • ❌ With enough work, someone could do this safely as a separate package.

heyimalex avatar Jun 07 '17 23:06 heyimalex

I ended up here as was struggling with this too but since found a different solution. I'd be interested to know if it violates the any best practices, 12 step principles or if there are any security concerns.

  • I Set up a small express server to serve the static app, plus one api route called /config. When the app is run a json object is created with the whitelisted variables pulled from the environment, or defaults.
  • In the react app I made a higher order component withConfig() that fetches from the /config route and provides the result as props to the wrapped component.
  • To make this work in dev mode I set the proxy in package.json to point to the express server. This means in dev mode I have to start both the express server (npm start) and dev server (react-scripts start).

Here's a gist

hoolymama avatar Aug 04 '17 18:08 hoolymama

@hoolymama thanks for the gist. I've been struggling with this problem in few projects and IMHO it's crucial to be able to specify environment variables for configuring the application.

Although it might not be in scope for CRA, it would be nice to unify some approach and be able to use it without and further setup needed.

jakubknejzlik avatar Aug 07 '17 06:08 jakubknejzlik

I solved this for my current project, which is ejected, by conditionally passing in config via /config/env.js:getClientEnvironment():

function getClientEnvironment(publicUrl) {
  // Code...
  NODE_ENV: process.env.NODE_ENV || "development",
  PUBLIC_URL: publicUrl,
  CONFIG: process.env.NODE_ENV === "development" ? config : "" // Only for development
  // Code...
}

This fixes it for local development.

I also inject config into a script block in index.html on the server (Express or Koa).

Then in my Config component I look for config on the window object OR in process.env.CONFIG.

I then control which config to use with CONFIG_ENV=ci|staging|whatever yarn dev|serve.

It's not perfect, but it fixes it for us and we can now promote our staging build to production on Heroku without rebuilding.

adrianblynch avatar Aug 23 '17 13:08 adrianblynch

Update from a user

For those who might be interested, I've built a static server "specialized" for serving and configuring at runtime create-react-app apps: staticdeploy/app-server. It also allows for an easy "dockerization" of the apps.

To allow runtime configuration, it just uses an alternative configuration mechanism. So it doesn't work out-of-the-box with create-react-app, but making it work is simply a matter of adding a script tag to public/index.html, so it's not too bad.

When serving the files, I also implemented some best-match redirects to allow the app base url (PUBLIC_URL) to be configured at runtime as well.

pscanf avatar Sep 21 '17 21:09 pscanf

How about rewriting withimmutable-js?

sr1994lu avatar Oct 08 '17 06:10 sr1994lu

My big concern with some of the solutions is - I'd like to be able to host my app on a CDN that only serves static files, whilst at the same time I'd like to know that the software deployed to Dev, QA, PreProd and Prod are all the same.

If I'm needing to dynamically generate files on startup, that fails the CDN requirement. If I'm needing to rebuild the entire application in order to deploy into different environments, that fails the QA/PreProd/Prod requirements.

The idea of having an app-config.js file that is deployed alongside the built application is the best I can think of so far. It means that the entire application is built once, and on deployment that file is added alongside it for deployment-specific details - such as backend URLs to call. It is another moving part to think about though, but not a very big one. It can probably be done in the Docker setup using just shell scripting as well, not needing a complex setup. Just a bunch of echo statements into a well-known filename passing in environment variables.

sazzer avatar Dec 21 '17 17:12 sazzer

@sazzer can you be more specific how does it fails the CDN requirement? Is it the recommendation of static content, which can be change just by changing the environment variables?

jakubknejzlik avatar Dec 21 '17 18:12 jakubknejzlik

@jakubknejzlik The CDNs that I've looked at serve up static files. They don't let you run server processes to dynamically generate content. This would mean that the files that are served to the browsers need to be the files that are uploaded, as-is.

What I'm really hoping for - but feeling less and less hopeful about - is a process similar to:

  • Change is made to source code
  • Ci system builds the code
    • CI system automatically runs "npm test"
    • CI system automatically runs "npm run build"
    • CI system automatically puts a copy of the "build" directory into our artifact repository
    • CI system automatically deploys this latest build to the Dev system
  • At some point, an artifact is deployed to QA
    • The appropriate artifact is picked from the repository and deployed as-is to the QA systems
  • At some point, an artifact is deployed to PreProd
    • The appropriate artifact is picked from the repository and deployed as-is to the Prod systems
  • At some point, an artifact is deployed to Prod
    • The appropriate artifact is picked from the repository and deployed as-is to the Prod systems

For the backend - which is a Java app - this is really simple. The Java process can be run with system properties on a per-environment basis to provide the appropriate config - database credentials right now - but the actual files deployed are identical from one environment to the next.

For the frontend, because it's CRA which produces static files, this is not so easy.

The best I've been able to come up with so far is for the frontend deployment to be:

  • The frontend artifact contents
  • Another file dropped next to index.html that contains the appropriate configuration needed.

This technically means that the deployment onto each environment is not the same, but it's as close as I can make it right now. This means that I can't guarantee that the deployment to Prod will work just because it passed all of the tests at the earlier stages. (And no, technically I can't guarantee that with the backend with its environment properties, but it's a lot easier to manage and verify that. Start service, call healthcheck endpoint, on failure rollback.)

sazzer avatar Dec 21 '17 19:12 sazzer

Is there anything we need to do on our side for this? I don't understand from reading this issue.

gaearon avatar Jan 08 '18 20:01 gaearon

Put bluntly: If we start a container/webserver w/some static js compiled through CRA, we would like e.g. PUBLIC_URL to be able to be set at runtime by the orchestration/webserver, not at build time.

The-Loeki avatar Feb 22 '18 10:02 The-Loeki

Hi everyone, I just wanted to chime in with my current workaround, adapted from some comments above (pscanf's and heyimalex's):

  • Create build-env.js with the following contents:
// adapted from https://github.com/facebook/create-react-app/issues/2353#issuecomment-306949558
if (!process.env.NODE_ENV) {
  process.env.NODE_ENV = 'development'
}

// clientEnv is generated this way because we don't want to expose all of process.env,
// since it contains secrets (private API keys, etc)
const clientEnv = require("react-scripts/config/env")().raw;

console.log(`
// Auto-generated by build-env.js, DO NOT EDIT
window.process = { env: ${
  JSON.stringify(clientEnv, null, 2)
}}`.trim())
  • Add <script src="%PUBLIC_URL%/env.js"></script> to the <head> of public/index.html
  • If you're using a dynamic server, ensure it serves the /env.js path. For Express, this looks something like:
app.get('/env.js', function (req, res) {
  res.sendFile(path.join(__dirname, 'build', 'env.js'))
})
  • Configure your server to run the following on startup (e.g. the prestart script in package.json:
node ./build-env.js > build/env.js
  • Finally, in your component/etc files, replace process.env with __process.env and add the following at the top:
const __process = (typeof global !== 'undefined' ? global : window).process

This has the same downsides @pscanf mentioned:

  • it's a bit hackish
  • it doesn't allow to use environment variables in index.html
  • it cannot be used to set process.env.PUBLIC_URL at runtime (and PUBLIC_URL feels to me like a runtime variable)

as well as the __process variable thing, but it works well enough for me.

josephfrazier avatar Feb 22 '18 20:02 josephfrazier

We set the PUBLIC_URL and some other stuffs we know are configurable to e.g. PUBLIC_URL_REPLACE_ME and do some good old fashioned sed to 'fix' it in the init script ;)

Very Dirty (c) but functional

The-Loeki avatar Feb 28 '18 18:02 The-Loeki

@The-Loeki I think that potentially breaks sourcemaps and caching in weird ways. Even if you take out the service worker stuff, you have to remember to not set far future cache headers on /static/{css,js}/*, since your find-replace could make them not-so-static (which also means you're not getting the benefits of static asset caching). There are ways to fix this but they just add more complexity...

heyimalex avatar Feb 28 '18 18:02 heyimalex

We only serve the statically generated files, no nodejs & such; for PUBLIC_URL we traverse all builded files to fix them.

The one thing you have to be aware of regarding caching besides the headers is to not use relative URLs; they warn about that somewhere in the code.

The-Loeki avatar Feb 28 '18 18:02 The-Loeki

@The-Loeki Everything in /static/ has a content hash appended to the filename so that you can safely set far-future caching headers. When you modify those files using sed, the contents change but the hashes don't. That means if you accidentally release with the wrong PUBLIC_URL, fix it and then release again, everyone who already got the bad build will continue to see that build until their cache expires or is cleared. Same idea with the service worker I think. Just something to consider!

EDIT: But thinking about it more, if PUBLIC_URL is wrong, the files won't be loaded in the first place. So maybe this is not actually an issue? 🤷‍♂️

heyimalex avatar Feb 28 '18 19:02 heyimalex

héhéhé I'm actually pretty sure that that is an issue, albeit a very minor one; our devs have had to force-reload their browsers regularly while moving the app around.

OTOH while I do strongly support it being a runtime configurable, it's not like it's going to move every day.

So thanks for pointing it out because we've been a bit suprised by the behaviour, but not overly bothered by it.

I might cook up some nasty-ass fix for it as well, but don't wait up for it ;)

The-Loeki avatar Mar 01 '18 12:03 The-Loeki

I solved this using a hackish solution here https://stackoverflow.com/questions/51653931/react-configuration-file-for-post-deployment-settings

ideally there would be a clean native way (i.e import a js file that doesn't get bundled) but this is a good work around.

SpacePotatoBear avatar Aug 02 '18 14:08 SpacePotatoBear

@SpacePotatoBear I like your model/workaround. I currently do it based on the URL the client is accessed from - posted an example in your thread:

https://stackoverflow.com/a/51663697/1959584

lirbank avatar Aug 03 '18 00:08 lirbank

A native way of having runtime environmental variables would be very helpful when deploying in Dockerised environments (e.g. Kubernetes) and following a 12-factor app approach, specifically https://12factor.net/build-release-run

alexvicegrab avatar Oct 05 '18 21:10 alexvicegrab

Create React App runtime environment variables are much needed for containerized environment. Currently once its built there is no way to change environment variables. However there are some workaround like using additional config.js file and read from there. Even it's still file that need to be modified. In containerized environment everything should be setup by environment variables, not through some file. We've come very close to better solution. Idea is instead of reading from process.env, actually you can read from external url with get request. In response for get request there would be little nodejs server that returns its own process.env file's value which can be configured at runtime.

Note: I'm not JS developer, our guys hacked together this solution in our environment. Hope it helps someone.

shinebayar-g avatar Nov 09 '18 10:11 shinebayar-g

@shinebayar-g that's exactly where we've ended up too but in slightly different way. We created docker wrapper image that just during the container start creates js file with values from process.env ("REACT_APP_*" only; assigned to window.ENV) and starts nginx. Not sure if it works, but maybe it could help someone :-) https://github.com/inloop/cra-docker

jakubknejzlik avatar Nov 09 '18 10:11 jakubknejzlik

@jakubknejzlik I see, but your solution works when someone write their value into .env file itself right? If that's right, it's 1on1 scale right? But still big advantage is you don't have to rebuild image? In our case we had to use one base image for every other website. Also it has advantage of not writing anything into .env file itself but read it from ENVIRONMENT VARIABLEs.

shinebayar-g avatar Nov 09 '18 12:11 shinebayar-g

@shinebayar-g nope, this line: https://github.com/inloop/cra-docker/blob/master/entrypoint.sh#L1

is basically generating the env.js file with contents from env command and filters it for REACT_APP_*. This happens every time the container starts so it should contain the environment variables.

jakubknejzlik avatar Nov 09 '18 12:11 jakubknejzlik

@jakubknejzlik , Just realized your genius idea haha. Your solution is actually instead of serving additional nodejs, you can actually do it on nginx itself, did I got it?

shinebayar-g avatar Nov 10 '18 17:11 shinebayar-g

Yes, you just update the file on startup and serve it as static file with plain nginx. Not sure if genius, but it works 😏

jakubknejzlik avatar Nov 10 '18 18:11 jakubknejzlik

Today we completely dropped our additional nodejs server for in favor of nginx implementation of your example. With little modification in our end, it worked like a charm! I think this is current best work around for runtime environment variable. Thanks for docker image and scripts.

shinebayar-g avatar Nov 12 '18 15:11 shinebayar-g

@jakubknejzlik When I try to run your entrypoint.sh it outputs a "env.js?" Any idea what might be happening?

bjrb20 avatar Jan 16 '19 11:01 bjrb20

@SpacePotatoBear I like your model/workaround. I currently do it based on the URL the client is accessed from - posted an example in your thread:

https://stackoverflow.com/a/51663697/1959584

That is a very simple and elegant solution. Thank you for sharing. Implemented in 5 minutes. But in my case the environment URL is also a deployment variable, so I just added extra JS file (let's say 'env.js') to the code which is an access point to the the run-time config which identifies the environment (with process.env.NODE_ENV) and exports related configuration. So I just import env.js wherever I need config variables and use it.

koshkarov avatar Jan 26 '19 17:01 koshkarov

@BenRedmondBenham the entrypoint is supposed to be run as entrypoint in docker container. Checkout this repository where we use this image/approach:

https://github.com/graphql-services/graphql-credentials-admin/tree/develop?files=1

jakubknejzlik avatar Jan 26 '19 21:01 jakubknejzlik

My view is that probably the cleanest way to achieve this kind of JS bundle portability across environments, in a docker-centric and 12-factor app kinda workflow, is some variation of the first item mentioned by @kmalakoff:

  1. render environment variables into the HTML and then hoist them into an application at initialization

And the general technique for getting there suggested by @jakubknejzlik:

echo "window.ENV = `jo \\`env | grep REACT_APP_\`end=1`" > env.js

Is great.

I like the idea of modifying the HTML page instead of modifiying or adding a JS file, because this avoids the problems with caching and the content hash mentioned by @heyimalex.

Example

I'm going to use a different prefix, JS_BUNDLE_RUNTIME_CONFIG_, so that it's obvious that these are different than the REACT_APP_ -prefixed environment variables that are interpolated at build-time.

Set config values in environment variables

export JS_BUNDLE_RUNTIME_CONFIG_API_URL="api.dogs.com"
export JS_BUNDLE_RUNTIME_CONFIG_ANALYTICS_URL="analytics.dogs.com"

Put those environment variables into a JSON string

# requires https://github.com/jpmens/jo
PREFIX="JS_BUNDLE_RUNTIME_CONFIG_"
CONFIG_JSON=$(jo $(env | grep "$PREFIX" | cut -c $(expr ${#PREFIX} + 1)-))
    
echo $CONFIG_JSON
# {"ANALYTICS_URL":"analytics.dogs.com","API_URL":"api.dogs.com"}

Templatized public/index.html

<body>
    <div id="root"></div>
    <script type="application/json" id="js-bundle-runtime-config">
      {{ JS_BUNDLE_RUNTIME_CONFIG }}
    </script>
</body>

Note: I've stuffed the values into a non-JS script tag, to avoid polluting the window with additional variables, and we'll parse the JSON from within the bundle. But as variables on the window would be fine too!

Inject the config

sed -i "s/{{ JS_BUNDLE_RUNTIME_CONFIG }}/$CONFIG_JSON/" build/index.html

WHEN does this happen? If you're in a docker container, right when the container starts up. But to @sazzer's point about CDNs, if you're just sending the static files off someplace, you could also do this after the build, at the moment of deployment.

What gets sent to the browser

<body>
    <div id="root"></div>
    <script type="application/json" id="js-bundle-runtime-config">
      {"ANALYTICS_URL":"analytics.dogs.com","API_URL":"api.dogs.com"}
    </script>
    <script src="my-bundle.min.js"></script>
</body>

Consume the config from inside your bundled source

function getRuntimeConfig() {
    return JSON.parse(
      document.getElementById('js-bundle-runtime-config').innerHTML
    );
}
    
const config = getRuntimeConfig();
    
console.log(config);
// {"ANALYTICS_URL":"analytics.dogs.com","API_URL":"api.dogs.com"}

Summary

The bundle is the exact same artifact across environments, but the HTML that references the bundle gets tweaked per-environment.

This comment already has become quite long, but I wrote a more detailed post on the topic also discussing how to deal with local development (TLDR: webpack string-replace-loader to inject the JSON).

One final thought: I don't think providing this kind of solution really falls under the responsibility of create-react-app, but I also totally agree with @kmalakoff in that I don't understand what use cases exist where it'd be beneficial to use the build-time environment variable interpolation mechanism compared to something like this. Is there anything I'm missing? (I also get that the build-time environment variable stuff isn't gonna go away, just wondering! :D )

stuartsan avatar Feb 25 '19 19:02 stuartsan

I think your solution works well.

The use case for build time environment variables is that their values can be used during optimization. For example, all code wrapped in if (NODE_ENV === “development”) blocks is actually removed from the bundle in a production build. This is why React development builds are significantly slower than production builds.

heyimalex avatar Feb 25 '19 20:02 heyimalex

@heyimalex, I should have been more specific: I don't get when it'd be more beneficial to use the mechanism of REACT_APP_-prefixed environment variables at build time, for the use case described by the docs as:

displaying information conditionally based on where the project is deployed or consuming sensitive data that lives outside of version control.

stuartsan avatar Feb 25 '19 21:02 stuartsan

Some time ago, I've written detailed blog tutorial which solves this issue:

https://medium.freecodecamp.org/how-to-implement-runtime-environment-variables-with-create-react-app-docker-and-nginx-7f9d42a91d70

kunokdev avatar Mar 26 '19 20:03 kunokdev

For anyone wrestling with this problem I have just created a helper package on NPM to make the process a little easier. It has some scripts and documentation on how to use it. However, I would really love some feedback and any PRs are welcome if you think this is a useful package.

https://www.npmjs.com/package/@ethical-jobs/dynamic-env https://github.com/ethical-jobs/dynamic-env

P.S. kudos to @kunokdev as this is based on his blog article above.

developerdino avatar Apr 16 '19 05:04 developerdino

Ok, even easier then that:

We created a repository / Docker image that generates a env.js file from your environment variables as per the CRA docs.

See: https://github.com/beam-australia/create-react-env

Uses a small Golang binary to build your env vars into JS. Based on the alpine-linux nginx image. Comes in at only 10mb. Now you can statically run your CRA and have runtime env vars!

andrewmclagan avatar May 27 '19 08:05 andrewmclagan

Definitely use @andrewmclagan implementation over the one I created. It is a much better implementation.

developerdino avatar May 30 '19 06:05 developerdino

https://medium.com/@andrewmclagan_64462/runtime-environment-variables-create-react-app-84f7c261856c

andrewmclagan avatar May 31 '19 05:05 andrewmclagan

Just wanted to share my experience in case it helps someone. My specific case is that I'm trying to containerize my react app and my requirements are:

  1. I need to use nginx or other http servers I choose, I can't be tied to serving using node
  2. I need to be able to change my deployment env vars, restart the container/pod/etc and my changes should be picked up

After experimenting with some of the solutions here and elsewhere I come to believe that I actually don't require anything else from CRA -- processing the env vars at build time is the right thing to do and I should embrace that instead of trying to workaround it.

I don't know the other use cases but for me what I needed was in the context of being able to containerize my app and be able to change its env vars at deployment/env side.

So here is what I'm thinking of. Basically, I'd have a standard Dockerfile, the twist is that I'd only install the needed dependencies but it would not build the project yet, the custom entrypoint.sh would take care of that:

FROM node:12.2.0-alpine

# Copy project, install dependencies, etc, but do NOT build yet
# ...

RUN chmod +x entrypoint.sh
ENTRYPOINT [ "entrypoint.sh" ]

I didn't complete entrypoint.sh but its comments should tell you where I'm going with this:

#!/bin/sh
# This is what I have now, but just to get the entrypoint script going, I'd replace it
# with implementation of the comments below
yarn --silent clean:all && yarn --silent build
yarn --silent start

# What this needs to do in the future is
# 1. Capture REACT_APP_* env vars
# 2. Hash them and compare to their previous hash, if they differ:
#   a. Clean and rebuild
#   b. Store the new hash
# 3. Serve using nginx/etc

The disadvantage I see in this approach is that the image size is larger than if we just bundle the build using e.g. a multi-stage build. It also means the container maintains state (the env vars hash in entrypoint) but I think it's a caching mechanism, deleting the state won't do much harm. I'm still toying with this and didn't actually use it in production yet. Any feedback welcome!

amr avatar Jun 16 '19 09:06 amr

@amr we’ve been using this way too. But with rising number of project the cost of initial resources to even bring up the app was too high. It’s worth saying that we are not using the SSR so running application is matter of few megabytes of ram and fraction of cpu. Also startup times are <5s. In case of downloading dependencies and building the project we needed 1-2CPUs, ~2GB or ram and initial boot around ~5minutes...which was not acceptable (especially when using stuff like kubernetes properly).

jakubknejzlik avatar Jun 16 '19 10:06 jakubknejzlik

@jakubknejzlik the optimization of building only when env vars change (outlined above) should mitigate that a lot, because it would mean booting is very fast except the first time after you change env vars

amr avatar Jun 16 '19 10:06 amr

@amr no to be honest. We had a lot of commits and keeping the build phase in CI and not in production cluster felt more resource wise :).

jakubknejzlik avatar Jun 16 '19 11:06 jakubknejzlik

Honestly we were suffering from building at run-time also. Our create-react-app pods in our Kubernetes cluster required huge resources to build.... but almost nothing to run. So it was costing us a ton more then was needed. This is why we wrote: https://github.com/beam-australia/react-env it builds the environment when your app or container starts. Populating a window._env object with your white listed REACT_APP_FOO env vars. You can then access them directly or use a provided helper:

import React from 'react'
import env from '@beam-australia/react-env'

// Using the helper function:

const Example1 = () => <div>{env('FOO')}</div>

// Access the entire whitelisted environment object:

const Example2 = () => <div>{JSON.stringify(env())}</div>

// Or directly access a env var:

const Example3 = () => <div>{window._env.REACT_APP_FOO}</div>

If you are using Next.js react-env also supports server rendering. Your env vars will be accessible through the env() helper client and server-side. There are examples in the repo.

There is currently a PR to update the documentation on this approach.

andrewmclagan avatar Jun 17 '19 00:06 andrewmclagan

Thank @josephfrazier & @jakubknejzlik 🙇 I combine your solutions with tiny customization to make it work for me. Now I can be happy with Reactjs on my k8s cluster.

VietTD avatar Jun 17 '19 04:06 VietTD

Thanks all for these solutions. Based on one of them, I've built a small tool in Go that creates an env-config.js based on the withe listed variable in .env file. It allows building a distroless Docker image (24MB) that embeds the whole mechanism.

I also wrote a blog post to explain how it works. Thanks again to @jakubknejzlik for the initial source of inspiration :-)

dmetzler avatar Aug 07 '19 07:08 dmetzler

It's really annoying that react-scripts can't allow a dynamic public/index.html.js template function

Here are the 2 ways I've found to have a dynamic index.html template:

The first one is quick-and-dirty, using a regexp and build/index.html, example in your server.js:

const indexHtml = fs.readFileSync('./build/.index.html', 'utf-8');
const m = indexHtml.match(/<\!--placeholder-->/);

app.get('/*', (req, res) => {
    const html = `${indexHtml.slice(0, m.index)}${/* inject whatever here */}${indexHtml.slice(m.index + m[0].length)}`
    res.send(html);
});

Seconds way, you would eject or use a custom webpack config, then customize HtmlWebpackPlugin to do this: in webpack.config.prod.js

        new HtmlWebpackPlugin({
            templateParameters: (compilation, assets) => {
                // write to disk on the root level a ._assets.json file, used by server.js
                // it's similar to build/asset-manifest.json, except only js/css and more importantly in loading order
                // https://github.com/jantimon/html-webpack-plugin/issues/982#issuecomment-398665019
                fs.writeFileSync('._assets.json', JSON.stringify(assets));
            },
            template: './index.html.js',
            filename: 'index.html',
            inject: false
        }),

in webpack.config.dev.js

        new HtmlWebpackPlugin({
            template: './index.html.js',
            filename: 'index.html',
            inject: true,
            foo: process.env.FOO
        }),

index.html.js

module.exports = ({
    foo, // just for example
    js = [],
    css = []
} = {}) => `<!DOCTYPE html>
<html lang="en">
<head>
  ...
  ${css.map(url => `<link href="${BASE_PATH + '/' + url}" rel="stylesheet">`).join('')}
</head>
<body>
  ....
  ${js.map(url => `<script src="${BASE_PATH + '/' + url}"${nonce}></script>`).join('')}
</body>
</html>`;

then in server.js

const indexHtml = require('./index.html'); // your index.html templating function
const assets = require('._assets.json');

// ....
app.get('/*', (req, res) => {
    const html = indexHtml({
        foo: 'bar',
        ...assets // contains {jsAssets: Array<String>, cssAssets: Array<String>}
    });
    res.send(html);
});

but both ways are not easy as you can see

After reading comments up there, I think the public/env.js approach is short, but more limited (you can't template non-js things, like a <link ... href="${dynamicUrl}">

caub avatar Sep 04 '19 16:09 caub

you really dont need one.

andrewmclagan avatar Sep 08 '19 11:09 andrewmclagan

Here's what I've done in a recent app:

// fragile and ugly way to inject dynamic vars in index.html, see https://github.com/facebook/create-react-app/issues/2353
const mEndOfHeadIndex = indexHtml.match(/<\/head>/).index;
const mAppContainerAttributesIndex = indexHtml.match(/(?<=id="app")>/).index;

const indexTemplate = ({
  appId = process.env.REACT_APP_ID || '',
  apiUrl = process.env.REACT_APP_API_URL || ''
} = {}) => `${indexHtml.slice(0, mEndOfHeadIndex)}<link rel="stylesheet" href="${process.env.PUBLIC_URL || ''}/customers/${appId}/style.css" />${indexHtml.slice(mEndOfHeadIndex, mAppContainerAttributesIndex)} data-app-id="${appId}" data-api-url="${apiUrl}"${indexHtml.slice(mAppContainerAttributesIndex)}`;

You could of course load that stylesheet and those variables from client-side, but it"s more requests, more loading time, ..

caub avatar Sep 08 '19 19:09 caub

@andrewmclagan's library is almost perfect but I used it slightly different to how the docs recommend (I wanted this to be as lean as possible):

  1. Add <script src="%PUBLIC_URL%/env.js"></script> to public/index.html
  2. Install andrew's lib yarn add @beam-australia/react-env
  3. Modify the start script to be react-env --dest public && react-scripts start
  4. Modify your serve script (we use serve) to be react-env --dest build && serve -s build
  5. Use window._env.REACT_APP_* variables in your app instead of process.env.REACT_APP_*

I had to forgo using the "prestart" script because development/production have different destinations, and I really didn't want to use the docker image provided as we have our own.

I also didn't want to use a library to get the variables since all it really does is put them on window._env.

All and all this is working really well. I'm using it in multiple environments:

  • Local dev using docker-compose
  • Remote dev using k8s + skaffold
  • and in Production using k8s

ashconnell avatar Nov 18 '19 21:11 ashconnell

@ashconnell great! the docker image was mainly there as a guide to building your own. Feel free to write a PR if you think the docs could be clearer. Also considering a env.json PR that is open at the moment for static deployments.

https://github.com/beam-australia/react-env

andrewmclagan avatar Nov 18 '19 23:11 andrewmclagan

@andrewmclagan I've been trawling through many different 'solutions' to no avail, but after tearing your repo and examples apart, I've finally managed to get runtime environment vars working in my react app being hosted by ASP.NET Core 3x in Linux Containers for Azure App Service. Your solution has saved me tons of time and hassle messing with baking in vars at build time by hydrating ENV and ARG in my dockerfiles etc. Much thanks!

DanoThom avatar Jan 09 '20 10:01 DanoThom

@ashconnell and @andrewmclagan "thank you very much" for this, great job my friends. You guys are rockstars :)

arvtiwar avatar Feb 19 '20 00:02 arvtiwar

I've build an utility app that helps to create js file with environment variables. It provides small sized binary cli app (500kb-2Mb depending on edition and platform) with some config options. https://github.com/SkeLLLa/env2js

The idea is pretty much same as in https://github.com/beam-australia/react-env or https://github.com/dmetzler/go-deploy.

But I've made it little bit configurable and cross-platform (macos builds coming soon). So you can use it for local development and inside docker. Also as it's compiled binary it doesn't require node, so your containers will be small.

SkeLLLa avatar Feb 22 '20 21:02 SkeLLLa

All of the proposed solutions do seem to work for user-defined variables. However, and if I understood correctly, none of them allow for PUBLIC_URL to be overwritten after building the app, which renders all options unsuitable when hosting the app through a CDN on multiple environments.

If this is the case, has anyone reached a solution for it? Is the only option to have distinct builds per environment currently?

PedroGuerraPT avatar Feb 27 '20 16:02 PedroGuerraPT

@PedroGuerraPT : app-server also allows you to set PUBLIC_URL dynamically.

You just need to set PUBLIC_URL to ./ during the build stage, so that all generated links are relative. At serve time, the asset-serving algorithm is smart enough to figure out which asset to serve, even if requests do not perfectly match its path (detailed explaination).

pscanf avatar Feb 27 '20 21:02 pscanf

@pscanf : The problem is that the application is already being served by the CDN, which only hosts static content and does not allow any command to be executed (therefore, not allowing app-server to be started). Any solution that requires a custom server to be launched is not suitable for our scenario, I'm afraid.

PedroGuerraPT avatar Feb 28 '20 11:02 PedroGuerraPT

@PedroGuerraPT from my understanding You don't have any runtime (as CDN is serving static files) and You expect to propagate runtime environments...which don't make much sense :) . Unless your CDN provider offer any sort of code execution (eg. Cloudfront's Lambda@Edge) you need to build your app or change uploaded static files during deployment anyway.

jakubknejzlik avatar Feb 28 '20 12:02 jakubknejzlik

@jakubknejzlik, maybe the "runtime" term is not appropriate for my objective. The intent is really just to separate the app config (.env) from the code, not change the values during runtime.

As far as I'm aware, and other comments are mentioning the same, the point is that PUBLIC_URL cannot be overwritten any other way besides changing its value in the .env file before building the project.

The proposed solutions on this issue do work for user-defined variables, but not for PUBLIC_URL or other Advanced Configuration variables.

Having a distinct build per environment just because of one variable doesn't seem right.

PedroGuerraPT avatar Feb 28 '20 13:02 PedroGuerraPT

You could try setting the __webpack_public_path__ magic variable.

heyimalex avatar Feb 28 '20 16:02 heyimalex

One of the reasons why PUBLIC_URL can't be set in run-time is that CSS url function doesn't support dynamic values: https://stackoverflow.com/questions/858782/dynamic-urls-in-css-js

This means you have to use relative values. But relative paths can't be used because CRA/Webpack replaces relative URIs with root-defined URIs. So that this:

.myClass { background-image: url('../images/image.png'); }

becomes something like this:

.myClass { background-image: url('__PUBLIC_URL__/static/media/images/image.png'); }

Vanuan avatar Mar 03 '20 09:03 Vanuan

Hello, I also had this problem. I have solved it with one example from this page.

You can check my solution here: https://github.com/modestukasai/dynamic-environment-variable-react-docker

mkazinauskas avatar Apr 13 '20 17:04 mkazinauskas

I came here looking for runtime environment variable in Docker, and react-env did not disappoint.

The one thing that seems unsettled though is how to define PUBLIC_URL at runtime. Of course, it's not trivial, considering how that value needs to be written in index.html and other static/ output files.

I have solved this by building upon react-env and adding my own sed command to do more heavy lifting on boot.

#
# Stage 1
#
FROM node:12-alpine AS build

# Define `PUBLIC_URL` as variable to find-and-replace later
ENV PUBLIC_URL="{{base_url}}"

# Create app directory
WORKDIR /usr/src/app

# Bundle app source
COPY . .

# Install dependencies and build the app
RUN npm install --production && npm run build


#
# Stage 2
#
FROM beamaustralia/react-env:2.1.2

# Update the `react-env` entrypoint.sh file with my own command.
# The command finds `{{base_url}}` and replaces it with the value of
# `$REACT_APP_BASE_URL`, which is a runtime environment variable.
RUN sed -i "5ifind \/var\/www\/ -type f -exec sed -i'' -e 's|{{base_url}}|'\"\$REACT_APP_BASE_URL\"'|g' {} \\\;" /var/entrypoint.sh
RUN cat /var/entrypoint.sh

WORKDIR /var/www

# Copy app files from Stage 1
COPY --from=build /usr/src/app/build /var/www

I admit it's a bit of a rough job, but it solves the problem for me and hopefully others.

A caveat worth noting, because the files are mutated, if you need to change the value of $REACT_APP_BASE_URL, simply restarting the container is not enough. This is because the files are already rewritten inside the paused container. If you need to change the env, you'll have to fully rm the container. Small price to pay, IMO, especially since the PUBLIC_URL shouldn't change often. In my case, this solution allows me to support separate dev, qa, staging, and production environments without needing to build up to 4 images.

Note that $REACT_APP_BASE_URL is fully optional in this solution. If it goes undefined, its value would be empty string, in which case, you'd be left with the CRA default of files on the base routes (ex: /favicon.ico).


Along with this, I need to configure react-router. I do that like this.

import env from "@beam-australia/react-env";
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router } from "react-router-dom";
import * as url from "url";
import App from "./App";

const baseUrl = env("BASE_URL");
const basePath = url.parse(baseUrl).pathname ?? "/";

const AppWithRouter = (
  <Router basename={basePath}>
    <App />
  </Router>
);
ReactDOM.render(AppWithRouter, document.getElementById("root"));

EDIT

I've created an issue on react-env about this to gauge interest in this becoming part of react-env. https://github.com/beam-australia/react-env/issues/27

jfairley avatar May 12 '20 04:05 jfairley

What about envsubst? In short, suggestion is following:

  1. You define your environment in index.html following way:
    <script>
        const API_BASE_URL = "http://localhost:8080"; // <- default value
        window.$$env = {
            apiBaseUrl: `${API_BASE_URL}`,
        };
    </script>
    
  2. Run envsubst to replace ${API_BASE_URL} with variable value
    defined_envs=$(printf '${%s} ' $(env | cut -d= -f1))
    envsubst "$defined_envs" < "$template_path" > "$output_path"
    
  3. All values in window.$$env are strings, you need some code to convert them to expected types

I have sample repo (https://github.com/zaverden/frontend-env) where you can find more details and working example.

zaverden avatar Sep 13 '20 16:09 zaverden

@andrewmclagan's library is almost perfect but I used it slightly different to how the docs recommend (I wanted this to be as lean as possible):

  1. Add <script src="%PUBLIC_URL%/env.js"></script> to public/index.html
  2. Install andrew's lib yarn add @beam-australia/react-env
  3. Modify the start script to be react-env --dest public && react-scripts start
  4. Modify your serve script (we use serve) to be react-env --dest build && serve -s build
  5. Use window._env.REACT_APP_* variables in your app instead of process.env.REACT_APP_*

I had to forgo using the "prestart" script because development/production have different destinations, and I really didn't want to use the docker image provided as we have our own.

I also didn't want to use a library to get the variables since all it really does is put them on window._env.

All and all this is working really well. I'm using it in multiple environments:

  • Local dev using docker-compose
  • Remote dev using k8s + skaffold
  • and in Production using k8s

Great solution by @ashconnell. I had to use window.__env though, using two underscores instead of one.

larsblumberg avatar Mar 03 '21 10:03 larsblumberg

Is there a way of having a 12 factor app, but in the official nginx-unprivileged image? Before in the default nginx image, I had an envsubst script, but now I don't have enough privileges to create a file in the /usr/share/nginx/html folder. What are my options?

Janjko avatar Apr 29 '21 13:04 Janjko

We took a bit convoluted solution, but it has some benefits:

  1. yarn add -D react-app-rewired
  2. add "build:dynamic-env": "react-app-rewired build", to package.json script section
  3. add .env.production and add the env vars that needs runtime injection. e.g. REACT_APP_OAUTH_CLIENT_ID="--runtime-inject--"
  4. add config-overrides.js:
const HtmlWebpackPlugin = require("html-webpack-plugin");
const DefinePlugin = require("webpack").DefinePlugin;

const REACT_APP = /^REACT_APP_/i;

// reference: https://github.com/jantimon/html-webpack-plugin#events
class InjectEnvJsToIndex {
	constructor(htmlWebpackPlugin) {
		this.htmlWebpackPlugin = htmlWebpackPlugin;
	}
	apply(compiler) {
		if (!this.htmlWebpackPlugin) {
			console.warn(
				"not injecting _env.js to index.html because htmlWebpackPlugin not found"
			);
		}
		compiler.hooks.compilation.tap("InjectEnvJsToIndex", (compilation) => {
			const hooks = this.htmlWebpackPlugin.getHooks(compilation);
			hooks.alterAssetTagGroups.tap("InjectEnvJsToIndex", (data) => {
				data.headTags.push({
					tagName: "script",
					voidTag: false,
					attributes: {
						src: "/_env.js",
					},
				});
			});
			// console.log("inject env.js to index.html", hooks.alterAssetTagGroups);
		});
	}
}

module.exports = function override(config, _env) {
	if (process.env.NODE_ENV !== "production") {
		return;
	}
	let replaceRuntimeEnv;
	let htmlWebpackPlugin;
	for (let p of config.plugins) {
		// inject env var
		if (p instanceof DefinePlugin) {
			const env = p.definitions["process.env"];
			const updated = Object.keys(env)
				.filter((key) => REACT_APP.test(key))
				.filter((key) => env[key] === '"--runtime-inject--"')
				.reduce((env, key) => {
					const value = `window.${key}`;
					console.log(`injecting ${key} as ${value} in production build`);
					env[key] = value;
					return env;
				}, {});
			replaceRuntimeEnv = {
				"process.env": updated,
			};
		}
		if (p.constructor.name === "HtmlWebpackPlugin") {
			// only use react-scripts's plugin class, in case there are multiple versions of htmlWebpackPlugin
			htmlWebpackPlugin = p.constructor;
		}
	}
	if (replaceRuntimeEnv) {
		config.plugins.unshift(new DefinePlugin(replaceRuntimeEnv));
	}
	// inject script src=_env.js tag
	config.plugins.push(new InjectEnvJsToIndex(htmlWebpackPlugin));
	return config;
};

Then you could either have an init script that creates the env.js or have a simple http server that serves env.js

Example go server

Build with CGO_ENABLED=0 go build -o build/serve main.go

package main

import (
	"bytes"
	"flag"
	"fmt"
	"hash/maphash"
	"io"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"time"
)

var BaseDir = "build"

var vars bytes.Buffer
var varsHash string

func init() {
	h := maphash.Hash{}
	w := io.MultiWriter(&vars, &h)
	for _, v := range os.Environ() {
		if strings.HasPrefix(v, "REACT_APP_") {
			i := strings.Index(v, "=")
			if i < 0 {
				log.Fatalf("env not correct: %v", v)
			}
			key := v[:i]
			value := v[i+1:]
			value = strings.ReplaceAll(value, "\"", "\\\"")
			fmt.Fprintf(w, `window.%s="%s";`, key, value)
		}
	}
	varsHash = fmt.Sprintf("%x", h.Sum(nil))
}

func env(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("content-type", "application/javascript")
	// sensible cache expires: 10 min
	if !*debug {
		w.Header().Set("expires", time.Now().Add(time.Minute*10).Format(http.TimeFormat))
	}
	w.Header().Set("etag", varsHash)
	if r.Header.Get("if-none-match") == varsHash {
		w.WriteHeader(http.StatusNotModified)
		return
	}
	w.Write(vars.Bytes())
}

func notfound(w http.ResponseWriter, _ *http.Request, err string) {
	w.WriteHeader(http.StatusNotFound)
	w.Write([]byte(err))
}

func internal(w http.ResponseWriter, _ *http.Request, err string) {
	w.WriteHeader(http.StatusInternalServerError)
	w.Write([]byte(err))
}

func denied(w http.ResponseWriter, _ *http.Request) {
	w.WriteHeader(http.StatusUnauthorized)
	w.Write([]byte("not authorised"))
}

func serve(w http.ResponseWriter, r *http.Request) {
	path := r.URL.Path
	if path == "/_env.js" {
		env(w, r)
		return
	}
	if path == "/index.html" || path == "/" {
		// good idea, but always need a https server to work: http/2 needs https
		if pusher, ok := w.(http.Pusher); ok {
			// Push is supported.
			options := &http.PushOptions{
				Header: http.Header{
					"Accept-Encoding": r.Header["Accept-Encoding"],
				},
			}
			if err := pusher.Push("/_env.js", options); err != nil {
				log.Printf("Failed to push: %v", err)
			}
		}
	}
	fn := filepath.Join(BaseDir, path)
	indexFn := filepath.Join(BaseDir, "index.html")
	fi, err := os.Stat(fn)
	if err != nil {
		if os.IsNotExist(err) {
			fn = indexFn
		} else {
			internal(w, r, err.Error())
			return
		}
	}
	if fi == nil || fi.IsDir() {
		fn = indexFn
	}
	if path == "/service-worker.js" {
		w.Header().Set("Cache-Control", "no-cache")
	}

	f, err := os.Open(fn)
	if err != nil {
		internal(w, r, err.Error())
		return
	}
	defer f.Close()

	fi, err = f.Stat()
	if err != nil {
		internal(w, r, err.Error())
		return
	}
	http.ServeContent(w, r, f.Name(), fi.ModTime(), f)
}

var debug = flag.Bool("debug", false, "debug mode")

func main() {
	port := flag.String("port", ":8000", "listen addr")
	cert := flag.String("cert", "", "cert for tls")
	key := flag.String("key", "", "key for tls")
	help := flag.Bool("help", false, "help")
	flag.Parse()
	addr := os.Getenv("PORT")
	if addr == "" {
		addr = *port
	}
	if *help {
		flag.Usage()
		return
	}
	if flag.NArg() < 1 {
		BaseDir = "build"
	}
	http.HandleFunc("/", serve)
	if *cert != "" && *key != "" {
		log.Println("serving", BaseDir, "and listening tls on", addr)
		log.Fatal(http.ListenAndServeTLS(addr, *cert, *key, nil))
	}
	log.Println("serving", BaseDir, "and listening on", addr)
	http.ListenAndServe(addr, nil)
}

Example nginx based dockerfile that creates _env.js
# Nginx based web server
FROM nginx:alpine
COPY --from=build /source/dist /usr/share/nginx/html
COPY ./nginx.conf /etc/nginx/nginx.conf
COPY ./nginx_proxy.conf /etc/nginx/nginx_proxy.conf
RUN echo -e "#!/bin/sh\n"\
  "for i in \$(env); do\n"\
  "  PREFIX=\`echo \$i | cut -c1-10\`\n"\
  "  if [ \"\$PREFIX\" = 'REACT_APP_' ]; then\n"\
  "    VAR=\`echo \$i | cut -d= -f1\`\n"\
  "    eval \"VAL=\\\${\$VAR}\"\n"\
  "    OLD=\"{\$VAR}\"\n"\
  "    echo \"replacing \$OLD with \$VAL\"\n"\
  "    sed -i \"s:\$OLD:\${VAL//:/\\:}:g\" /usr/share/nginx/html/_env.js\n"\
  "  fi\n"\
  "done\n"\
  "gzip -kc /usr/share/nginx/html/index.html > /usr/share/nginx/html/index.html.gz\n"\
  "nginx -g 'daemon off;'\n" > /init.sh
EXPOSE 80
CMD ["sh", "/init.sh"]

pros:

  • same dev workflow as react-scripts
  • injection only happens in production build

cons:

  • depending on webpack
  • a bit convoluted

jackieli-tes avatar Jul 05 '21 14:07 jackieli-tes

Is anyone using a solution of fetching the config.js file created by docker via a http client on app startup from your assets folder instead of adding the script to the html or adding the variables to the window object?

My app will be served in a shell so only the <div id="my-root-id"></div> will be used so I can't really mess with the HTML head or anything like that. Also I'm not sure if adding things to the window object would be allowed.

Just generally wondering if there are any drawbacks for my solution or is there a different reason no one used this approach?

mario-subo avatar Jul 07 '21 07:07 mario-subo

@mario-subo At my former company we had an express http server hosting our CRA. We had a /config route to fetch out the runtime config before we started sending out other requests (GraphQL, Auth0, etc...) and just stuck the config data in a Context.

ChristianJacobsen avatar Jul 07 '21 08:07 ChristianJacobsen

@mario-subo At my former company we had an express http server hosting our CRA. We had a /config route to fetch out the runtime config before we started sending out other requests (GraphQL, Auth0, etc...) and just stuck the config data in a Context.

Yeah I will be trying a similar approach. One config file and just fetch it at runtime and stick it in a context. But instead of an express server I am thinking of just using a normal fetch("./config.json") and injecting the said file in docker for each environment.

I'll come back with details if everything goes well (or more importantly if it doesn't haha)

mario-subo avatar Jul 07 '21 09:07 mario-subo

Same challenge - following!

MurrayFoxcroft avatar Jul 08 '21 13:07 MurrayFoxcroft

FWIW, we looked at this problem while using Create React App with a serverless backend in SST: https://github.com/serverless-stack/serverless-stack

Here's roughly how we solved it:

  1. On the backend, allow defining React environment variables using the outputs from the backend.

    // Create a React.js app
    const site = new sst.ReactStaticSite(this, "Site", {
      path: "frontend",
      environment: {
        // Pass in the API endpoint to our app
        REACT_APP_API_URL: api.url,
      },
    });
    
  2. Spit out a config file while starting the local environment for the backend.

  3. Then start React using sst-env -- react-scripts start, where we have a simple CLI that reads from the config file and loads them as build-time environment variables in React.

  4. While deploying, replace these environment variables based on the outputs from the backend.

We wrote about it here: https://serverless-stack.com/chapters/setting-serverless-environments-variables-in-a-react-app.html

jayair avatar Jul 21 '21 00:07 jayair

I found this article to be useful for docker images. Where we ran a script prior to build:

env.sh

#!/bin/bash

# https://create-react-app.dev/docs/adding-custom-environment-variables We should utilize these instead of the custom logic here

if [[ -z "${SPA_CONTENT_DIR}" ]]; then
  ENV_JS="./env-config.js"
else
  ENV_JS="./${SPA_CONTENT_DIR}/env-config.js"
fi

if [[ -z "${SPA_ENVIRONMENT}" ]]; then
  environmentFile=".env"
  echo "Creating default env-config.js"
else
  environmentFile=".env.${SPA_ENVIRONMENT}"
  echo "Creating env-config.js for ${SPA_ENVIRONMENT}"
fi

if [ ! -f "$environmentFile" ]; then
  echo "ERROR: Environment file $environmentFile does not exist!"
  exit 1;
fi

# Recreate config file
rm -rf ${ENV_JS}
touch ${ENV_JS}

# Add assignment 
echo "window._env_ = {" >> ${ENV_JS}

# Read each line in .env file
# Each line represents key=value pairs
while read -r line || [[ -n "$line" ]];
do
  # Split env variables by character `=`
  if printf '%s\n' "$line" | grep -q -e '='; then
    varname=$(printf '%s\n' "$line" | sed -e 's/=.*//')
    varvalue=$(printf '%s\n' "$line" | sed -e 's/^[^=]*=//')
  fi

  # Read value of current variable if exists as Environment variable
  value=$(printf '%s\n' "${!varname}")
  # Otherwise use value from .env file
  [[ -z $value ]] && value=${varvalue}
  
  # Append configuration property to JS file
  echo "  $varname: \"$value\"," >> ${ENV_JS}
done < $environmentFile

echo "}" >> ${ENV_JS}

package.json

...
scripts: {
  "build": "react-scripts build && npm run preserve",
  "preserve": "chmod +x ./env.sh && ./env.sh && cp env-config.js ./build/",
}
...

index.html

...
    <script src="/env-config.js?d=20210806"></script>
...

mstelz avatar Aug 06 '21 12:08 mstelz

We ended up by mounting a config.js file inside the public folder, like this

config.js

 window.REACT_APP_API_URL="https://base-url-here.domain.com/api";  
 window.REACT_APP_PUBLIC_URL="https://base-url-here.domain.com/login";
 window.REACT_APP_REDIRECT_URL="http://test-environment.domain.com/";
 window.REACT_APP_REDIRECT_REG="https://domain.pre.domain.com/registerPopup.html";
 window.REACT_APP_REDIRECT_FORGOT="https://domain.pre.domain.com/forgotPassword.html";

Then

mount this config.js on this path where apache (or nginx) expects it: /usr/local/apache2/htdocs/module_name/config.js

Inside index.html (public folder) reference the config.js file

<!DOCTYPE html>
<html lang="es">

<head>
  <script src="%PUBLIC_URL%/config.js"></script>
  <meta charset="utf-8" />
  <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
 [...]

Then, since we didn't want to modify our code and pollute it with different references to the window object, we created this file that does the binding:

config.ts


const REACT_APP_DEPLOY_ENV: string = window.REACT_APP_DEPLOY_ENV || '';
const REACT_APP_MAIN_SITE_HOMEPAGE: string = window.REACT_APP_MAIN_SITE_HOMEPAGE || '';
const REACT_APP_API_URL: string = window.REACT_APP_API_URL || '';
const PUBLIC_URL: string = window.PUBLIC_URL || '';
const REACT_APP_REDIRECT_URL: string = window.REACT_APP_REDIRECT_URL || '';
const REACT_APP_REDIRECT_REG: string = window.REACT_APP_REDIRECT_REG || '';
const REACT_APP_REDIRECT_FORGOT: string = window.REACT_APP_REDIRECT_FORGOT || '';

export {
  REACT_APP_DEPLOY_ENV,
  REACT_APP_MAIN_SITE_HOMEPAGE,
  REACT_APP_API_URL,
  PUBLIC_URL,
  REACT_APP_REDIRECT_URL,
  REACT_APP_REDIRECT_REG,
  REACT_APP_REDIRECT_FORGOT,
};

For local development (without Apache/Nginx), you can build the docker image and provide the config.js file manually inside the public folder.

justpolidor avatar Sep 13 '21 09:09 justpolidor

Hello, my team has just published a package react-inject-env that allows you to build the base files > inject environment variables > deploy app.

It works on a 2 step process:

  1. First it builds the static files with a placeholder variables.
  2. Then it takes in your actual environment variables, looks through your build files, and substitutes the placeholders variables with the real variables.

Try it out and feel free to leave feedback!

https://www.npmjs.com/package/react-inject-env

es-lynn avatar Sep 16 '21 06:09 es-lynn

Hi all, I just wrote some packages related to this problem.

This approach is similar to the react-inject-env above, but also works to:

  1. Webpack, Vite, Rollup projects (powered by unplugin),
  2. CSR, SSR, SSG modes,
  3. and testing environment such as Jest and Mocha (based on babel plugin).

Hope this package helps someone looking for this.

Feel free to give your feedback.

https://iendeavor.github.io/import-meta-env/

soc221b avatar Mar 11 '22 14:03 soc221b

what helped me to serve the same CRA build from different domains (prod vs stage) and at the same time serve index.html and all the rest assets from different domains (use CDN):

  1. Stop providing PUBLIC_URL in build time.
  2. Start serving env.js per environment (e.g. with window.ASSETS_PUBLIC_URL = 'production.com')
  3. Replace CRA's HtmlWebpackPlugin instance with mine that uses templateContent prop so I can construct src attribute for script tags by myself (so I can use window.ASSETS_PUBLIC_URL there). I used Craco for that.
  4. Patch loading dynamic js chunks by setting __webpack_public_path__ = window.PREPLY_ASSETS_PUBLIC_HOST in my app js entrypoint.

oleg-rdk avatar Jun 29 '22 11:06 oleg-rdk