nextjs-nestjs-integration-example icon indicating copy to clipboard operation
nextjs-nestjs-integration-example copied to clipboard

Doesn't work when babel is disabled (babel is no longer used in next v12)

Open R-Bower opened this issue 3 years ago • 4 comments

When NextJS v12 is used without a babel configuration, this solution fails to perform service injections.

Example:

// number.service.ts
import {Injectable} from "@nestjs/common"

@Injectable()
export class NumberService {
  getNumber(): number {
    return Math.random() * 100
  }
}
// number.controller.ts
import {Controller, Get} from "@nestjs/common"

import {NumberService} from "./number.service"

@Controller("randomNumber")
export class NumberController {
  constructor(private numberService: NumberService) {}

  @Get()
  randomNumber(): number {
    return this.numberService.getNumber()
  }
}
// number.module.ts
import {Module} from "@nestjs/common"

import {NumberController} from "./number.controller"

@Module({
  controllers: [NumberController],
})
export class NumberModule {}

[Nest] 8972 - 02/11/2022, 4:02:40 PM ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'getNumber')

I understand that there's transformation happening with babel. When these transformations aren't applied, services aren't injected properly. There are likely errors with every type of dependency injection. Not sure on how to proceed. Let me know if you'd like a replication repo.

R-Bower avatar Feb 12 '22 00:02 R-Bower

Managed to fix this by modifying Next's webpack config. The solution is to force webpack to use the babel config for the NestJS code.

// in next.config.js
webpack: (config) => {
    config.module.rules.push({
      // apply babel to the NestJS files.
      test: /.*\/backend\/.*\.ts/,
      use: {
        loader: "babel-loader",
        options: {
          plugins: [
            "babel-plugin-transform-typescript-metadata",
            ["@babel/plugin-proposal-decorators", {legacy: true}],
            "babel-plugin-parameter-decorator",
          ],
          presets: [
            [
              "next/babel",
              {
                "preset-typescript": {
                  onlyRemoveTypeImports: true,
                },
              },
            ],
          ],
        },
      },
    })
}

R-Bower avatar Feb 12 '22 00:02 R-Bower

That makes sense! Another solution would be to place this .babelrc in your project root:

{
  "presets": ["next/babel"]
}

That will make Next v12 use the Babel transform again.

Skn0tt avatar Feb 15 '22 08:02 Skn0tt

Can I add typeorm? image I am getting this error. The problem is that the Nestjs server is built in a file, as I see. How can I resolve this?

future-mine avatar Sep 22 '22 18:09 future-mine

Hi @future-mine! Please open a separate issue and provide detailed steps on how to reproduce this (a reproduction repository would be great!). That'd make it a lot easier to help you :)

Skn0tt avatar Sep 26 '22 08:09 Skn0tt