More Node.js answers

by Danny
Published 3 min read

In ES modules you import JSON with an import attribute that says type json, or read the file and parse it yourself. Here is the syntax, the versions, and when to use each.

The short answer

#

In an ES module, a plain import of a .json file fails. Add an import attribute that tells Node.js the file is JSON. The parsed data arrives as the default export.


_10
import config from './config.json' with { type: 'json' };
_10
_10
console.log(config.port);

If you would rather avoid import attributes, read the file with fs and call JSON.parse.

Why it happens

#

In CommonJS, require('./config.json') has always worked, because require looks at the file extension and parses JSON for you. ES modules work differently. On the web, a server decides what a file is through its MIME type, not its extension, and importing a file should never run code you did not expect. So the language added import attributes: a way for your code to say "I expect this to be JSON". If the file turns out to be JavaScript, the import fails instead of running it.

Node.js follows the same rule. Without the attribute you get an error such as ERR_IMPORT_ATTRIBUTE_MISSING, telling you the module needs an attribute of type json.

The syntax also changed along the way. An early version of the proposal used the keyword assert. It was replaced by with, which Node.js has supported since v18.20.0. The old assert form was removed in Node.js 22, so code using it now throws a syntax error. All currently supported Node.js versions (22, 24 and 26) understand with.

How to fix it

#

Use a static import with an attribute

This is the best choice when the JSON ships with your code, such as config, fixtures or translation files.


_10
import pkg from '../package.json' with { type: 'json' };
_10
_10
console.log(`Running ${pkg.name} v${pkg.version}`);

A few rules apply:

  • You only get a default export. Named imports, such as import { version } from './package.json', do not work. Destructure afterwards instead.
  • The file is parsed once and cached, like any module. Every import gets the same object, so changes you make to it are shared across your app.
  • TypeScript supports this syntax from version 5.3. With resolveJsonModule turned on, you also get types for the JSON contents.

Use a dynamic import

When the path is only known at runtime, pass the attribute in the second argument of import().


_10
const locale = process.env.LOCALE ?? 'en';
_10
_10
const { default: messages } = await import(`./locales/${locale}.json`, {
_10
with: { type: 'json' },
_10
});

Notice the default key. Dynamic imports return the module namespace, so the data sits under default.

Read and parse the file yourself

If the file changes while the app runs, if it lives outside your project, or if you want to handle bad JSON gracefully, read it as text and parse it.


_10
import { readFile } from 'node:fs/promises';
_10
_10
const url = new URL('./data.json', import.meta.url);
_10
const data = JSON.parse(await readFile(url, 'utf8'));

Using new URL(..., import.meta.url) resolves the path relative to the current module rather than the folder you ran node from. On Node.js 20.11 and later you can use import.meta.dirname with path.join instead.

Because this reads the file each time, you always get fresh data and nothing is cached.

Use createRequire

If you are moving a CommonJS codebase to ES modules and want the old behaviour, createRequire gives you a working require inside an ES module.


_10
import { createRequire } from 'node:module';
_10
_10
const require = createRequire(import.meta.url);
_10
const config = require('./config.json');

This works, but it is a bridge. For new code, prefer the import attribute.

Common pitfalls

#
  • Using assert instead of with****. Old tutorials show assert { type: 'json' }. That syntax no longer works in current Node.js.
  • Trying named imports. Only the default export exists. Import the whole object and pick fields from it.
  • Relative paths with readFile****. A path like './data.json' is resolved from the current working directory, not from the module. Use import.meta.url to avoid surprises when the script runs from another folder.
  • Expecting updates. A static or dynamic import is cached for the life of the process. Use readFile if the file changes.
  • Bundler differences. Vite, webpack and esbuild may let you import JSON without the attribute, or even support named imports. That code can break when run directly in Node.js, so add the attribute anyway.
#

Was this resource helpful?