Sub topic 13
Choosing Between JSON Modules, fetch, and File Reads
This chapter assumes you already know how static and dynamic JSON imports work, how the module cache shares one object among importers, and how browsers and Node.js handle JSON modules. It also assumes you are comfortable with async/await, fetch, and the Node.js fs module. The goal here is to help you decide which loading method fits a given job.
JSON modules are not the only way to get JSON data into a program, and they are often not the best one. You can choose from four common mechanisms:
- JSON modules:
import ... with { type: "json" }orimport()with the same attribute. - fetch:
fetch(url)followed byresponse.json(), in browsers and in Node.js 18 and later. - File reads:
fs.readFilefollowed byJSON.parse, in Node.js and other server runtimes. - require: CommonJS
require("./file.json"), orcreateRequirefrom inside an ES module.
Each one makes different trade-offs about when the data loads, how errors surface, whether the result is cached, and whether build tools can see it.
The Core Trade-off: Load Time and Identity
The most important difference is when the data is loaded and whether you get the same object every time.
A static JSON import is resolved during module linking. That happens before any of your code runs. If the file is missing or invalid, the whole module graph fails, and nothing in it executes. Once the import succeeds, every importer shares one cached object for the life of the page or process.
fetch and readFile run when your code calls them. Each call does fresh I/O and returns a fresh object. Errors arrive as ordinary rejected promises that you can catch, inspect, and recover from.
Dynamic import() falls between the two. It runs on demand, but the result still goes into the module cache. After the first successful load, later calls return the same shared instance and never re-read the file.
| Property | Static JSON import | Dynamic `import()` | `fetch` + `json()` | `readFile` + `JSON.parse` | `require` |
|---|---|---|---|---|---|
| When it loads | Link time | On call (once) | On every call | On every call | On first call |
| Result identity | Shared singleton | Shared singleton | Fresh object | Fresh object | Shared singleton |
| Sees file changes | No | No | Yes (subject to HTTP cache) | Yes | No, unless the cache is cleared |
| Error detail | Generic load or parse failure | Rejected promise, little detail | HTTP status, headers, parse error | `ENOENT`, `EACCES`, `SyntaxError` | Thrown error with code |
| Request options | None | None | Headers, credentials, abort signal | Encoding, abort signal | None |
| Bundler can inline it | Yes | Yes (with static paths) | No | No | Yes (most bundlers) |
| Environments | Browsers, Node, Deno, Bun | Browsers, Node, Deno, Bun | Browsers, Node 18+, Deno, Bun | Server runtimes | Node, Bun |
A Decision Path
When JSON Modules Are the Right Choice
Use a JSON module when the data is part of your program's source: feature flags baked in at deploy time, a list of country codes, a translation table, or a JSON Schema. In each case:
- The data does not change while the program runs.
- A missing file is a deployment bug, so failing early is what you want.
- A bundler can inline the data and tree-shake around it, and a type checker can infer its shape with
resolveJsonModule. - One shared instance saves memory and parse time when many modules import the same file.
Dynamic import() extends this to data you choose at runtime, such as a locale picked from a fixed set of files that ship with the app. Bundlers can split each candidate file into its own chunk when the path is a template literal with a static prefix, as in ./locales/${lang}.json.
When fetch Is the Right Choice
In the browser, use fetch when any of these apply:
- The data changes on the server, like a live inventory count.
- You need to send headers, cookies, or credentials, or set a timeout.
- You want to handle a 404 differently from a 500 or from malformed JSON.
- You want to retry after a failure.
That last point matters more than it looks. In browsers, the HTML specification records a failed module fetch in the module map. Calling import() again with the same URL usually fails right away without a new network request, so retry logic built on import() does not work. fetch has no such memory.
async function loadInventory(url, { retries = 2, timeoutMs = 5000 } = {}) {
for (let attempt = 0; ; attempt++) {
try {
const response = await fetch(url, {
headers: { Accept: "application/json" },
signal: AbortSignal.timeout(timeoutMs)
});
if (response.status === 404) {
return null; // A missing resource is a normal outcome here
}
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return await response.json(); // Throws SyntaxError on malformed JSON
} catch (err) {
if (err instanceof SyntaxError || attempt >= retries) {
throw err; // Bad JSON will not fix itself on retry
}
}
}
}
const items = await loadInventory("/api/inventory.json");
console.log(items === null ? "No inventory" : items.length);Notice that fetch does not check the MIME type for you. A JSON module rejects a response whose Content-Type is not a JSON type, but response.json() parses any body. If the server's content type matters to you, check response.headers.get("content-type") yourself.
When File Reads Are the Right Choice
On the server, readFile plus JSON.parse is the flexible option for local files. It gives you precise error codes, a fresh object on every call, and full control over when to reload. A common case is a configuration file that operators edit while the service is running:
import { readFile } from "node:fs/promises";
import { watch } from "node:fs";
const configUrl = new URL("./config.json", import.meta.url);
async function loadConfig() {
const text = await readFile(configUrl, "utf8");
return JSON.parse(text);
}
let config = await loadConfig();
console.log("Loaded", config.appName, "version", config.version);
watch(configUrl, async () => {
try {
config = await loadConfig();
console.log("Reloaded version", config.version);
} catch (err) {
// Editors often write files in stages, so a partial file can fail to parse.
// Keep the last good config and wait for the next change event.
console.error("Reload skipped:", err.code ?? err.message);
}
});Keeping the old value when a reload fails is the key design choice. With a static JSON import, a malformed file stops the process from starting at all, and changes made while the process runs are never seen.
File reads also let you validate before trusting the data. You can pass a reviver to JSON.parse, or check the parsed object against a schema. You cannot hook into how a JSON module parses its file.
Where require Still Fits
In CommonJS code, require("./config.json") remains the idiomatic choice. It is synchronous and cached like a JSON module, but you can clear its cache. From an ES module, you can reach it through createRequire:
import { createRequire } from "node:module";
const require = createRequire(import.meta.url);
const config = require("./config.json");
console.log(config.appName);
// Force a fresh read on the next require call
delete require.cache[require.resolve("./config.json")];
const fresh = require("./config.json");
console.log(fresh === config); // falseIn new ES module code, prefer a JSON module for static data and readFile for data that changes. Using require from ESM is mainly useful when you need a synchronous load or are moving a codebase over step by step.
Edge Cases That Change the Decision
- Large files. A JSON module or a bundled import puts the whole file into your JavaScript bundle and parses it at startup. For data larger than a few hundred kilobytes, fetching it lazily keeps your first load small.
- Shared mutation. If callers must be able to change the data without affecting each other, a JSON module is a poor fit. Each caller would need to copy it with
structuredClone(config). A function that returns a freshJSON.parseresult gives each caller its own copy for free. - Content Security Policy. JSON modules are fetched under the
script-srcdirective, whilefetchis governed byconnect-src. A strict policy may allow one and block the other. - Cross-origin data. Both methods require CORS for cross-origin URLs, but only
fetchlets you setcredentialsand custom headers. - Testing. Tools can mock
fetchandreadFileper test. A JSON module is cached for the whole test run, so you need loader-level mocking or test isolation to swap it out.
Exercise
A browser dashboard shows exchange rates that a server updates every minute. A developer writes const rates = (await import("/api/rates.json", { with: { type: "json" } })).default; inside a function that runs every 60 seconds. What goes wrong, and what should they use instead?
Show answer
After the first successful load, the module cache returns the same object on every call, so the rates never update. If the first request fails, the browser records that failure and later calls with the same URL usually fail without retrying. Adding a query string to bust the cache leaks a new module record on every refresh. They should use fetch("/api/rates.json") with response.json(), which does fresh I/O on each call, supports a timeout through AbortSignal.timeout, and lets them handle HTTP errors and retries.
Exercise
A Node.js service imports ./config.json with a static JSON import. Operators complain that edits to the file are ignored until a restart, and that one typo stopped the service from booting at all. Which loading method fixes both problems, and what should the reload code do when parsing fails?
Show answer
Read the file with readFile and JSON.parse, and reload it from a fs.watch callback. Each read returns fresh data, so edits take effect without a restart. Wrap the reload in try/catch. On a SyntaxError or a file error, keep the last good config and log the problem rather than crashing. The file may be half-written or temporarily invalid. At startup you can still fail fast, or fall back to defaults if that suits the service better.
Exercise
You have a 40 KB list of country codes that never changes and is used by twelve modules in a bundled web app. Which method fits best, and why?
Show answer
A static JSON import. The data is fixed at build time, so the bundler can inline it and a type checker can infer its shape. All twelve importers share one parsed instance, which saves memory and parse time. A missing or broken file is a build or deployment bug, so failing at link time is the behavior you want. To keep importers from changing the shared object by accident, treat it as read-only or freeze it in one wrapper module.