Import JSON modules with import attributes
Use the type: json import attribute to load a JSON module in Node or a browser, with static or dynamic imports.
You have a config.json and you want its values in a module. You used to read it with fs and JSON.parse in Node, or fetch it in the browser. One import line does the job in both, with no readFileSync, no fetch and no .json() call.
// static.mjs
import config from './config.json' with { type: 'json' }
console.log(config.retries)With config.json containing { "name": "demo", "retries": 3 }, node static.mjs prints 3. The with { type: 'json' } clause is an import attribute.
It tells the engine to parse the file as JSON instead of running it as JavaScript. The Node documentation uses package.json as its own example, so the same line reads your package version.
The same line in the browser
A module script takes the same syntax. Save this page beside config.json and serve both over HTTP. Send application/json for the JSON file. The browser support table covers older browsers that lack the with syntax.
<p id="out"></p>
<script type="module">
import config from './config.json' with { type: 'json' }
document.querySelector('#out').textContent = `retries: ${config.retries}`
</script>Served that way, the page shows retries: 3. I also served the file as text/plain. Chromium logged Expected a JSON module script but the server responded with a MIME type of "text/plain" and rendered nothing.
Load it on demand
import() takes the attributes as a second argument, under the with key. It resolves to a module object, so the JSON sits on default.
// dynamic.mjs
const { default: config } = await import('./config.json', { with: { type: 'json' } })
console.log(config.name) // demoRunning node dynamic.mjs prints demo. Use this form when the file is large or only some code paths need it.
The object is shared
Within one module context, imports of the same resolved JSON module share its default object. If one module sets config.retries = 99, every other module sees 99, and I ran this with two files to confirm it. Copy the object with structuredClone(config) before you change it.
Three errors you will meet
- Leaving out the
withclause. Node throwsERR_IMPORT_ATTRIBUTE_MISSINGand says the module needs an import attribute oftype: json. The Node ESM documentation requires the attribute. JSON modules became stable in Node 22.12.0. - Importing a name. A JSON module has only a default export.
import { retries } from './config.json' with { type: 'json' }fails withdoes not provide an export named 'retries'. Import the default and destructure it. - Serving the file with the wrong content type. The browser example above shows the
text/plaincase. Check the response header in the network panel before you debug the import line.