As React is a single page application that runs as static page inside a browser runtime environment, there is nothing like a runtime variable. However, there are few hacks through which we can implement dynamic variables in a React application.
But the question is why we need a runtime variable for static page? Well, in my experience there are few cases which compel us to look for runtime or dynamic variable in a React app or for that matter of fact for any SPA. For example, different API endpoints for local, pre-prod, and production, different API keys for pre-prod and prod, and likewise.
- An environment file
- A Bash script
- A NPM script
- Include script tag in public/index.html
- Script where runtime variable is needed
Create an env.preprod file, create this file at /public/env/ location e.g. /public/env/env.preprod
This is the file where the runtime environment variable will be stored, there could more than one variable in the file. Why under public directory? as it will be bundled during the build process into tarball
Bash script that will be executed during
npm start for local, that will create the env-config.js with content from env.preprod file and same for pre-prod during deployment. For prod, we'll have the default env-config.js file.
This will wire up as the
prestart npm script and execute the bash script.
The env-config.js created so far needs to be loaded in the index.html, else we can't use it. When env-config.js is created, the browser's window object is assigned a runtime variable.
And now for all the hard work done so far, it's time to ripe/use the runtime variable. Since the variable is assigned as a window object, now we can use the way we want.
- Execute script during deployment
- location.conf (when using NGINX)
Include a script to execute the
env.sh in the deployment process. For docker image details, checkout the reference section at the end.
When the Nginx server is used as a web server, allow access to env-config.js file.
Creating a default reduces the effort to configure any steps needed during the production deployment. But if we want, we can create another env file like env.prod and run the same during production deployment. However, this is totally up to you!
If you have reached here, then I did a satisfactory effort to keep you reading. Please be kind to leave any comments or ask for any corrections. Happy Coding!