Node.jsJavaScriptError Fix2026 Updated

ReferenceError: require is not defined— Fixed [Complete Guide 2026]

January 20266 min readNode.js · All OS

⚡ Quickest Fix — Pick One

Option A — Remove type: module from package.json (stay with CommonJS):

package.json
{
  "name": "my-app"
  // remove "type": "module" ← delete this line
}

Option B — Switch require() to import (use ES Modules):

server.js
// Replace: const express = require('express')
import express from 'express'  // ← use this instead

What Causes ReferenceError: require is not defined?

Terminal Error
ReferenceError: require is not defined in ES module scope, you can use import() instead
    at file:///Users/you/projects/app/server.js:1:1
    Node.js v20.11.0

Node.js supports two module systems. Understanding the difference is the key to fixing this error permanently:

SystemSyntaxActivated by
CommonJS (CJS)require() / module.exportsDefault for .js files
ES Modules (ESM)import / export"type": "module" in package.json or .mjs files

The error fires when you add "type": "module" to package.json (or use a .mjs file), which makes Node.js treat your file as an ES Module — and require() does not exist in ES Module scope. The fix is choosing one system and being consistent.

Most Node.js backend projects — Express APIs, CLI tools, scripts — work best with CommonJS. ES Modules are better for frontend-adjacent code or if you want to align with browser JavaScript.

1

Remove type: module from package.json

Stay with CommonJS — fastest fix
30 sec

If you added "type": "module" and do not specifically need ES Modules, simply remove it. Your require() calls will work again immediately.

package.json — BEFORE
{
  "name": "my-app",
  "version": "1.0.0",
  "type": "module"   // ← remove this line
}
package.json — AFTER
{
  "name": "my-app",
  "version": "1.0.0"
  // no "type" field = CommonJS by default
}

No other changes needed. All your require() and module.exports code works exactly as before.

2

Switch to ES Module import Syntax

Keep type: module — modernise your code
10 min

If you want to keep ES Modules (or are using a framework that requires it), replace all require() calls with import statements.

Side by side comparison

CommonJS (old) → ES Module (new)
// CommonJS                      // ES Module
const express = require('express')  →  import express from 'express'
const path = require('path')        →  import path from 'path'
const { readFile } = require('fs')  →  import { readFile } from 'fs/promises'
const cors = require('cors')        →  import cors from 'cors'
const mongoose = require('mongoose') → import mongoose from 'mongoose'

// Exporting
module.exports = router             →  export default router
module.exports = { fn1, fn2 }       →  export { fn1, fn2 }
module.exports.name = value         →  export const name = value

Complete Express app in ES Module style

server.js (ES Module)
import 'dotenv/config'
import express from 'express'
import cors from 'cors'
import mongoose from 'mongoose'

const app = express()

app.use(cors())
app.use(express.json())

mongoose.connect(process.env.MONGODB_URI)

app.get('/api/health', (req, res) => {
  res.json({ status: 'ok' })
})

const PORT = process.env.PORT || 3000
app.listen(PORT, () => console.log(`Server on port ${PORT}`))

When using ES Modules with Node.js, always use import 'dotenv/config' instead of require('dotenv').config() — it must still be the first import.

3

Use .cjs File Extension

Mixed project — keep specific files as CommonJS
2 min

If you have "type": "module" globally but need specific files to use CommonJS, rename them to .cjs..cjs files always use CommonJS regardless of the package.json type setting.

terminal
# Rename your file
mv server.js server.cjs

# Run it
node server.cjs
server.cjs
// This file uses CommonJS — require() works fine
const express = require('express')
const cors = require('cors')

const app = express()
app.use(cors())
app.listen(3000)

The file extension rule: .cjs = always CommonJS, .mjs = always ES Module, .js = determined by package.json type field.

4

Use createRequire in ES Modules

When you must use require() in an ES Module file
2 min

Sometimes you need require() inside an ES Module file — for example to load a JSON file or a package that only supports CommonJS. Node.js provides createRequire for exactly this:

server.js (ES Module)
import { createRequire } from 'module'
const require = createRequire(import.meta.url)

