ReferenceError: require is not defined— Fixed [Complete Guide 2026]
⚡ Quickest Fix — Pick One
Option A — Remove type: module from package.json (stay with CommonJS):
{
"name": "my-app"
// remove "type": "module" ← delete this line
}Option B — Switch require() to import (use ES Modules):
// Replace: const express = require('express')
import express from 'express' // ← use this insteadWhat Causes ReferenceError: require is not defined?
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.0Node.js supports two module systems. Understanding the difference is the key to fixing this error permanently:
| System | Syntax | Activated by |
|---|---|---|
| CommonJS (CJS) | require() / module.exports | Default 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.
Remove type: module from package.json
Stay with CommonJS — fastest fixIf you added "type": "module" and do not specifically need ES Modules, simply remove it. Your require() calls will work again immediately.
{
"name": "my-app",
"version": "1.0.0",
"type": "module" // ← remove this line
}{
"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.
Switch to ES Module import Syntax
Keep type: module — modernise your codeIf 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 // 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 = valueComplete Express app in ES Module style
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.
Use .cjs File Extension
Mixed project — keep specific files as CommonJSIf 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.
# Rename your file
mv server.js server.cjs
# Run it
node 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.
Use createRequire in ES Modules
When you must use require() in an ES Module fileSometimes 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:
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:
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.
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
// ❌ 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 correctlyES Module version
// ❌ WRONG
import app from 'express' // app is the function, not an instance
// ✅ CORRECT
import express from 'express'
const app = express() // create the instanceMiddleware order matters
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
| Cause | Fix |
|---|---|
| const app = require('express') (missing call) | const app = express() after requiring |
| Router exported as object instead of Router | module.exports = router (not { router }) |
| Circular dependency causing undefined import | Move app creation to separate app.js file |
| Middleware is not a function | Check that what you pass to app.use() is a function |
CommonJS vs ES Modules — Quick Reference
Side by Side Comparison
| Feature | CommonJS | ES Modules |
|---|---|---|
| Import | require() | import x from 'x' |
| Export | module.exports = x | export default x |
| Named export | exports.fn = fn | export { fn } |
| Activate | default for .js | "type": "module" or .mjs |
| __dirname | built-in | use fileURLToPath workaround |
| Dynamic import | require() anywhere | await import() in async |
| Best for | Node.js backends | Modern browsers + Node |
How to Prevent These Errors
- Pick one module system for your project and be consistent throughout
- For Node.js backends (Express, APIs, scripts) — use CommonJS unless you have a specific reason for ES Modules
- Never mix require() and import in the same file
- If you add type: module, update ALL require() calls to import statements
- Use .cjs or .mjs extensions for files that need to deviate from the project default
- Always call express() to create the app instance before calling app.use()
- Add middleware (cors, body parsers) BEFORE route definitions in Express
Frequently Asked Questions
What causes ReferenceError require is not defined in Node.js?+−
How do I fix require is not defined in ES module?+−
Can I use require() and import in the same project?+−
What is __dirname equivalent in ES modules?+−
What causes TypeError app.use is not a function?+−
How do I fix TypeError app.use is not a function in Express?+−
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