Could not access root module file error in TRPCModule

HEAD
86891ccbuild(nestjs-trpc-v2): bump to 1.4.1
Avatar of bensadevs
bensadevs
posted

I got this error This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason: Error: Could not access root module file. at TRPCGenerator.buildRootImportsMap

My app.module has:

	TRPCModule.forRoot({
		basePath: "/api/trpc",
		autoSchemaFile: "../../packages/server",
		context: AppContext,
	}),
Avatar of anthropic/claude-haiku-4.5
Claude Haiku 4.5
commented

Now I have all the information needed. Let me create a summary of the problem:

##Problem Analysis

The error "Could not access root module file" occurs in the TRPCGenerator.buildRootImportsMap() method because the library cannot find the file that called TRPCModule.forRoot().

Here's what's happening:

  1. File Discovery: When you call TRPCModule.forRoot() in your app.module, the library uses a FileScanner that analyzes the stack trace to determine which file made the call.

  2. Stack Trace Inspection: The FileScanner.getCallerFilePath() method:

    • Examines the Node.js call stack
    • Looks for source maps to get the original TypeScript file path
    • Falls back to the compiled JavaScript file if source maps aren't available
  3. Validation Failure: Later, when the TRPCGenerator tries to load that file using this.project.addSourceFileAtPathIfExists(this.moduleCallerFilePath), it returns null because the path is either:

    • Incorrect
    • Points to a non-existent file
    • Uses a path that the ts-morph Project can't resolve

##Most Common Causes

  1. Source maps not enabled: Your tsconfig.json doesn't have "sourceMap": true
  2. Incorrect skip depth: The stack trace offset isn't correct for your environment
  3. Build artifacts not available: The compiled files or source maps are missing when the module initializes

##Solutions

Try these in order:

  1. Enable source maps in your tsconfig.json:

    {
      "compilerOptions": {
        "sourceMap": true,
        // ... other options
      }
    }
    
  2. Ensure your app module file path is correct: Make sure your app.module.ts (or .js if compiled) actually exists at the location the scanner finds.

  3. Check your build output: Make sure you've compiled your TypeScript and that source maps were generated alongside the .js files.

  4. If using dynamic imports: If your app.module is being dynamically imported or the stack trace path is unusual, you might need to open an issue with more details about your project structure.

Would you like me to check your specific tsconfig.json or help you debug the actual path that's being resolved?

Avatar of bensadevs
bensadevs
commented

this is my tsconfig:

{ "extends": "@repo/typescript-config/nestjs.json", "compilerOptions": { "baseUrl": "./", "outDir": "./dist",

	"paths": {
		"@/*": ["./src/*"]
	},

	"sourceMap": true,
	"inlineSources": true,

	// Set `sourceRoot` to  "/" to strip the build path prefix
	// from generated source code references.
	// This improves issue grouping in Sentry.
	"sourceRoot": "/"
},
"include": ["src"],
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]

}

My app is a monorepo with turborepo I have apps/api which is nestjs and @repo/trpc which is where I have my trpc stuff. The packages/trpc/src/server/server.ts exists already but its isnt being changed evert.

Here is the whole error

This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason: Error: Could not access root module file. at TRPCGenerator.buildRootImportsMap (/project/node_modules/.pnpm/nestjs-trpc-v2@1.4.1_@nestjs+common@11.1.11_class-transformer@0.5.1_class-validator@0.1_be4cda22ef7f7c792a580efb3d594e54/node_modules/nestjs-trpc-v2/lib/generators/trpc.generator.ts:204:13) at TRPCGenerator.onModuleInit (/project/node_modules/.pnpm/nestjs-trpc-v2@1.4.1_@nestjs+common@11.1.11_class-transformer@0.5.1_class-validator@0.1_be4cda22ef7f7c792a580efb3d594e54/node_modules/nestjs-trpc-v2/lib/generators/trpc.generator.ts:71:38) at MapIterator.iteratee (/project/node_modules/.pnpm/@nestjs+core@11.1.11_@nestjs+common@11.1.11_class-transformer@0.5.1_class-validator@0.1_dec3eb7e8922d39ae71062d41c83de09/node_modules/@nestjs/core/hooks/on-module-init.hook.js:22:43) at MapIterator.next (/project/node_modules/.pnpm/iterare@1.2.1/node_modules/iterare/src/map.ts:9:39) at IteratorWithOperators.next (/project/node_modules/.pnpm/iterare@1.2.1/node_modules/iterare/src/iterate.ts:19:28) at Function.from () at IteratorWithOperators.toArray (/project/node_modules/.pnpm/iterare@1.2.1/node_modules/iterare/src/iterate.ts:227:22) at callOperator (/project/node_modules/.pnpm/@nestjs+core@11.1.11_@nestjs+common@11.1.11_class-transformer@0.5.1_class-validator@0.1_dec3eb7e8922d39ae71062d41c83de09/node_modules/@nestjs/core/hooks/on-module-init.hook.js:23:10) at callModuleInitHook (/project/node_modules/.pnpm/@nestjs+core@11.1.11_@nestjs+common@11.1.11_class-transformer@0.5.1_class-validator@0.1_dec3eb7e8922d39ae71062d41c83de09/node_modules/@nestjs/core/hooks/on-module-init.hook.js:43:23) at NestApplication.callInitHook (/project/node_modules/.pnpm/@nestjs+core@11.1.11_@nestjs+common@11.1.11_class-transformer@0.5.1_class-validator@0.1_dec3eb7e8922d39ae71062d41c83de09/node_modules/@nestjs/core/nest-application-context.js:252:50) at process.processTicksAndRejections (node:internal/process/task_queues:105:5) at async NestApplication.init (/project/node_modules/.pnpm/@nestjs+core@11.1.11_@nestjs+common@11.1.11_class-transformer@0.5.1_class-validator@0.1_dec3eb7e8922d39ae71062d41c83de09/node_modules/@nestjs/core/nest-application.js:103:9) at async NestApplication.listen (/project/node_modules/.pnpm/@nestjs+core@11.1.11_@nestjs+common@11.1.11_class-transformer@0.5.1_class-validator@0.1_dec3eb7e8922d39ae71062d41c83de09/node_modules/@nestjs/core/nest-application.js:175:13) at async bootstrap (/main.ts:50:2)

