Sub topic 9
When Imports Fail: Common Errors and Their Causes
This chapter assumes you already know static and dynamic import with with { type: "json" }, and that a JSON module exposes a single default export. It also assumes you can run code in Node.js or a browser and read a stack trace. The goal here is diagnosis. When a JSON import fails, the error message usually tells you which stage of loading broke. Once you know the stage, the fix is usually obvious.
Where in the Pipeline Each Error Comes From
A JSON import goes through several stages before your code sees the data. The engine parses the importing module and reads its attributes. The host (the browser or Node.js) resolves the specifier and fetches the resource. It then checks the response against the declared type and parses the JSON text. Finally it links the module and makes the default export available. Each failure category maps to one of these stages.
One rule matters more than the rest. With static imports, a failure at any stage stops the entire module graph before any of its code runs. A try/catch around the code in the importing module can't catch it, because that code never runs. With dynamic import(), the same failures arrive as a rejected promise, which you can catch.
Missing Type Attribute
This is the most common error. You import a .json file without the attribute:
import config from "./config.json"; // no `with { type: "json" }`The host fetches the file and sees that it is JSON. The import didn't declare that type, so the host refuses to treat it as a module. A file extension or a server response alone never turns a resource into a JSON module. Typical messages:
| Environment | Typical message |
|---|---|
| Node.js | `TypeError [ERR_IMPORT_ATTRIBUTE_MISSING]: Module "file:///app/config.json" needs an import attribute of "type: json"` |
| Chromium | `Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "application/json"` |
| Firefox / Safari | A similar message stating that the MIME type is not allowed for a JavaScript module |
The browser message can mislead you. It sounds like a server misconfiguration, but the server is correct. Without the attribute the browser expects JavaScript, and it rejects the JSON MIME type. Add with { type: "json" } to fix it.
Type Mismatch in the Other Direction
The reverse mistake also fails. If you declare type: "json" on something that is not JSON, the host rejects it:
import helpers from "./helpers.js" with { type: "json" };Node.js reports ERR_IMPORT_ATTRIBUTE_TYPE_INCOMPATIBLE. A browser fails because the server sends text/javascript and a JSON module requires a JSON MIME type. The attribute is a contract: the declared type must match what actually arrives. The previous chapter on why the attribute is required explains the security reason for this.
Bad MIME Type from the Server
In browsers the MIME type, sent in the Content-Type header, decides whether the resource counts as JSON. The file extension doesn't count. The browser accepts application/json, text/json, and any +json type such as application/ld+json. Two server problems come up often:
- The server serves
.jsonastext/plainorapplication/octet-stream. The import fails even though the file contents are valid JSON. Fix the server's MIME mapping. - The server returns an HTML page instead of the file. Single-page app servers often answer unknown paths with
index.htmland a200status. The error then mentionstext/html. In practice this means the path is wrong, not the MIME configuration.
Invalid JSON
If the type check passes but the text isn't valid JSON, the host throws a SyntaxError while parsing. JSON modules use strict JSON parsing, the same rules as JSON.parse. That means these all fail:
- Trailing commas:
{"a": 1,} - Comments:
// noteor/* ... */ - Single-quoted strings or unquoted keys:
{'a': 1},{a: 1} NaN,Infinity, orundefinedas values
A JSON file shared with a tool that accepts JSONC (JSON with comments), such as many editor config files, often has comments or trailing commas. It loads fine in that tool and fails as a module. Node.js includes the file path in the error, which helps. Browsers may only report the position in the text.
A leading byte-order mark (BOM) is a special case. The HTML specification decodes JSON module text as UTF-8 and strips a BOM. Some older tools and runtimes didn't. If a file works in one environment and fails in another with an error at position 0, check for a BOM.
Unsupported Attributes
Hosts accept only the attribute keys they recognize. Today that is type in both browsers and Node.js. An unknown key, or an unknown value for type, fails:
// Unknown key: rejected by the host
import data from "./data.json" with { type: "json", integrity: "sha384-..." };
// Unknown type value: rejected
import doc from "./doc.xml" with { type: "xml" };Node.js reports unsupported type values as ERR_IMPORT_ATTRIBUTE_UNSUPPORTED. For unknown keys, engines raise a SyntaxError for static imports and reject the promise for dynamic imports. Unknown attributes are never silently ignored. That's deliberate: if the host ignored an attribute you were relying on, the import would quietly behave differently from what you wrote.
Dynamic import() has some extra shape errors that throw a TypeError through the returned promise:
| Mistake | Example | Result |
|---|---|---|
| Options is not an object | `import(url, "json")` | Rejected with `TypeError` |
| `with` is not an object | `import(url, { with: "json" })` | Rejected with `TypeError` |
| Attribute value is not a string | `import(url, { with: { type: 1 } })` | Rejected with `TypeError` |
| Old key name | `import(url, { assert: { type: "json" } })` | Depends on runtime; current runtimes ignore `assert`, so you get a missing-type error |
The last row catches people during migrations. The legacy-syntax chapter covers this in more detail.
Not Found and Named Export Errors
Two more errors aren't specific to JSON, but they show up in JSON imports all the time.
A wrong path gives ERR_MODULE_NOT_FOUND in Node.js and a failed network request in the browser. Remember that relative specifiers are resolved against the importing module's URL, not the current working directory or the page URL. That's a common source of confusion with dynamic imports inside utility modules.
A named import such as import { appName } from "./config.json" with { type: "json" } fails at link time with SyntaxError: The requested module './config.json' does not provide an export named 'appName'. The file loads and parses fine. The failure comes from the binding step.
Handling Failures at Runtime
You can't catch static import failures from inside the module graph, so use dynamic import() when a JSON file might be missing or malformed. The following Node.js script loads an optional override file. It falls back to defaults when the file is absent and re-throws every other error:
// load-config.mjs
const defaults = { appName: "Inventory", version: 3, features: [] };
async function loadOverrides(path) {
try {
const mod = await import(path, { with: { type: "json" } });
return mod.default;
} catch (err) {
if (err.code === "ERR_MODULE_NOT_FOUND") {
return {}; // optional file: absent is fine
}
if (err instanceof SyntaxError) {
throw new Error(`Malformed JSON in ${path}: ${err.message}`, { cause: err });
}
throw err; // type mismatch, unsupported attribute, etc.
}
}
const overrides = await loadOverrides("./config.local.json");
const config = { ...defaults, ...overrides };
console.log(config);Save it as load-config.mjs and run node load-config.mjs. Then create config.local.json with {"version": 5} and run it again. Finally, add a trailing comma to that file to see the malformed-JSON branch.
This caching also applies to successful loads, and it's one reason the file-reading alternatives covered later suit data that changes while the program runs.
Quick Diagnosis Reference
| Symptom | Likely cause | Fix |
|---|---|---|
| Message mentions `application/json` while expecting JavaScript | Missing `with { type: "json" }` | Add the attribute |
| Message mentions `text/html` | Wrong path; server returned a fallback page | Correct the path |
| Message mentions `text/plain` or `octet-stream` | Server MIME mapping | Serve `.json` as `application/json` |
| `SyntaxError` with a text position | Comments, trailing commas, or other non-JSON syntax | Make the file strict JSON |
| `does not provide an export named` | Named import from JSON | Import the default export and destructure it |
| `ERR_IMPORT_ATTRIBUTE_UNSUPPORTED` or unknown-key error | Unsupported key or type value | Use only `type: "json"` |
Exercise
A page loads import settings from "/api/settings.json" with { type: "json" };. The console says the server responded with a MIME type of "text/html", and the Network tab shows status 200. The file exists in your repository at public/settings.json. What is most likely wrong, and why doesn't the status code rule out a path problem?
Show answer
The URL probably doesn't match where the server serves the file. public/settings.json is typically served at /settings.json, not /api/settings.json. Many single-page app servers answer unknown paths with index.html and a 200 status, so the browser receives HTML and rejects it as a JSON module. Fix the specifier to /settings.json. The 200 status means only that the server returned something, not that it returned the file you asked for.
Exercise
You wrap a static import data from "./data.json" with { type: "json" }; at the top of main.js in a mental model where a try/catch later in main.js will handle a malformed data.json. Why doesn't this work, and how would you restructure it?
Show answer
Static imports are fetched, parsed, and linked before any code in main.js runs. A JSON SyntaxError fails the whole module graph, and the try/catch never runs. Replace the static import with await import("./data.json", { with: { type: "json" } }) inside a try block and read .default from the result. The failure then arrives as a rejected promise that catch can handle.
Exercise
A team migrating old code changes import(path, { assert: { type: "json" } }) to run on a current Node.js release and gets an error saying the module needs an import attribute of "type: json". The attribute is clearly present. What happened?
Show answer
Current runtimes no longer recognize the assert key in the options object. They ignore it, so the import arrives with no type attribute at all, and the host reports a missing type. Rename the key: import(path, { with: { type: "json" } }).