Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React SPA dynamic environment configuration

I'm building React SPA application from ground up using create-react-app and setting up uri address for API server of my SPA. According to official documentation suggested way is to create environment .env files for such kind of needs. I'm using a continuous delivery as part of development workflow. After deployment React SPA application goes in one Docker container and API goes to another. Those containers are deployed in separate servers and I do not know exactly what uri for API will be, so there is no way to create separate .env file for each deployment. Is there any "right way" to provide dynamic configuration for my SPA application so I can easily change environment parameters

API URI examples in SPA

// api.config.js

export const uriToApi1 = process.env.REACT_APP_API1_URI;
export const uriToApi2 = process.env.REACT_APP_API2_URI;

// in App.js

import { uriToApi1, uriToApi2 } from '../components/config/api.config.js';

/* More code */
<DataForm apiDataUri={`${uriToApi1}/BasicService/GetData`} />
/* More code */
<DataForm apiDataUri={`${uriToApi2}/ComplexService/UpdateData`} />
like image 590
Anton Avatar asked Jun 02 '26 09:06

Anton


1 Answers

Let's imagine that you build your frontend code in some dist folder that will be packed by Docker in the image. You need to create config folder in your project that also will be added in dist folder (and obvious, will be packed in Docker image). In this folder, you will store some config files with some server-specific data. And you need to load these files when your react application starts.

The flow will be like that:

  1. User opens your app.
  2. Your App shows some loader and fetches config file (e.g. ./config/api-config.json)
  3. Then your app reads this config and continues its work.

You need to setup Docker Volumes in your Docker config file and connect config folder in Docker container with some config folder on your server. Then you will be able to substitute config files in a docker container by files on your server. This will help you to override config on each server.

like image 72
Andrii Golubenko Avatar answered Jun 04 '26 23:06

Andrii Golubenko