Sub topic 4
Why the Type Attribute Is Required
This chapter assumes you know how ES modules are fetched and linked, what a JSON module is, and how the with { type: "json" } clause is written. Those topics were covered in the earlier chapters. Here we look at why the language makes you write that clause at all, and what goes wrong without it.
The question the attribute answers
When you write import config from "./config.json", the .json ending looks like enough information. A human reader knows the file is JSON. The JavaScript host (the browser or Node.js) does not trust the ending, and on the web it can't.
A URL is an opaque string. A web server can answer a request for /config.json with any bytes and any Content-Type header it likes. Browsers have never used file extensions to decide how to treat a response. They use the MIME type the server sends. A response with Content-Type: application/json is JSON. A response with Content-Type: text/javascript is a script, whatever the URL ends with.
That leaves a problem. If the host picks the module type from the server's response, then the server decides whether your import runs code. The type attribute moves that decision to the importer. You state what you expect, and the host refuses to load anything else.
The attack the attribute prevents
Developers think of importing JSON as safe. It reads data and runs no code. People import JSON from places they would never load a script from: a CDN with translation files, a partner's API, a configuration service run by another team.
Picture an early version of JSON modules where the browser trusted the MIME type and no attribute existed:
- Your page imports
https://cdn.example.com/locales/en.json. - You expect a data object, so you never audit that CDN the way you would audit a script source.
- The CDN is compromised, or the path is taken over, and the server starts responding with
Content-Type: text/javascriptand a body of attacker code. - The browser sees a JavaScript MIME type, treats the response as a JavaScript module, and evaluates it with your page's full privileges. It can read cookies the page can see, rewrite the DOM, and send data anywhere.
The import statement in your source never changed. Something you meant as a data read became remote code execution. This is a privilege escalation: a resource that should only have been able to supply data got the ability to run code.
With the attribute, the outcome depends only on your source code. with { type: "json" } means "this must be JSON". If the response is anything else, the load fails before evaluation, so attacker code never runs.
How the host enforces it
The check is simple, and it applies in both directions.
The second direction matters too. Leaving out the attribute does not mean "figure it out". It means "this must be JavaScript". So a JSON file served correctly as application/json fails when imported without the attribute. Browsers report a message such as "Expected a JavaScript module script but the server responded with a MIME type of application/json". If the host guessed and accepted it as JSON, the code would only work while the server kept sending the right header, and the opposite swap from the attack above would become possible.
| Declared in import | Server sends | Result |
|---|---|---|
| `type: "json"` | `application/json` | Loads as a JSON module |
| `type: "json"` | `text/javascript` | Fails, no code runs |
| none | `text/javascript` | Loads as a JavaScript module |
| none | `application/json` | Fails, JSON is not accepted as JavaScript |
| `type: "yaml"` | anything | Fails, unsupported type |
In the HTML specification the module map, the browser's cache of loaded modules, is keyed by both the URL and the module type. A request for a URL as JSON and a request for the same URL as JavaScript are separate entries. A JSON load can't be satisfied from a cached script, and a script load can't be satisfied from cached JSON.
The same rule in Node.js
Node.js reads modules from disk, and files have no MIME type there. Node could have used the .json extension and skipped the attribute. It requires the attribute anyway, for two reasons. Code that runs in browsers and in Node.js should behave the same way. Node also supports custom loaders and http:-style resolution, where the extension tells you nothing about the content.
Node.js infers a format from the extension and then checks that format against the attribute. You can see the three failure cases with a short script. Put it next to the config.json from earlier chapters and a helper.js file containing export const x = 1;.
// check.mjs (run with: node check.mjs)
async function attempt(label, specifier, options) {
try {
await import(specifier, options);
console.log(`${label}: loaded`);
} catch (err) {
console.log(`${label}: ${err.code}`);
}
}
await attempt("JSON, no attribute", "./config.json");
await attempt("JSON, type json", "./config.json", { with: { type: "json" } });
await attempt("JS, type json", "./helper.js", { with: { type: "json" } });
await attempt("JSON, type yaml", "./config.json", { with: { type: "yaml" } });On current Node.js releases (22 and later) the output is:
JSON, no attribute: ERR_IMPORT_ATTRIBUTE_MISSING
JSON, type json: loaded
JS, type json: ERR_IMPORT_ATTRIBUTE_TYPE_INCOMPATIBLE
JSON, type yaml: ERR_IMPORT_ATTRIBUTE_UNSUPPORTEDA later chapter covers these errors and their messages in detail. The point here is that the rules match the browser's: the declared type must match the actual format, and leaving the attribute out means JavaScript.
Why an inline attribute and not some other signal
The design committee looked at other ways to carry the expected type. Comparing them explains the syntax you now write.
| Option | Problem |
|---|---|
| Trust the file extension | URLs have no reliable extensions on the web, and servers choose the content type. |
| Trust the MIME type alone | This is the attack described above: the server decides whether code runs. |
| Put the type in the specifier, such as `"json:./config.json"` | It mixes type into the URL namespace and conflicts with import maps and existing URL schemes. |
| Configure it out of band, for example in a manifest | The expectation sits away from the import, so a reader can't tell from the statement whether code may run. |
| Inline attribute on the import | The expectation sits next to the import, the host can enforce it, and other types can be added later. |
The inline form also extends to other module types. type: "css" for CSS module scripts uses the same mechanism, as a later chapter shows.
ECMAScript requires hosts to reject attribute keys they don't support, so a typo such as { typ: "json" } fails loudly rather than being ignored. If unknown keys were skipped, a misspelled attribute would quietly remove the protection you thought you had.
What the attribute does not protect against
The type check guarantees one thing: a JSON import never executes code. It does not check that the data is correct. A compromised server can still send valid JSON with harmful values, such as a URL pointing to an attacker's domain or a translation string containing markup. If your code passes those values to innerHTML or eval, or uses them as a redirect target, you have a separate injection problem. Validate untrusted JSON the same way you would validate a fetch response. The attribute also does not stop the request being sent, so it does nothing for privacy or availability.
Exercise
A teammate removes with { type: "json" } from import strings from "https://cdn.example.com/en.json" because "the file ends in .json anyway". The CDN correctly serves application/json. What happens in the browser, and what would change if the CDN were later compromised to serve JavaScript?
Show answer
With the CDN serving application/json, the import fails at once, because an import without a type attribute must be a JavaScript module and JSON is not accepted as JavaScript. If the CDN were compromised to serve text/javascript, the same import would succeed and run the attacker's code with the page's privileges. The attribute is what turns that case into a failed load.
Exercise
In Node.js, import data from "./data.js" with { type: "json" } fails even though data.js contains only {"a": 1}. Why, and how do you fix it?
Show answer
Node.js infers the format from the .js extension as JavaScript, and that conflicts with the declared type json, so it throws ERRIMPORTATTRIBUTETYPEINCOMPATIBLE. Rename the file to data.json, or drop the attribute and turn the file into a real JavaScript module, for example export default {"a": 1};.
Exercise
An import uses with { type: "json" } to load a remote config, and the app then sets location.href = config.loginUrl. Is the app safe from a compromised config server?
Show answer
No. The attribute guarantees that no code from the server is executed, but the server can still send valid JSON with a malicious loginUrl and send users to a phishing site. The app has to validate the value, for example by checking it against an allowlist of origins.