Runtime configuration for Single-Page Applications
Posted on
When we are working on developing a large and distributed system, the frontend is separated and normally presented as a single-page application (SPA) or a set of micro frontends (set of SPAs). Normally, an SPA is immutable and served from some static storage, and not served from the same app that provides the backend APIs or using server-side rendering (SSR) to generate them at runtime. This means you don't have access to environment variables to configure your application during deployment or at runtime.
This is a quite common problem with quite common solutions.
Build-time configuration: Create different app configurations and build different artifacts for each of the environments. But in that case, you will get a separate set of artifacts and can’t guarantee that your production application is exactly the same as what you use for testing.
Runtime configuration: Instead of building separate artifacts, you can include some placeholders for all configurations and replace them with actual values during application deployment, like here. This approach is much better from my point of view, but also has some cons. For example: increased complexity in deployment scripts, potential security risks if placeholders are not managed properly, and harder to debug issues related to configuration values.
Runtime configuration with external configuration: In this approach, we can move our application configuration to a separate external file (let’s call it config.json) and fetch this file during application startup. This option is preferable for many reasons: it is easier to manage and update configuration without rebuilding the application, and it simplifies the deployment process by separating configuration from the application code.
Here is a simple example implementing this approach for a React application.
First of all, you need to create the config and put it into the public folder:
Bonus content: How to deal with configuration in case of Kubernetes
In case you serve your static applications from a simple container with an HTTP server (nginx for example), you can easily mount the configuration file from a ConfigMap.