I have a React app using Create React App which uses Typescript and I am trying to read in config values, such as API urls. I currently have a config.json
which contains this data, here's a sample with fake data to show the gyst of it:
{
"apiUrl": "https://localhost:3001/",
"externalUrl": "https://localhost:3002/"
}
The desired outcome
I can build the web app once and deploy it anywhere, updating the config values at deploy time e.g. for dev apiUrl
should be https://localhost:4001/, in prod apiUrl
should be https://localhost:5001/.
The config should be available in all files and not limited to just inside components (so hooks like useContext
won't work) and be Typescript compliant e.g. can access the config values via a typed interface/type.
What I've tried
There is quite a few similar posts to this, such as:
- How to have a external JSON config file in react jsx
- React configuration file for post deployment settings
- Build Once and Deploy Everywhere for SPAs
The general suggestion is to put a config.js
in the public
folder, reference it as a script
in index.html
and finally call it via the window
e.g. window.Config.apiUrl
.
This throws an error in Typescript as us adding in this config in the index.html
via a script
doesn't actually add the type and I can get around this by using // ts-nocheck
, though this is not ideal as it disables all checks for the file. Additionally, it would be preferable for the config file to be a type so can confidently reference it.