So just as food for thought, three options that don’t require fetch at all:
- Use environment variables
- Just import the JSON directly
- Use JS instead of JSON and import that
1 requires a build process, 2 will only [currently] work without a build process in Chrome and Edge, 3 will work in any current browser.
2 and 3 rely on use of modules.
For first option you would have the set of values currently in your JSON config stored as environment variables. They are interpolated into your codebase, at build time you tell the build tool which set of vars you’re using, code builds with that config.
For second option, if you’re using modules then you can just do
import myjson from "./myjson" assert { type: "json" };
Or
const myjson = await import("./myjson", { assert: { type: "json" }});
In above cases, myjson
is just a JS object, same as any other JS module import.
Note that importing JSON works out-of-the-box in Chrome. Firefox is behind a flag, should be in v soon. Safari needs to wait until next OSX/iOS release. However, there’s a build process then this can be transpiled.
For third option, you can also use a JS file rather than a JSON file, ensure it exports the thing you want, and import that, eg
export myconfigs = {
foo: 1,
bar: 2,
}
Then
import { myconfigs } from "./myconfigs.js";
// ...then use them in the code
Or
const { myconfigs } = await import("./myconfigs.js");
// ...then use them in the code
Just as an aside with current fetch
based solution, can just do this at the top of the file
const { someUrl, someToken, someEmail, someNumber } = await fetch("./somejson").then((response) => response.json());
// ...then use someUrl, someToken etc in your code
So as the first line in the file, just fetch and parse the values from the JSON file.
I am assuming that if the values you’re extracting from the JSON aren’t there then the code won’t work, so I’m not sure you really need any error handling. It should just explode if something fails