I'm building a dockerized React application and need to define some environment variables for API URLs. However, React inject those variables in the build phase, so I need to rebuild the whole image every time the environment changes. This slows down my pipeline, as I can't reuse the same app image for homologation and production.
I've searched for some patterns and I'm now using a JS config file to inject the environment on the fly, but it doesn't look very straightforward. Does someone know a better way to handle this problem?
I had the same problem recently, then I published some packages: @import-meta-env/* to npm to solve the problem.
This plugin exposes environment variables on a special import.meta.env object (heavily inspired by Vite).
During production it will be statically replaced with a placeholder instead of current environment variables.
Thus we can run a script anywhere to populating files with environment variables from the system.
You can see more info at https://iendeavor.github.io/import-meta-env/ .
I also created a Docker example: https://github.com/iendeavor/import-meta-env/tree/main/packages/examples/docker-starter-example .
Hope this helps someone who needs it.
Yes indeed this is a problem with environment variables. What you want to achieve can be done with a service that is commonly called "Remote Config" or "Config as a service - CaaS". This service notifies your application that some external data has changed. I would highly recommend LaunchDarkly or Firebase but you can always choose to build it on your own (not a fast solution though). The only way to avoid multiple environment builds is by applying rules on the CaaS and modify the responses based on who requests (eg, based on the request's "Origin" header)