title: Runtime Configurations with React published: true description: tags: react, SPA config, runtime, configurations


Most of the time using custom build time environment variables are suitable but runtime variables can be valuable in addition to or in place of environment variables.

Runtime configurations or variables, can be beneficial when you need to change a configuration at run time. Some examples of variables you could load at runtime is theme data or api urls.

Do not store any secrets (such as private API keys) in your environment or runtime variables!

Why runtime variables?

  • Build app only once and deploy the same build to multiple environments (i.e. dev, qa, prod)
  • Configurations can be changed/updated after the app is deployed
  • Load configurations from an external source
  • Save time - Build pipelines can take long periods of time some with many steps (i.e. infrastructure steps, build steps, tests, etc). Loading configurations during runtime can help reduce the amount of times your app is built.

How do runtime variables work?

Runtime variables get loaded into the browser's window object when the index.html of a single page application gets loaded.

In the <head> or <body> of the html file we can run a Javascript snippet that sets up the configurations on the window object.

Javascript code in the index.html file will get loaded synchronously from top to bottom as long as the async flag is not present. By placing the code to load our snippet before the main bundle it can be guaranteed that the values will be set on the window object and accessible when your main javascript bundle is loaded.

Let’s look at how this can be accomplished.

Create a new file called runtime-config.js and setup some variables

``` // runtime-config.js window['runConfig'] = { apiUrl: 'test.com/api' }

```

To load the script in the index.html file add the script tag to the file inside either the <head> or <body> tag. If you are starting with Create React App the file will be located at <project_root>/public/index.html

<script src="%PUBLIC_URL%/runtime-config.js"></script>

``` // index.html

<!-- runtime config -->
<script src="%PUBLIC_URL%/runtime-config.js"></script>
<!-- runtime config -->

<title>React App</title>


```

How to use in a React component

To access the variables that are setup in the runtime-config file, from your app files you can reference the window object.

window['runConfig']

Example usage in a React component:

``` export const MyComponent = () => { const { apiUrl } = window['runConfig']; return (

Runtime config apiUrl: {apiUrl}
) }

```

Full Example:

https://github.com/mattcat10/react-runtime-config

Notes: - Don't use runtime configurations if your configurations are really large. They are loaded synchronously and could slow down your initial load time of your app

  • This post explains how to use runtime configurations in a react app, but the same concept can be applied to any SPA framework.