Sub topic 7
One Instance per Module Graph: Caching and Mutation
This chapter assumes you know ES module import and export, can run JavaScript in Node.js or a browser, and have read the earlier chapters on the with { type: "json" } clause and the default-only export of JSON modules. You will learn what the runtime does after it parses a JSON file once, why every importer receives the same object, and how to protect yourself when that sharing causes trouble.
The Module Map: Load Once, Share Everywhere
Every JavaScript environment that runs ES modules keeps a module map. The module map is a cache of the modules that have already been fetched and evaluated, keyed by the module's resolved URL. In browsers the HTML specification also includes the module type in the key, so the key is the pair (URL, type). When a second import resolves to a key the map already holds, the runtime does not fetch or parse anything. It hands back the existing module record.
JSON modules follow the same rule. The first import of ./config.json with type: "json" does three things:
- It fetches or reads the file.
- It runs
JSON.parseon the text, using the same semantics as the global function. - It stores the resulting value as the module's default export.
Every later import that resolves to the same URL gets that same value. "The same" here means object identity: the same reference, not a copy.
Seeing the Sharing in Action
Create these four files in one folder and run node main.js. Node.js 22 or later supports the with syntax without flags.
{
"appName": "Inventory",
"version": 3,
"features": ["search", "export"]
}Save that as config.json. Then add the modules:
// a.js
import config from "./config.json" with { type: "json" };
config.version = 4;
config.features.push("audit");
console.log("a.js set version to", config.version);// b.js
import config from "./config.json" with { type: "json" };
console.log("b.js sees version", config.version);
console.log("b.js sees features", config.features);// main.js
import "./a.js";
import "./b.js";
import config from "./config.json" with { type: "json" };
const again = await import("./config.json", { with: { type: "json" } });
console.log("same object?", again.default === config);Add a package.json containing { "type": "module" } so Node treats .js files as ES modules. The output is:
a.js set version to 4
b.js sees version 4
b.js sees features [ 'search', 'export', 'audit' ]
same object? trueThree details matter here.
- Evaluation order.
a.jsruns beforeb.jsbecause module evaluation is depth-first, in the order the import declarations appear. If you swap the two imports inmain.js,b.jsprints version 3. Code that relies on a shared JSON object being mutated is therefore sensitive to import order, and that dependency is easy to break during a refactor. - Nested values are shared too. The
featuresarray is part of the same object graph, sopushin one module shows up in the other. - Dynamic import hits the same cache.
import()resolves the specifier, finds the existing entry, and returns its namespace. The file is not read again.
What You Can and Cannot Change
The binding and the object behave differently, which can be confusing.
| Operation | Example | Result |
|---|---|---|
| Reassign the import binding | `config = {}` | `TypeError`: import bindings are read-only |
| Change a property | `config.version = 4` | Allowed, visible to all importers |
| Add or delete a property | `delete config.appName` | Allowed, visible to all importers |
| Mutate a nested array | `config.features.push("x")` | Allowed, visible to all importers |
| Change the namespace object | `ns.default = {}` (with `import * as ns`) | `TypeError`: namespace objects are sealed |
The read-only binding protects only the name. The parsed value is an ordinary, extensible, unfrozen object, exactly what JSON.parse would return. No runtime freezes JSON modules for you.
The File Is Not Reread
Caching also means changes to the file on disk after the first import are invisible. Calling import() again with the same URL returns the stale object. Node.js gives you no supported API to evict an entry from the ES module cache. This is different from CommonJS, where you could delete keys from require.cache.
Cache Busting with Query Strings
The cache key is the full URL, so a different query string creates a different module:
// reload.js
async function loadFresh(path) {
const url = new URL(path, import.meta.url);
url.searchParams.set("t", Date.now().toString());
const module = await import(url.href, { with: { type: "json" } });
return module.default;
}
const first = await loadFresh("./config.json");
const second = await loadFresh("./config.json");
console.log(first === second); // false: two different URLs, two entriesThis works in browsers and in Node.js, but every call adds a new entry to the module map that is never removed. In a long-running server that reloads configuration often, those entries add up as a memory leak. For data that changes at runtime, reading the file yourself is the better tool. A later chapter compares those options.
Where "One Instance" Ends
"One instance" holds within a single module map, and environments keep several maps:
- Each realm has its own map. A Web Worker, an
iframe, a Node.jsworker_threadsworker, and avmcontext each parse the JSON separately and get their own objects. Mutations do not cross that boundary. - Different URLs mean different instances.
./config.jsonand./config.json?v=1are separate entries. Symlinks in Node.js usually resolve to the real path, so two links to one file normally share an instance. Flags such as--preserve-symlinkschange that. - Duplicate package copies. If two versions of a dependency each ship
data.jsonin differentnode_modulesfolders, you get two objects. You might expect one shared object and still get two. - Bundlers. A bundler usually inlines the JSON as an object literal inside one module and keeps the same sharing semantics within a bundle. Separate bundles or chunks that each inline the file end up with separate copies.
Defending Against Accidental Mutation
You have three common choices. Which one fits depends on whether consumers ever need to write.
Freeze at the Source
Wrap the JSON in a JavaScript module that deep-freezes it, and have the rest of the code import from the wrapper:
// config.js
import raw from "./config.json" with { type: "json" };
function deepFreeze(value) {
if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
Object.freeze(value);
for (const key of Object.keys(value)) {
deepFreeze(value[key]);
}
}
return value;
}
export default deepFreeze(raw);// use-config.js
import config from "./config.js";
try {
config.version = 99;
} catch (error) {
console.log(error.constructor.name); // TypeError (modules run in strict mode)
}
console.log(config.version); // 3Writes throw because module code always runs in strict mode. Be aware that this freezes the shared object in place, so any other module that imports config.json directly also sees a frozen object.
Copy Before Mutating
If one consumer needs a private, editable version, clone it:
import config from "./config.json" with { type: "json" };
const local = structuredClone(config);
local.features.push("beta");
console.log(config.features.length, local.features.length); // 2 3structuredClone is a good fit because JSON values contain only plain objects, arrays, strings, numbers, booleans, and null, and it copies all of them deeply.
Export a Factory
When callers routinely need fresh objects, export a function instead of the data:
// defaults.js
import raw from "./config.json" with { type: "json" };
export function createConfig(overrides = {}) {
return { ...structuredClone(raw), ...overrides };
}| Approach | Cost | Best when |
|---|---|---|
| Deep freeze once | One traversal at startup | Data is read-only for the whole app |
| `structuredClone` per consumer | One copy per consumer | A few modules need private edits |
| Factory function | One copy per call | Callers routinely need fresh, customized objects |
| Read the file with `fs` or `fetch` | I/O on every load | Data changes while the program runs |
Exercise
main.js contains import "./b.js"; import "./a.js"; in that order, using the a.js and b.js files from this chapter. What does b.js print for config.version and config.features, and why?
Show answer
It prints version 3 and features [ 'search', 'export' ]. Modules evaluate depth-first in the order their import declarations appear, so b.js runs before a.js has mutated the shared object. The object is still shared, so code that runs after a.js would see version 4.
Exercise
A Node.js server calls await import("./flags.json", { with: { type: "json" } }) inside a request handler so that edits to flags.json take effect without a restart. Why does this not work, and what are two ways to fix it, along with the drawback of each?
Show answer
After the first call the module map caches the parsed object, so later calls return the same stale object and the file is never reread. One fix appends a changing query string to the URL. That forces a new module each time, but every entry stays in the module map forever and memory grows. The other fix reads the file with fs.promises.readFile and JSON.parse on each request or on a timer. That always returns fresh data, but it costs file I/O and you have to handle read and parse errors yourself.
Exercise
A module does import data from "./table.json" with { type: "json" }; data = data.filter(x => x.active);. What happens, and how would you rewrite it?
Show answer
It throws a TypeError, because import bindings are read-only and cannot be reassigned. Store the result in a new variable instead, for example const active = data.filter(x => x.active);. filter returns a new array, so the shared object stays unchanged.