Sub topic 11
JSON Modules in the Browser: MIME Types and Servers
This chapter assumes you can already write a static import ... with { type: "json" } declaration and a dynamic import() call with an options object. You also need to be able to serve files over HTTP from a local server. Here the focus moves from syntax to the network: what a browser checks when it fetches a JSON module, why a correct import can still fail because of server configuration, and how to diagnose and fix those failures.
The Browser Ignores File Extensions
Browsers do not use the .json extension to decide what a file is. The extension in your import specifier is just part of a URL. The browser trusts the Content-Type response header that the server sends, which holds the file's MIME type (a label such as application/json or text/javascript).
When a module request completes, the browser compares two things:
- The module type your code asked for. Without a
typeattribute this is JavaScript. Withwith { type: "json" }it is JSON. - The MIME type in the server's
Content-Typeheader.
If they don't match, the browser refuses to create the module, and every module that depends on it fails as well. This check is the security guarantee from the earlier chapter, enforced in practice. A response labeled as JSON can never run as script, and a script can never be loaded as if it were data.
Which MIME types count as JSON
The HTML specification accepts any "JSON MIME type" for a JSON module:
application/jsontext/json- any type whose subtype ends in
+json, such asapplication/ld+jsonorapplication/manifest+json
Parameters such as ; charset=utf-8 are allowed. The body is always decoded as UTF-8, whatever charset the header claims.
What happens in each combination
| Import written as | Server sends `Content-Type` | Result |
|---|---|---|
| `with { type: "json" }` | `application/json` | Loads; default export is the parsed value |
| `with { type: "json" }` | `application/vnd.api+json` | Loads (subtype ends in `+json`) |
| `with { type: "json" }` | `text/plain` | Fails: MIME type is not JSON |
| `with { type: "json" }` | `text/javascript` | Fails: the server claims script, you asked for JSON |
| no attribute | `application/json` | Fails: a JavaScript module needs a JavaScript MIME type |
| no attribute | `text/javascript` (body is JSON) | Tries to parse the JSON as JavaScript, usually a `SyntaxError` |
The last row explains why the attribute matters. If a JavaScript file is served under a .json URL, it executes only when it is imported without the attribute, so it can never execute through an import that you marked as data.
Serving JSON Correctly
Most servers already map .json to application/json, so a typical setup works with no changes:
- Python's
python3 -m http.serveruses the system MIME table, which maps.jsontoapplication/jsonon common platforms. - Express's
express.staticand most static hosts (Netlify, GitHub Pages, S3 with correct metadata) sendapplication/json. - Nginx's default
mime.typesfile containsapplication/json json;.
Problems come from custom servers, misconfigured object storage, and API endpoints that send JSON as text/plain or text/html. If you write your own server, set the header explicitly. The following Node.js server uses only built-in modules and serves a small demo:
// server.mjs — run with: node server.mjs, then open http://localhost:8080
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
import { extname, join, normalize } from "node:path";
const root = process.cwd();
const types = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
};
createServer(async (req, res) => {
const urlPath = new URL(req.url, "http://localhost").pathname;
const safePath = normalize(urlPath === "/" ? "/index.html" : urlPath);
const filePath = join(root, safePath);
if (!filePath.startsWith(root)) {
res.writeHead(403).end();
return;
}
try {
const body = await readFile(filePath);
const type = types[extname(filePath)] ?? "application/octet-stream";
res.writeHead(200, { "Content-Type": type });
res.end(body);
} catch {
res.writeHead(404, { "Content-Type": "text/plain" }).end("Not found");
}
}).listen(8080);Put these files next to it:
<!-- index.html -->
<!doctype html>
<html>
<body>
<h1 id="title"></h1>
<script type="module" src="./main.js"></script>
</body>
</html>// main.js
import config from "./config.json" with { type: "json" };
document.getElementById("title").textContent =
`${config.appName} v${config.version}`;Use the config.json from earlier chapters. To see the failure for yourself, change the .json entry to "text/plain", restart the server, and reload. The heading stays empty and the console reports a MIME type error.
CORS, Origins, and file:// URLs
Module requests use CORS mode (Cross-Origin Resource Sharing, the rules for whether one origin may read another's responses). This applies to JSON modules in the same way it applies to JavaScript modules:
- Same-origin imports just work.
- A cross-origin JSON module, for example
https://cdn.example.com/data.json, needs the server to send anAccess-Control-Allow-Originheader that allows your page's origin. Without it the import fails, even when the MIME type is correct. - Opening
index.htmldirectly from disk (file:///...) fails in Chromium-based browsers, because module scripts can't load fromfile://URLs. Always use a local HTTP server.
Credentials follow the module script rules. Same-origin requests include cookies, and cross-origin requests include them only if the importing <script> has crossorigin="use-credentials" and the server allows credentials.
Import Maps Work Too
Import maps remap the specifier before the fetch, and the type attribute travels with the request. You can give a JSON file a bare name:
<script type="importmap">
{
"imports": {
"app-config": "/data/config.json"
}
}
</script>
<script type="module">
import config from "app-config" with { type: "json" };
console.log(config.appName);
</script>The MIME check still applies to the final URL, /data/config.json.
Module Map Keys Include the Type
The browser caches modules in a per-document module map. The key for that map is the pair of URL and module type, not the URL alone. Two imports of the same URL with the same type share one module instance, which is the shared-object behavior you saw in the caching chapter. An import of that URL without the attribute is a different entry, and in practice it fails the JavaScript MIME check. The browser's HTTP cache works separately from the module map. A page reload clears the module map, but the HTTP cache may still serve an old copy of the file, so watch your Cache-Control headers while developing.
Browser Support and Fallbacks
With the with keyword, JSON modules are supported in Chrome and Edge 123+, Safari 17.2+, and Firefox 138+. Chromium shipped JSON modules earlier under the old assert syntax, which current versions no longer accept.
Older browsers fail in two different ways, and you should plan for each:
- Static import: the
withclause is a syntax error in a browser that lacks support, so the entire module fails to parse. You can't catch that from inside the same module. - Dynamic import: a browser that doesn't understand the options argument ignores it, treats the file as JavaScript, and rejects on the MIME check. That rejection can be caught.
When you can't rely on support, load data through a dynamic import with a fallback to fetch:
// load-json.js
export async function loadJson(url) {
try {
const mod = await import(url, { with: { type: "json" } });
return mod.default;
} catch (err) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status} loading ${url}`);
}
return response.json();
}
}The fallback also gives you a fresh object instead of the shared cached module. If you use it in a modern browser too, keep that difference in mind. Production apps often skip this problem by bundling, because the bundler inlines the JSON at build time, as a later chapter explains.
Troubleshooting Checklist
| Symptom in console | Likely cause | Fix |
|---|---|---|
| Expected a JSON module script but the server responded with MIME type "text/plain" | Server mislabels `.json` | Set `Content-Type: application/json` |
| Expected a JavaScript module script but the server responded with MIME type "application/json" | Missing `with { type: "json" }` | Add the attribute |
| CORS policy: No 'Access-Control-Allow-Origin' header | Cross-origin JSON without CORS headers | Configure CORS on the data server or serve it same-origin |
| SyntaxError: Unexpected identifier 'with' (or similar) | Browser too old for import attributes | Upgrade, bundle, or use the `fetch` fallback |
| SyntaxError while parsing JSON | Body isn't valid JSON (comments, trailing commas, an HTML error page) | Fix the file; check that the URL doesn't return an HTML 404 page |
The browser's exact wording differs from these messages, but the meaning is the same.
Exercise
Your page runs import data from "https://api.example.com/v1/items" with { type: "json" }. The response body is valid JSON, CORS headers are correct, and the server sends Content-Type: application/vnd.example.items+json. Does the import succeed? What would change if the server sent text/html?
Show answer
It succeeds. The subtype ends in +json, so the browser counts it as a JSON MIME type. With text/html the MIME check fails, the browser rejects the module, and the importing module graph fails to load. This happens even though the body is valid JSON, because the browser never looks at the body to decide the type.
Exercise
A teammate opens index.html by double-clicking it. The file contains a module script that imports ./config.json with { type: "json" }. Nothing renders in Chrome. Give the cause and two ways to fix it.
Show answer
Module scripts can't load from file:// URLs in Chromium-based browsers, so the module request is blocked before any MIME check happens. One fix is to serve the folder over HTTP, for example with python3 -m http.server or the Node server in this chapter, and open http://localhost:.... Another is to bundle the app so the JSON is inlined into a single script. Even then, a local server is the reliable way to test.
Exercise
Why does await import(url, { with: { type: "json" } }) inside try/catch work as a feature-detection strategy, while a static import ... with { type: "json" } does not?
Show answer
A static import with with is part of the module's syntax. An older browser fails to parse the whole module, so no code in that module runs and nothing can catch the error. A dynamic import is an ordinary expression. An older browser ignores the unknown second argument, loads the file as JavaScript, and rejects the returned promise on the MIME check. Your catch block can then fall back to fetch.