Import JSON Files in Node.js and Web JavaScript ES Modules

Problem: If you try to import a JSON file in your Node.js module like you’d import/require any other JS module, it’d throw an error:

import config from './config.json';
// Throws the following error:
// TypeError [ERR_IMPORT_ASSERTION_TYPE_MISSING]: Module "file://config.json" needs an import assertion of type "json"

If you did the same on Web platform (JS running in a browser), you’d get the following error:

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "application/json". Strict MIME type checking is enforced for module scripts per HTML spec.

Solution: What you need to do is add an import assertion that allows the import statement to include additional information about the module resource:

// This works!
import config from './config.json' assert { type: 'json' };
console.log(config); // will dump the JSON object

Why is the assertion required at all? Because on web platforms (browsers, etc.) the MIME type (or Content-Type) of a module resource (config.json in our case) that is being imported is checked before deciding whether the resource (like JavaScript resources) should be executed or not.

Now if some piece of code was doing import data from https://malicious-web.com/data.json that ended up sending application/javascript as it’s MIME, the script would get executed unknowingly. Hence, assertions ensure that if a JSON module is being imported, then the import will fail if the MIME type received from the server doesn’t match the expected type, i.e., application/json.

For dynamic imports, this is how you’d specify the type assertion:

const config = await import('./config.json', {
  assert: { type: 'json' }
});
console.log(config.default); // .default for default exports

Leave a Reply

Your email address will not be published. Required fields are marked *