Avatar of anthropic/claude-haiku-4.5
Claude Haiku 4.5
commented

Unfortunately, TRPCModuleOptions doesn't expose a way to explicitly set the rootModuleFilePath. The library relies on automatic detection.

##Solution 3: Check your build output and source maps

The most likely issue is that your source maps aren't being generated correctly. Let me suggest some debugging steps:

  1. Check if source maps exist after building:

    # In your apps/api directory
    ls -la dist/
    # Look for .js.map files
    
  2. Verify the source map content points to the correct path:

    head dist/app.module.js.map
    
  3. Ensure your build process is working:

    # In your workspace root
    pnpm build
    # or
    turbo build
    

##Solution 4: Explicit path in your tsconfig (for monorepo)

Your baseUrl might be causing issues. Try adjusting your tsconfig.json:

{
  "extends": "@repo/typescript-config/nestjs.json",
  "compilerOptions": {
    "baseUrl": "./src",  // Changed from "./"
    "outDir": "./dist",
    "rootDir": "./src",  // Add this
    "paths": {
      "@/*": ["./*"]  // Updated to match new baseUrl
    },
    "sourceMap": true,
    "inlineSources": true,
    "sourceRoot": "/"
  },
  "include": ["src"],
  "exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}

##Solution 5: Use explicit file path (Workaround)

If the above doesn't work, there might be an undocumented way to pass the path. Check your node_modules to see the actual implementation, or open an issue with the library maintainers about monorepo support.

Which of these solutions would you like to try first? I'd recommend starting with Solution 1 (temporarily disable autoSchemaFile) to confirm that's the source of the error, then move to Solution 4 (tsconfig adjustment).

Avatar of bensadevs
bensadevs
commented

even if I write TRPCModule.forRoot({ basePath: "/api/trpc", autoSchemaFile: "./server.ts", context: AppContext, }),

i get the same error

This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason: Error: Could not access root module file. at TRPCGenerator.buildRootImportsMap (/project/node_modules/.pnpm/nestjs-trpc-v2@1.4.1_@nestjs+common@11.1.11_class-transformer@0.5.1_class-validator@0.1_be4cda22ef7f7c792a580efb3d594e54/node_modules/nestjs-trpc-v2/lib/generators/trpc.generator.ts:204:13) at TRPCGenerator.onModuleInit (/project/node_modules/.pnpm/nestjs-trpc-v2@1.4.1_@nestjs+common@11.1.11_class-transformer@0.5.1_class-validator@0.1_be4cda22ef7f7c792a580efb3d594e54/node_modules/nestjs-trpc-v2/lib/generators/trpc.generator.ts:71:38) at MapIterator.iteratee (/project/node_modules/.pnpm/@nestjs+core@11.1.11_@nestjs+common@11.1.11_class-transformer@0.5.1_class-validator@0.1_dec3eb7e8922d39ae71062d41c83de09/node_modules/@nestjs/core/hooks/on-module-init.hook.js:22:43) at MapIterator.next (/project/node_modules/.pnpm/iterare@1.2.1/node_modules/iterare/src/map.ts:9:39) at IteratorWithOperators.next (/project/node_modules/.pnpm/iterare@1.2.1/node_modules/iterare/src/iterate.ts:19:28) at Function.from () at IteratorWithOperators.toArray (/project/node_modules/.pnpm/iterare@1.2.1/node_modules/iterare/src/iterate.ts:227:22) at callOperator (/project/node_modules/.pnpm/@nestjs+core@11.1.11_@nestjs+common@11.1.11_class-transformer@0.5.1_class-validator@0.1_dec3eb7e8922d39ae71062d41c83de09/node_modules/@nestjs/core/hooks/on-module-init.hook.js:23:10) at callModuleInitHook (/project/node_modules/.pnpm/@nestjs+core@11.1.11_@nestjs+common@11.1.11_class-transformer@0.5.1_class-validator@0.1_dec3eb7e8922d39ae71062d41c83de09/node_modules/@nestjs/core/hooks/on-module-init.hook.js:43:23) at NestApplication.callInitHook (/project/node_modules/.pnpm/@nestjs+core@11.1.11_@nestjs+common@11.1.11_class-transformer@0.5.1_class-validator@0.1_dec3eb7e8922d39ae71062d41c83de09/node_modules/@nestjs/core/nest-application-context.js:252:50) at process.processTicksAndRejections (node:internal/process/task_queues:105:5) at async NestApplication.init (/project/node_modules/.pnpm/@nestjs+core@11.1.11_@nestjs+common@11.1.11_class-transformer@0.5.1_class-validator@0.1_dec3eb7e8922d39ae71062d41c83de09/node_modules/@nestjs/core/nest-application.js:103:9) at async NestApplication.listen (/project/node_modules/.pnpm/@nestjs+core@11.1.11_@nestjs+common@11.1.11_class-transformer@0.5.1_class-validator@0.1_dec3eb7e8922d39ae71062d41c83de09/node_modules/@nestjs/core/nest-application.js:175:13) at async bootstrap (/main.ts:50:2)

Avatar of anthropic/claude-haiku-4.5
Claude Haiku 4.5
commented

I found the problem! The Project is being created with hardcoded compiler options that don't include your tsconfig.json. Critically, it's missing:

  1. Your baseUrl and paths configuration
  2. Your actual tsconfig settings
  3. The ability to resolve aliases like @/*

This means when the FileScanner returns a path like /project/apps/api/dist/app.module.js, and ts-morph tries to load it, it can't find it because the Project doesn't know about your workspace structure.

The fix requires patching the library. However, there's a workaround you can try:

##Workaround: Patch the generator.module.ts

Create a patch file for the library using patch-package:

  1. Install patch-package:
pnpm add -D patch-package
  1. Add postinstall script to package.json:
{
  "scripts": {
    "postinstall": "patch-package"
  }
}
  1. Modify node_modules to fix the issue by editing:
node_modules/nestjs-trpc-v2/lib/generators/generator.module.ts

Around line 56-61, change:

const defaultCompilerOptions: CompilerOptions = {
  target: ScriptTarget.ES2019,
  module: ModuleKind.CommonJS,
  emitDecoratorMetadata: true,
  experimentalDecorators: true,
  allowJs: true,
  checkJs: true,
  esModuleInterop: true,
};
const project = new Project({ compilerOptions: defaultCompilerOptions });

To:

const defaultCompilerOptions: CompilerOptions = {
  target: ScriptTarget.ES2019,
  module: ModuleKind.CommonJS,
  emitDecoratorMetadata: true,
  experimentalDecorators: true,
  allowJs: true,
  checkJs: true,
  esModuleInterop: true,
};
// Load tsconfig if available to get proper path resolution
let projectOptions: any = { compilerOptions: defaultCompilerOptions };
try {
  const tsconfigPath = require('path').resolve(process.cwd(), 'tsconfig.json');
  if (require('fs').existsSync(tsconfigPath)) {
    projectOptions.tsConfigFilePath = tsconfigPath;
  }
} catch {}
const project = new Project(projectOptions);
  1. Create the patch:
pnpm patch-package nestjs-trpc-v2

This will create a patches/nestjs-trpc-v2+1.4.1.patch file.


##Better Solution: Open an Issue with the maintainers

Since you're using this library, the real fix should be in the library itself. The library should:

  1. Load the tsconfig.json from the project root
  2. Use it when creating the ts-morph Project
  3. Pass the correct root module file path

You should open an issue on the nestjs-trpc-v2 repository with:

  • Your error message
  • Your monorepo structure
  • Your tsconfig.json
  • The fact that FileScanner.getCallerFilePath() might be returning incorrect paths in monorepos

Try the patch-package approach first and let me know if it works! If you need help setting it up, I can guide you through it step by step.


END OF POST

Could not access root module file error in TRPCModule — mguay22/nestjs-trpc-v2