TypeError [ERR_IMPORT_ASSERTION_TYPE_MISSING] in Node.js

avatar

Borislav Hadzhiev

Last updated: Mar 29, 2022

banner

Photo from Unsplash

TypeError [ERR_IMPORT_ASSERTION_TYPE_MISSING] in Node.js #

Use an import assertion to solve the error "TypeError [ERR_IMPORT_ASSERTION_TYPE_MISSING]: Module needs an import assertion of type json", e.g. import myJson from './example.json' assert {type: 'json'}. This syntax indicates that the module is JSON and not to be executed.

typeerror err import assertion type missing

Here is an example of how the error occurs.

index.js
// ⛔️ TypeError [ERR_IMPORT_ASSERTION_TYPE_MISSING]: Module // "file://bobbyhadz-js/example.json" needs an // import assertion of type "json" import myJson from './example.json';

The line above throws an error because we need to explicitly note that we are importing a JSON module, so it cannot be executed.

index.js
import myJson from './example.json' assert {type: 'json'}; // 👇️ { // name: 'Alice', // country: 'Austria', // tasks: [ 'develop', 'design', 'test' ], // age: 30 // } console.log(myJson.person); console.log(myJson.person.name); // 👉️ "Alice" console.log(myJson.person.country); // 👉️ "Austria"

The code snippet above assumes that there is an example.json file in the same directory with the following content:

example.json
{ "person": { "name": "Alice", "country": "Austria", "tasks": ["develop", "design", "test"], "age": 30 } }

Note that the type property in your package.json has to be set to module, because we are using ES6 Modules syntax.

package.json
{ "type": "module", // ... rest }

Here is a screenshot of the output from running the index.js file.

import json file success

You can read more about why this is necessary in the Import assertions proposal page on GitHub.

In short, the import assertion proposal adds an inline syntax for module import statements.

The syntax was introduced for improved security when importing JSON modules and similar module types which cannot execute code.

This prevents a scenario where a server responds with a different MIME type, causing code to be unexpectedly executed.

The assert {type: 'json'} syntax enables us to specify that we are importing a JSON or similar module type that isn't going to be executed.

You can read more about the import assertions proposal in this tc39 GitHub repository.

Conclusion #

Use an import assertion to solve the error "TypeError [ERR_IMPORT_ASSERTION_TYPE_MISSING]: Module needs an import assertion of type json", e.g. import myJson from './example.json' assert {type: 'json'}. This syntax indicates that the module is JSON and not to be executed.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.