Sub topic 13
Choosing Between JSON Modules, fetch, and File Reads
This chapter assumes you know how static and dynamic JSON imports work, how the module cache shares one object, and how Node.js and browsers load JSON modules. It also assumes you are comfortable with async/await and JSON.parse. JSON modules are one way to load JSON data. In many cases a plain fetch or file read is the better choice.
What each approach gives you
A JSON module gets loaded as part of the module graph. It is fetched once, parsed once and cached, and every importer receives the same object. That suits data that ships with your code and stays the same while the program runs, such as default settings, locale strings or lookup tables.
The other approaches treat JSON as data you load at runtime. You decide when the read happens, how errors are handled and whether you get a fresh copy.
| Need | JSON module | `fetch` + `response.json()` | `fs` + `JSON.parse` |
|---|---|---|---|
| Runs in browsers | Yes | Yes | No |
| Runs in Node.js | Yes | Yes (Node 18+) | Yes |
| Fresh data on each load | No, cached | Yes, subject to HTTP caching | Yes |
| Custom headers, auth, timeouts | No | Yes | Not applicable |
| Handle a missing file gracefully | Only with dynamic `import()` and `try`/`catch` | Check `response.ok` | Catch the read error |
| Bundler can inline it at build time | Yes | No | No |
| Fails before any code runs (static form) | Yes | No | No |
Reading the file yourself in Node.js
If the file can change while the process runs, or each caller needs its own copy to mutate, read and parse the file directly. Each call to JSON.parse returns a new object, and the module cache is never involved.
import { readFile } from "node:fs/promises";
const text = await readFile(new URL("./config.json", import.meta.url), "utf8");
const config = JSON.parse(text);
console.log(config.appName);Resolving the path against import.meta.url keeps it relative to the module file rather than the current working directory, which is how an import specifier behaves too.
In CommonJS code, require("./config.json") also works. It caches like a JSON module and has the same shared-object behavior. Use it only in code that is already CommonJS.
Fetching in the browser
In the browser, use fetch when the data comes from an API, needs request options such as credentials or headers, or should be retried or replaced with a fallback on failure.
const response = await fetch("/data/config.json");
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const config = await response.json();
console.log(config.appName);fetch does not check the server's MIME type, so it will not reject a wrongly served file the way a JSON module import does. response.json() still rejects if the body is not valid JSON.
A decision path
Rules of thumb
- Use a static JSON module for small, fixed data that ships with your code and that you treat as read-only.
- Use dynamic
import()when the file is picked at runtime but stays fixed once loaded, such as a locale. - Use
fetchfor remote, authenticated or frequently changing data. - Use
fswithJSON.parsein Node.js for files that change on disk, like a config that gets hot-reloaded.
Exercise
A Node.js server must reload rates.json every minute because another process rewrites it. A teammate re-runs await import("./rates.json", { with: { type: "json" } }) on a timer. Why does this fail to pick up changes, and what should they use?
Show answer
Dynamic import() caches the module by its resolved URL. Every later call returns the same module with the same object, so changes on disk never show up. They should read the file with readFile and parse it with JSON.parse on each tick, which returns a new object every time.
Exercise
A browser app loads optional feature flags from /flags.json and should fall back to defaults if the file is missing. Why is a static JSON import a poor fit, and which approach fits better?
Show answer
A failed static import stops the whole module graph from evaluating, so the app would not start. fetch with a response.ok check, or a dynamic import() wrapped in try/catch, lets the app catch the failure and use the defaults.