Sub topic 12
JSON Modules in Node.js
This chapter assumes you know ES module import/export, how to run .mjs files or set "type": "module" in package.json, and the with { type: "json" } syntax covered earlier. It covers what is specific to Node.js: how Node decides a file is JSON, which versions support what, the error codes it raises, how JSON modules fit with CommonJS, and how Node's module cache behaves.
How Node Decides a File Is JSON
Browsers decide a module's format from the HTTP Content-Type header. Node has no HTTP response for local files, so it uses the file extension. When Node resolves a specifier to a file: URL whose path ends in .json, it assigns that module the json format. It then checks that format against the type import attribute.
The extension and the attribute have to agree:
- A
.jsonfile imported withouttype: "json"is rejected. - A
.jsor.mjsfile imported withtype: "json"is rejected. - A
.jsonfile imported withtype: "json"is read as UTF-8, parsed with JSON semantics, and wrapped in a module whose only export isdefault.
Node determines the format from the URL's path, so a query string or hash does not change it. ./config.json?v=2 is still treated as JSON. You will use this later for cache busting.
Node also accepts data: URLs with the application/json MIME type. In that case the MIME type sets the format, because there is no extension to read:
import data from 'data:application/json,{"ok":true}' with { type: "json" };
console.log(data.ok); // trueVersion History
Node's support for JSON modules changed several times, and old tutorials and Stack Overflow answers often show syntax that no longer runs. Pin your expectations to the Node version you deploy.
| Node.js version | What changed |
|---|---|
| 12.x to 16.x (early) | JSON modules only behind the `--experimental-json-modules` flag |
| 16.14.0, 17.1.0 | `assert { type: "json" }` supported without a flag; the attribute is required |
| 18.20.0, 20.10.0, 21.0.0 | `with { type: "json" }` syntax added alongside `assert` |
| 22.0.0 | `assert` syntax removed; only `with` is accepted |
| 22.12.0, 23.1.0 | JSON modules and import attributes marked stable; no more `ExperimentalWarning` |
On the releases in between, a JSON import works but prints a line such as ExperimentalWarning: Importing JSON modules is an experimental feature. It is only a warning and does not change behavior. If your test runner fails on stderr output, upgrade Node rather than suppressing every warning with --no-warnings.
To make the requirement explicit, declare it in package.json:
{
"name": "inventory",
"type": "module",
"engines": {
"node": ">=20.10.0"
}
}A Minimal Working Setup
With the config.json from earlier chapters next to it, this file runs as-is on any Node version from 20.10.0 onward:
// main.mjs
import config from "./config.json" with { type: "json" };
console.log(`${config.appName} v${config.version}`);
console.log(process.versions.node);node main.mjsRelative specifiers resolve against the importing file's URL, not the current working directory. Running node src/main.mjs from the project root still finds src/config.json. If you build the path from process.cwd() instead, you are using a different and more fragile lookup.
JSON files inside packages work the same way, but they go through the package's exports field. If a package defines exports and doesn't list ./data.json, then import x from "some-pkg/data.json" with { type: "json" } fails with ERR_PACKAGE_PATH_NOT_EXPORTED, even though the file exists on disk.
Node's Error Codes
Node throws errors with stable code properties, which are better to match on than message text. The names changed when assertions became attributes. Older releases use ERR_IMPORT_ASSERTION_* for the same conditions.
| Situation | Error code | Error type |
|---|---|---|
| `.json` file imported without `type` | `ERR_IMPORT_ATTRIBUTE_MISSING` | `TypeError` |
| `type: "json"` on a non-JSON file | `ERR_IMPORT_ATTRIBUTE_TYPE_INCOMPATIBLE` | `TypeError` |
| Unknown `type` value, such as `"css"` | `ERR_IMPORT_ATTRIBUTE_UNSUPPORTED` | `TypeError` |
| Attribute key other than `type` | `ERR_IMPORT_ATTRIBUTE_UNSUPPORTED` | `TypeError` |
| File contents are not valid JSON | none | `SyntaxError` |
| File not found | `ERR_MODULE_NOT_FOUND` | `Error` |
Node supports only the type key. Adding an attribute that another tool understands, for example a bundler-specific key, makes Node reject the import.
A static import fails while the module graph is being linked, before any of your code runs, so you can't wrap it in try/catch. A dynamic import fails when its promise rejects, so you can handle that:
// errors.mjs
async function tryImport(specifier, options) {
try {
await import(specifier, options);
console.log(`${specifier}: ok`);
} catch (err) {
console.log(`${specifier}: ${err.name} ${err.code ?? ""}`);
}
}
await tryImport("./config.json"); // missing type
await tryImport("./errors.mjs", { with: { type: "json" } }); // incompatible
await tryImport("./config.json", { with: { type: "css" } }); // unsupported
await tryImport("./config.json", { with: { type: "json" } }); // okRunning it on a current Node release prints:
./config.json: TypeError ERR_IMPORT_ATTRIBUTE_MISSING
./errors.mjs: TypeError ERR_IMPORT_ATTRIBUTE_TYPE_INCOMPATIBLE
./config.json: TypeError ERR_IMPORT_ATTRIBUTE_UNSUPPORTED
./config.json: okCommonJS Interop
CommonJS require() has loaded JSON since Node's early days, and it needs no attribute:
// legacy.cjs
const config = require("./config.json");
console.log(config.appName);Inside an ES module, require does not exist, but you can create one with createRequire. This is a practical fallback when you must support Node versions where neither assert nor with works everywhere:
// compat.mjs
import { createRequire } from "node:module";
const require = createRequire(import.meta.url);
const config = require("./config.json");
console.log(config.version);The two loaders keep separate caches. A file loaded with require() and the same file loaded with import ... with { type: "json" } produce two different objects. If one part of your app mutates the require copy, the import copy does not change.
| Aspect | `import ... with { type: "json" }` | `require("./x.json")` |
|---|---|---|
| Attribute needed | Yes | No |
| Works in `.cjs` files | Only through dynamic `import()` | Yes |
| Cache | ESM cache, keyed by URL, not clearable | `require.cache`, keyed by path, deletable |
| Sync or async | Static: at link time. Dynamic: returns a promise | Synchronous |
| Works in browsers | Yes, same syntax | No |
CommonJS files can also load JSON modules through dynamic import(), because import() is available in both module systems:
// loader.cjs
(async () => {
const { default: config } = await import("./config.json", {
with: { type: "json" }
});
console.log(config.features);
})();The Module Cache and Reloading
The ES module cache in Node is keyed by the resolved URL and has no public API for removing entries. After a JSON module is loaded, it stays loaded for the life of the process, even if the file on disk changes. This is fine for static configuration. It causes problems for long-running processes that watch a config file and expect to pick up edits.
Because the cache key includes the query string, a new query string creates a new module instance:
// reload.mjs
async function loadFresh(path) {
const url = new URL(path, import.meta.url);
url.searchParams.set("t", String(Date.now()));
const mod = await import(url.href, { with: { type: "json" } });
return mod.default;
}
const first = await loadFresh("./config.json");
const second = await loadFresh("./config.json");
console.log(first === second); // falseThe CommonJS cache can be cleared with delete require.cache[require.resolve("./config.json")]. That only affects the require copy, never the ESM one.
Tests and Mocks
Test runners that run in Node inherit these rules. A test that mutates an imported config object changes that object for every later test in the same process, because they all share one module instance. Clone the object before modifying it, for example with structuredClone(config), or run each test file in its own process. Node's built-in test runner (node --test) runs each file in a separate process by default.
Exercise
A project runs on Node 22 and contains import pkg from "./package.json" assert { type: "json" };. What happens when you start it, and what is the fix?
Show answer
Node 22 removed the assert syntax, so the file fails to parse with a SyntaxError before anything runs. Replace assert with with: import pkg from "./package.json" with { type: "json" };.
Exercise
A file named settings.data contains valid JSON. Will import s from "./settings.data" with { type: "json" } work in Node, and why?
Show answer
No. Node determines the format from the file extension, and .data is not recognized as JSON. The import fails instead of being parsed as JSON. Rename the file to .json, or read it with fs.readFile and JSON.parse.
Exercise
Module A loads config.json with createRequire and sets config.debug = true. Module B then loads the same file with import config from "./config.json" with { type: "json" }. What does B see for config.debug, and why?
Show answer
B sees undefined (assuming the file has no debug key). The CommonJS loader and the ES module loader keep separate caches, so each creates its own object from the file. A's change only affects the require copy.
Exercise
Why can't you catch ERRIMPORTATTRIBUTE_MISSING from a static import with try/catch, and how would you handle it in code?
Show answer
Node links static imports before evaluating any module code, so the error happens before the try block runs and the whole module graph fails to load. Use dynamic import() inside try/catch (or attach .catch()), because its failure is a promise rejection at runtime.