Skip to content
Happy Programming Guide
Start learning
JavaScript

Fixing “ReferenceError: require is not defined”

require is CommonJS; your code is running as an ES module or in a browser, where it does not exist. Which situation you are in, and the fix for each: import syntax, package type, or createRequire.

A close-up view of a black laptop keyboard, focusing on the keys with visible wear and dust

ReferenceError: require is not defined means the code called require() somewhere that does not provide it. require belongs to CommonJS, Node’s original module system. It is absent in browsers, and it is absent in files Node treats as ES modules — which, since "type": "module" became common in package.json, is most new projects. There are four situations, and the message alone does not say which, so identify yours first.

The two systems#

JavaScript
// CommonJS - Node's original system
const fs = require('fs');
module.exports = { readConfig };

// ES modules - the standard, in browsers and modern Node
import fs from 'node:fs';
export { readConfig };

Node decides which system a file uses from its extension and the nearest package.json: .cjs is always CommonJS, .mjs is always ESM, and .js follows the "type" field — "module" for ESM, absent or "commonjs" for CommonJS. In an ESM file, require, module, __dirname and __filename do not exist.

Situation 1: it is running in a browser#

If the error is in the browser console, the script is a plain browser script and require was never available there. Browser code loads modules with import:

HTML
<script type="module" src="app.js"></script>
JavaScript
import { format } from './util.js';          // relative path, with extension
import confetti from 'https://cdn.example.com/confetti.js';

Bare package names, import x from 'lodash', do not work in the browser without a bundler or an import map, because the browser has no node_modules. Code copied from a Node tutorial into a browser page is the classic source of this error; use a bundler such as Vite, or a CDN URL.

Situation 2: Node, and the package is an ES module#

JSON
{ "type": "module" }

With that in package.json, every .js file is ESM and require is gone. Two fixes:

Switch the file to import syntax, which is the forward-looking choice:

JavaScript
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const __filename = fileURLToPath(import.meta.url);      // if you need them
const __dirname = path.dirname(__filename);
// or, on Node 20.11 and later:
const dir = import.meta.dirname;

Or keep CommonJS for that file by renaming it to .cjs. Node then ignores the package type for it. Useful for a single legacy script or a config file you do not want to rewrite.

Situation 3: a config file#

Tools read configuration files with Node, and a module.exports = {...} config in a "type": "module" project fails with this error. Either rename it to .cjs — tailwind.config.cjs, postcss.config.cjs, .eslintrc.cjs — or convert it to export default {...}. Most tools accept both; check the tool’s documentation for which extensions it looks for.

Situation 4: you need require inside an ES module#

A CommonJS-only package, a JSON file on an old Node, or a dynamic path. Create a require function:

JavaScript
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);

const legacy = require('some-cjs-only-package');
const data = require('./data.json');

Most CommonJS packages can be imported directly from ESM, import pkg from 'some-cjs-package', with the whole module.exports arriving as the default import. createRequire is for the cases where that does not work. JSON can also be imported natively: import data from './data.json' with { type: 'json' }.

Test runners and TypeScript#

Jest historically ran files as CommonJS and needed configuration for ESM; Vitest runs ESM natively. A test that fails with this error under one runner and not the other is a runner configuration question. In TypeScript, the module setting in tsconfig.json decides what the compiled output uses; "module": "nodenext" follows the package type, and a mismatch between it and package.json produces this error at runtime.

Choosing a direction#

New projects: ESM, with "type": "module" and import everywhere. It is the standard, it works in browsers and Node alike, and the ecosystem has moved. Existing CommonJS projects: no need to convert unless a dependency forces it; leave the type unset and keep using require. The pain is in mixing, so pick one per project and use .cjs or .mjs for the exceptions.

Questions people ask#

Which is better, require or import?

import is the standard and works everywhere. require is Node-only and still fine in existing projects. Do not mix in one file.

Why does __dirname not exist either?

Same reason: it is a CommonJS convenience. Use import.meta.dirname on current Node, or the fileURLToPath pattern above.

Can I use require in a .mjs file?

Only via createRequire. The file is ESM by definition.

Node says “require() of ES Module not supported”. Is that the same?

The reverse: a CommonJS file requiring an ESM-only package. Newer Node versions allow it in many cases; otherwise convert the calling file to ESM or use a dynamic import().

Where to go next#

'Cannot use import statement outside a module', the other side of this errorRead next

Keep reading

JavaScript

JavaScript Security

XSS, CSRF, dependency risk, token storage and prototype pollution — the JavaScript vulnerabilities that matter, in the browser and in Node.

5 min read

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

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