Fix Error Cannot Find Module in Node.js and Next.js

As a developer working on a Next.js project, I recently encountered an issue where I couldn’t run a server file that retrieves product information from MongoDB. The error message indicated that the module ‘src/app/lib/dbConnect.ts’ couldn’t be found. In this article, I’ll walk you through the solution I found to resolve this issue.

The Problem

The error occurred when I tried to run the route.ts file using node <file>. The file imports dbConnect.ts, Product.ts, and NextResponse from their respective locations. However, Node.js couldn’t find the dbConnect.ts module.

The Code

Here’s the code for the route.ts file:

const dbConnect = require('src/app/lib/dbConnect.ts');
const Product = require('src/app/models/Product');
const NextResponse = require('next/server');

async function GET() {
  await dbConnect.dbConnect();

  try {
    const objectId = new mongoose.Types.ObjectId('669dd2f352983f03c171e511');
    const document = await Product.Product.findById(objectId).exec();

    NextResponse.NextResponse.json(document);
  } catch (err) {
    NextResponse.NextResponse.json({ error: err.message });
  }
}

GET();

The Error Message

The error message indicated that Node.js couldn’t find the dbConnect.ts module:

Error: Cannot find module 'src/app/lib/dbConnect.ts'
Require stack:
- C:\Users\user\project\src\app\api\getproduct\route.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1144:15)
    at Module._load (node:internal/modules/cjs/loader:985:27)
    at Module.require (node:internal/modules/cjs/loader:1235:19)
    at require (node:internal/modules/helpers:176:18)
    at Object.<anonymous> (C:\Users\user\project\src\app\api\getproduct\route.js:54:19)
    at Module._compile (node:internal/modules/cjs/loader:1376:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
    at Module.load (node:internal/modules/cjs/loader:1207:32)
    at Module._load (node:internal/modules/cjs/loader:1023:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:135:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    'C:\\Users\\user\\project\\src\\app\\api\\getproduct\\route.js'
  ]
}

The Solution

To resolve this issue, I followed these steps:

Use Relative Paths: Ensure that the paths in your require statements are relative to the current file.

const dbConnect = require('../../lib/dbConnect');
const Product = require('../../models/Product');
const NextResponse = require('next/server');

Compile TypeScript to JavaScript: Node.js requires JavaScript files. Use tsc (TypeScript compiler) to compile your TypeScript files to JavaScript before running them.

tsc

Use ES Modules: If you want to use import statements, ensure your package.json has "type": "module" and use .js extensions in your imports.

    {
      "type": "module"
    }

    JavaScript

    import dbConnect from '../../lib/dbConnect.js';
    import Product from '../../models/Product.js';
    import { NextResponse } from 'next/server';

    Check Your Environment: Ensure that your environment is set up correctly to handle TypeScript and ES modules.

      By following these steps, you should be able to resolve the “Cannot find module” error and successfully run your Next.js project with Node.js.

      Final Thoughts

      When working with Next.js and TypeScript, it’s essential to ensure that your environment is set up correctly and that you’re using the right paths and modules. By following the steps outlined in this article, you can resolve common issues like the “Cannot find module” error and get back to building your application.

      Related blog posts