How to fix Error: Cannot find module './self' (resolving to itself) in Node.js

Node.jsBEGINNERMEDIUMUpdated Dec 9, 2025ยท 89 views

This error occurs when a module attempts to import or require its own filename or path, creating an unintended self-reference. Node.js cannot resolve the module because the import points back to the same file, preventing proper module loading and initialization.

Quick fix

Fixes MODULE_NOT_FOUND

// DON'T DO THIS - this file importing itself
const self = require('./index'); // Wrong!

// Or with dynamic paths
const self = require(__filename); // Wrong!

// Or with relative paths that resolve to this file
const self = require('./'); // Wrong if this is index.js!
  1. Identify the self-referencing import
  2. Remove or fix the self-referencing import
  3. Fix relative path imports
  4. Check package.json exports and aliases
node.js โ€” error
// DON'T DO THIS - this file importing itself
const self = require('./index'); // Wrong!
// Or with dynamic paths
const self = require(__filename); // Wrong!
// Or with relative paths that resolve to this file
const self = require('./'); // Wrong if this is index.js!
Error: Cannot find module './self' (resolving to itself)

What this error means

The "Cannot find module './self' (resolving to itself)" error happens when a module tries to import itself by its own filename or a path that resolves back to itself. This typically occurs when the import path inadvertently matches the current file's name or location. Node.js's module resolution algorithm follows a specific order: it checks for core modules first, then node_modules, and finally relative paths. When an import statement points back to the same file being executed, Node.js detects this as a self-reference and cannot resolve the module. This is different from a circular dependency between two separate files. Instead, it's a single file trying to load itself, which breaks the module loading chain. The error manifests as MODULE_NOT_FOUND with the "resolving to itself" indicator, signaling that Node.js recognizes the self-reference and aborts the operation.

Typical symptoms

  • Application crashes with "Cannot find module" and "resolving to itself" message
  • Error occurs on startup or when a specific import statement is executed
  • The error mentions a file path or module name that matches the current file
  • Confusion because the file actually exists and is spelled correctly
  • Import works fine in other parts of the codebase but fails in one location
  • Error persists even after clearing node_modules and reinstalling dependencies

Common causes

  1. Import statement uses the module's own filename instead of importing specific exports
  2. Incorrect relative path that inadvertently resolves to the current file
  3. Self-referencing in package.json exports or subpath patterns
  4. Using __filename or process.argv[1] in an import statement
  5. Copy-paste error where a module was duplicated without changing the import path
  6. Conditional imports or dynamic require statements that evaluate to the file itself
  7. Misconfiguration in module aliases or path mappings (in TypeScript or build tools)
  8. ESM vs CommonJS mismatch where the same file tries to import itself with different extensions

How to fix "Error: Cannot find module './self' (resolving to itself)"

1Identify the self-referencing import

First, locate the import or require statement causing the error. The error message will indicate which file is trying to import itself:

javascript
// DON'T DO THIS - this file importing itself
const self = require('./index'); // Wrong!

// Or with dynamic paths
const self = require(__filename); // Wrong!

// Or with relative paths that resolve to this file
const self = require('./'); // Wrong if this is index.js!

Look for imports in your code that reference the current file's name or a path that resolves back to it. Check the line number in the stack trace to pinpoint the exact location.

2Remove or fix the self-referencing import

Delete the import statement if it's not needed, or change it to import only what you need from elsewhere:

BEFORE (broken):

javascript
// index.js
const self = require('./index');
const helper = require('./helper');

module.exports = {
  doSomething() {
    return helper.process();
  }
};

AFTER (fixed):

javascript
// index.js
const helper = require('./helper');

module.exports = {
  doSomething() {
    return helper.process();
  }
};

If you need to reference the current module's exports within itself, use module.exports directly instead of requiring the file again:

