Today I started writing a new project on Node.js and got this error on the very first run:

const express = require('express');
                ^
ReferenceError: require is not defined
    at ModuleJob.run (node:internal/modules/esm/module_job:152:23)
    at async Loader.import (node:internal/modules/esm/loader:166:24)
    at async Object.loadESM (node:internal/process/esm_loader:68:5)

First of all I checked my Node.js version:

node -v

There were no issues

v15.5.1

It looked strange as previously I haven’t seen such an error in the server side applications built on Node.js.

I did a quick stackoverflow search and found a couple of responses mentioning that require doesn’t work in the browser and that one should use either webpack or browserify.

A couple more minutes and I’ve found what I was looking for. It looks like in the versions of Node.js 14+ the error ReferenceError: require is not defined can occur on the server as well.

The issue is that in file package.json contained this line:

"type": "module",

It means that the default way of using npm modules is not require anymore, but import.

Solution

To get rid of the error require is not defined in Node.js you can do 3 things:

  • change the type of modules in package.json to commonjs:

    "type": "commonjs"
    
  • deleted the string "type": "commonjs" from the file package.json

  • change the require to import:

    // const express = require('express');
    import express from 'express';