Last modified: Jun 30, 2025 By Alexander Williams

Fix Error: Cannot find module './routes/index'

If you see the error Cannot find module './routes/index', don't worry. This is a common issue in Node.js. It happens when the app can't locate the module.

Why does this error occur?

The error occurs when Node.js cannot find the specified module. This can happen for several reasons:

  • The file does not exist.
  • The path is incorrect.
  • The module is not installed.

How to fix the error

Here are the best ways to fix this issue.

1. Check the file path

First, verify the file path. Ensure the ./routes/index file exists in your project.


ls ./routes/index.js

If the file is missing, create it or correct the path.

2. Verify the module export

Ensure the module exports correctly. In ./routes/index.js, add:


// Export the module
module.exports = router;

If you're using ES modules, use:


export default router;

3. Reinstall dependencies

Sometimes, dependencies cause issues. Run:


npm install

This reinstalls all packages. If you face similar issues like Cannot find module 'pg', reinstalling helps.

4. Check the require statement

Ensure the require statement is correct. Use:


const router = require('./routes/index');

If the file is index.js, Node.js automatically looks for it. But specifying the full path is safer.

5. Clear the module cache

Node.js caches modules. Clear it with:


delete require.cache[require.resolve('./routes/index')];

This forces Node.js to reload the module.

Common mistakes

Here are mistakes that cause this error:

  • Typos in the file path.
  • Missing index.js file.
  • Incorrect module exports.

For example, if you encounter Cannot find module 'socket.io', check the spelling.

Example scenario

Let's say your project structure is:


project/
├── app.js
└── routes/
    └── index.js

In app.js, use:


const router = require('./routes/index');

This works because the path is correct.

Conclusion

The Cannot find module './routes/index' error is easy to fix. Check the file path, verify exports, and reinstall dependencies. If you face similar issues like Cannot find module 'typescript', apply the same solutions.

Always double-check your code. Happy coding!