// Now you can use require() in this ES module file
const pkg = require('./package.json')
const legacyModule = require('./legacy-module.cjs')

console.log(pkg.version)

__dirname and __filename in ES Modules

Two other variables that do not exist in ES Modules: __dirname and __filename. Here is how to recreate them:

server.js (ES Module)
import { fileURLToPath } from 'url'
import path from 'path'

// Recreate __filename and __dirname
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

// Now use them exactly like CommonJS
const configPath = path.join(__dirname, 'config.json')
console.log('Current directory:', __dirname)

TypeError: app.use is not a function — Fixed

This is a separate but very common Express error that often appears alongside module issues. It deserves its own explanation.

Terminal Error
TypeError: app.use is not a function
    at Object.<anonymous> (/Users/you/projects/api/server.js:5:5)
    at Module._compile (node:internal/modules/cjs/loader:1376:14)

This error means the variable you are calling .use() on is not an Express app instance. Almost always caused by a single missing step — forgetting to call express().

The Most Common Cause — Missing express() Call

server.js
// ❌ WRONG — app is the express function, not an app instance
const app = require('express')
app.use(cors())   // TypeError: app.use is not a function

// ✅ CORRECT — call express() to create the app instance
const express = require('express')
const app = express()   // ← this creates the app instance
app.use(cors())         // works correctly

ES Module version

server.js (ES Module)
// ❌ WRONG
import app from 'express'   // app is the function, not an instance

// ✅ CORRECT
import express from 'express'
const app = express()       // create the instance

Middleware order matters

server.js — correct order
const express = require('express')
const cors = require('cors')
const app = express()

// ✅ CORRECT ORDER:
// 1. Body parsers and middleware first
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(cors())

// 2. Routes after middleware
app.get('/api/data', (req, res) => {
  res.json({ data: 'works' })
})

// 3. Error handler last
app.use((err, req, res, next) => {
  res.status(500).json({ error: err.message })
})

app.listen(3000)

Other causes of app.use is not a function

CauseFix
const app = require('express') (missing call)const app = express() after requiring
Router exported as object instead of Routermodule.exports = router (not { router })
Circular dependency causing undefined importMove app creation to separate app.js file
Middleware is not a functionCheck that what you pass to app.use() is a function

CommonJS vs ES Modules — Quick Reference

Side by Side Comparison

FeatureCommonJSES Modules
Importrequire()import x from 'x'
Exportmodule.exports = xexport default x
Named exportexports.fn = fnexport { fn }
Activatedefault for .js"type": "module" or .mjs
__dirnamebuilt-inuse fileURLToPath workaround
Dynamic importrequire() anywhereawait import() in async
Best forNode.js backendsModern browsers + Node

How to Prevent These Errors

Frequently Asked Questions

What causes ReferenceError require is not defined in Node.js?+
You have 'type': 'module' in package.json which makes all .js files ES Modules. ES Modules use import/export syntax — require() does not exist in this context. Either remove type: module or switch to import statements.
How do I fix require is not defined in ES module?+
Two options: remove 'type': 'module' from package.json to use CommonJS, OR replace all require() calls with import statements. Do not mix the two systems in the same file.
Can I use require() and import in the same project?+
Yes, but not in the same file. Use .cjs extension for CommonJS files and .mjs or .js (with type: module) for ES Module files. This lets you mix module systems across files in the same project.
What is __dirname equivalent in ES modules?+
Use: import { fileURLToPath } from 'url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename). This recreates __dirname for ES modules.
What causes TypeError app.use is not a function?+
The most common cause is writing const app = require('express') instead of const express = require('express'); const app = express(). You must call express() to create the app instance. app.use() only exists on the app instance, not on the express function itself.
How do I fix TypeError app.use is not a function in Express?+
Make sure you called express() to create the app: const express = require('express'); const app = express(). Then app.use() will work. Also ensure cors(), body parsers, and other middleware are added BEFORE route definitions.

Need Expert Help?

We Build Production-Grade Node.js & Express Apps

Softplix is a full-stack development agency. Dealing with module system issues or Express configuration in production? We can help.

Talk to an Engineer