Sub topic 15
Import Attributes and JSON Modules
This chapter assumes you know ES module syntax, the import() expression and its namespace object, try/catch with await, and how to run .mjs files in Node.js or serve modules to a browser. Earlier chapters showed that import() resolves to a namespace object and that a default export shows up as its default property. JSON modules follow those same rules. They add one requirement: you must tell the runtime what kind of file you expect to receive.
What Import Attributes Are
An import attribute is a key-value pair attached to an import. It gives the host (the browser or Node.js) extra information about how to load the module. At present the only attribute with broad support is type. Static imports put attributes after the specifier, behind the with keyword:
// main.mjs
import settings from './settings.json' with { type: 'json' };
console.log(settings.theme);Dynamic imports take the same attributes as an options object in the second argument:
// main.mjs
const { default: settings } = await import('./settings.json', {
with: { type: 'json' },
});
console.log(settings.theme);Both examples need a settings.json file next to main.mjs:
{
"theme": "dark",
"pageSize": 25,
"features": ["search", "export"]
}Run node main.mjs and it prints dark. The attribute does not change the specifier or how it resolves. It is a declaration of what you expect the resolved file to be.
Why the Runtime Requires `type: 'json'`
The type attribute is there for security. A browser decides how to treat a fetched module by its MIME type, not by its file extension. Suppose your code imports https://cdn.example.com/data.json and the runtime simply trusts whatever arrives. A compromised or misconfigured server could then reply with Content-Type: text/javascript and run arbitrary code inside your page. You meant to read data, and you would be executing a script.
When you write type: 'json', the host compares your declaration against the response:
- If the response is JSON, the runtime parses it and does not execute it.
- If the response turns out to be JavaScript, the import fails.
- If you leave out the attribute and the server sends JSON, the import also fails, because an unmarked import means "JavaScript module".
Node.js applies the same rule to local files, even though local files have no MIME header. It identifies the format from the extension and insists that the attribute match.
The Shape of a JSON Module
A JSON module has exactly one export, default. Its value is the parsed JSON. That value can be an object, an array, a string, a number, a boolean, or null. The module has no named exports, even when the top-level JSON value is an object:
// broken.mjs: fails at link time
import { theme } from './settings.json' with { type: 'json' };Node reports a SyntaxError saying the module does not provide an export named theme. Since this is a link-time error, no code in broken.mjs runs at all. The correct form imports the default export and destructures it afterward:
// fixed.mjs
import settings from './settings.json' with { type: 'json' };
const { theme, pageSize } = settings;
console.log(theme, pageSize); // dark 25The Parsed Object Is Shared
Earlier chapters showed that importing a specifier twice returns the same cached module instance. JSON modules are cached the same way. Each importer receives the same object, and that object is not frozen. If one module mutates it, every other module sees the change:
// a.mjs
import settings from './settings.json' with { type: 'json' };
settings.pageSize = 100;// b.mjs
import './a.mjs';
import settings from './settings.json' with { type: 'json' };
console.log(settings.pageSize); // 100, not 25Run node b.mjs to see it. The JSON file is read and parsed once per module graph, the first time it is imported. Editing the file afterward has no effect until the process or page reloads. For configuration that has to change at runtime, or that one module needs to modify privately, use structuredClone(settings) to get a copy, or read the file yourself with fetch() or fs.readFile().
Dynamic JSON Imports with Fallbacks
import() with attributes behaves like any other dynamic import. It returns a promise, and that promise rejects on a missing file, a network error, invalid JSON, or an attribute mismatch. The fallback pattern from the error-handling chapter carries over without changes:
// locales.mjs
export async function loadLocale(lang) {
try {
const mod = await import(`./locales/${lang}.json`, {
with: { type: 'json' },
});
return mod.default;
} catch (err) {
console.warn(`Locale "${lang}" unavailable (${err.code ?? err.name})`);
const fallback = await import('./locales/en.json', {
with: { type: 'json' },
});
return fallback.default;
}
}// main.mjs
import { loadLocale } from './locales.mjs';
const messages = await loadLocale('fr');
console.log(messages.greeting);For this to work you need locales/en.json containing { "greeting": "Hello" }. If locales/fr.json does not exist, the program logs a warning and prints Hello.
The options argument must be an object, and its with property must also be an object. If you pass a malformed argument, for example { with: 'json' }, the promise rejects with a TypeError and no loading starts. A JSON file with a syntax error rejects with a SyntaxError.
Common Errors and What They Mean
The table lists Node.js error codes. Browsers report the same conditions with less specific messages, usually a TypeError that mentions the MIME type.
| Situation | Node.js error | Fix |
|---|---|---|
| JSON imported without `with { type: 'json' }` | `ERR_IMPORT_ATTRIBUTE_MISSING` | Add the attribute |
| `type: 'json'` on a `.js` or `.mjs` file | `ERR_IMPORT_ATTRIBUTE_TYPE_INCOMPATIBLE` | Remove the attribute or point to the right file |
| Unknown type such as `type: 'css'` in Node | `ERR_IMPORT_ATTRIBUTE_UNSUPPORTED` | Use a type the host supports |
| Named import from a JSON module | `SyntaxError` (missing export) | Import `default` and destructure it |
| Using the old `assert` keyword | `SyntaxError` | Replace `assert` with `with` |
From `assert` to `with`
Older code and tutorials use import assertions:
import data from './data.json' assert { type: 'json' };The proposal was renamed and redesigned. The word "assert" suggested the attribute could only check a module and never affect how it loads, and that did not fit how hosts actually needed to use it. The standard keyword is now with. Node.js 22 removed support for assert, and Chromium-based browsers dropped it after with shipped. To migrate, search the codebase for assert { and replace it with with {. For dynamic imports, change { assert: { type: 'json' } } to { with: { type: 'json' } }.
Choosing Between JSON Modules and Reading Files
| Approach | Loaded | Cached | Works in browser and Node | Best for |
|---|---|---|---|---|
| Static `import ... with { type: 'json' }` | Before the module runs | Yes, shared | Yes | Fixed config that is always needed |
| `import(..., { with: { type: 'json' } })` | On demand | Yes, shared | Yes | Optional or per-locale data |
| `fetch(url).then(r => r.json())` | On demand | Only HTTP cache | Browser, and Node 18+ | Data that changes or comes from an API |
| `JSON.parse(await fs.readFile(...))` | On demand | No | Node only | Files that may change while running |
JSON modules suit data that ships with your code and stays the same for the life of the process. Bundlers can also inline static JSON imports or split dynamic ones into separate chunks, as described in the code-splitting chapter. Data that varies per request or must be reloaded belongs with fetch or the file system.
Some hosts support other type values. Chromium supports type: 'css', which returns a CSSStyleSheet as the default export. The pattern for these is the same: declare the type, then read default.
Exercise
A module contains import { version } from './package.json' with { type: 'json' };. It fails before any of its code runs. Why, and what is the smallest correct rewrite?
Show answer
A JSON module exposes only a default export, so asking for the named export version fails at link time with a SyntaxError, before evaluation starts. Rewrite it as import pkg from './package.json' with { type: 'json' }; const { version } = pkg;.
Exercise
Two modules import ./flags.json with type: 'json'. One sets flags.beta = true. Does the other see the change, and how would you give each module an independent copy?
Show answer
Yes. Both receive the same cached, unfrozen object, so the mutation is visible everywhere. Each module can call structuredClone(flags) (or structuredClone(mod.default)) and work on its own copy, or read the file with fetch or fs.readFile instead.
Exercise
Why does the runtime reject import('./data.json') when no attribute is given, even though the file is plainly JSON?
Show answer
An import without a type attribute declares that it expects JavaScript. Requiring an explicit type: 'json' means a server, or a mistake, cannot swap code in for data without the import failing. JSON is never executed, and a script is never accepted where data was declared.