javascript
// Correct way to reference the module itself
module.exports = {
  methodA() {
    return this.methodB();
  },
  methodB() {
    return 'result';
  }
};
3Fix relative path imports

If you intended to import from a different file, ensure the relative path is correct:

javascript
// Wrong - this resolves to the current file (index.js)
const lib = require('./');

// Correct - import from a different file
const lib = require('./lib');

// Or import a specific named export
const { helper } = require('./helper');

Use explicit filenames or directory names different from the current file to avoid confusion. Check that relative paths with './' or '../' point to different files.

4Check package.json exports and aliases

If you're using package.json "exports" field or TypeScript path aliases, ensure they don't accidentally resolve a module to itself:

json
{
  "exports": {
    ".": "./index.js",
    "./lib": "./lib/index.js",
    "./self": "./index.js"
  }
}

DO NOT use:

javascript
const self = require('./self'); // This would require ./index.js!

And check TypeScript tsconfig.json path mappings:

json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"],
      "@/utils": ["src/utils/index.ts"]
    }
  }
}

Ensure path mappings don't create self-references where a file tries to import itself under an alias.

5Avoid dynamic self-references

Be careful with dynamic require or import statements that might accidentally resolve to the current file:

AVOID:

javascript
// Don't use __filename or __dirname in require()
const self = require(__filename);

// Don't use process.argv[1] as a module path
const self = require(process.argv[1]);

// Don't compute paths that might resolve to the current file
const modulePath = './same-file';
const self = require(modulePath); // Risky!

DO:

javascript
// Use explicit, clear paths
const helper = require('./helper');
const utils = require('../utils');

// If you need runtime module info, don't require the module itself
const currentFile = __filename;
console.log('Current module:', currentFile);

Whenever you build a module path dynamically, double-check that it can't point back to the current file.

Advanced notes

Self-referencing within modules: If a module legitimately needs to call its own methods recursively or reference its own exports after initialization, use direct method calls or access module.exports directly:

javascript
module.exports = {
  recurse(n) {
    if (n <= 0) return;
    console.log(n);
    this.recurse(n - 1); // Call itself via 'this'
  }
};

CommonJS vs ES Modules: CommonJS (require) and ES Modules (import) handle self-references differently. ES modules may throw errors earlier during the parse phase, while CommonJS might fail at runtime. Ensure your module system is consistent throughout your project.

Barrel exports (index.js): If you have a barrel file that re-exports from submodules, be careful not to create a self-reference:

javascript
// index.js - DON'T DO THIS
const self = require('./'); // Self-reference!
module.exports = self;

// index.js - DO THIS instead
module.exports = require('./handler');

Build tool configuration: Bundlers (Webpack, Vite, esbuild) and transpilers (Babel) might optimize away self-references, but it's better to fix them in source code. Some build tools have warnings for circular dependencies that could catch this.

Package.json self-reference: In monorepos or packages with self-imports, the package name can be used to import from itself, but only if "exports" is configured correctly. Avoid confusion between the package name and relative paths.

Frequently asked questions

What does "MODULE_NOT_FOUND" mean?
/self' (resolving to itself)" error happens when a module tries to import itself by its own filename or a path that resolves back to itself. This typically occurs when the import path inadvertently matches the current file's name or location. js's module resolution algorithm follows a specific order: it checks for core modules first, then node_modules, and finally relative paths.
How do I fix "MODULE_NOT_FOUND"?
This error occurs when a module attempts to import or require its own filename or path, creating an unintended self-reference. Node.js cannot resolve the module because the import points back to the same file, preventing proper module loading and initialization.
What causes "MODULE_NOT_FOUND"?
Import statement uses the module's own filename instead of importing specific exports Incorrect relative path that inadvertently resolves to the current file Self-referencing in package.json exports or subpath patterns
Is the "MODULE_NOT_FOUND" error serious?
It is a medium-severity error โ€” more of a blocker than a risk. The steps above resolve it.

Official resources & further reading