Error on deploy a Nest.js Application only on render

Hello I have an error when deploying my application with Nest.js and TypeORM.
the error says:

Oct 26 08:55:02 AM error: error: relation "user" does not exist
Oct 26 08:55:02 AM /opt/render/project/src/node_modules/typeorm/driver/postgres/PostgresQueryRunner.js:211
Oct 26 08:55:02 AM throw new QueryFailedError_1.QueryFailedError(query, parameters, err);

And it happens only in the deployment of the application in ‘render’ as I did a build locally and I do not get the same error, I also tried it in a docker container where it does not present the same error, I made sure I have the environment variables I need and I have an ‘auth’ module with the ‘signIn’ and ‘signUp’ services to handle the authentication and the JWT.

This is my app.module.ts file:

@Module({
  imports: [
    ConfigModule.forRoot(),
    TypeOrmModule.forRoot({
      type: 'postgres',
      url: `postgres://${process.env.PGUSER}:${process.env.PGPASSWORD}@${process.env.PGHOST}:${process.env.PGPORT}/${process.env.PGDATABASE}`,
      synchronize: process.env.NODE_ENV === 'local',
      logging: true,
      autoLoadEntities: process.env.NODE_ENV === 'local',
      entities: ['**/*.entity{ .ts,.js}'],
      migrations: ['dist/db/migrations/*{.ts,.js}'],
      migrationsRun: true,
    }),
    UserModule,
    AuthModule,
    // more modules
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

The User module and entity is as follows:

// user.entity.ts
@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ type: 'varchar', length: 80 })
  name: string;

  @Exclude()
  @Column({ type: 'varchar', length: 350 })
  password: string;

  @Column({ type: 'varchar', length: 150 })
  email: string;

  @CreateDateColumn({
    type: 'timestamp',
    default: () => 'CURRENT_TIMESTAMP(6)',
  })
  created_at: Date;

  @UpdateDateColumn({
    type: 'timestamp',
    default: () => 'CURRENT_TIMESTAMP(6)',
    onUpdate: 'CURRENT_TIMESTAMP(6)',
  })
  updated_at: Date;

  async validatePassword(password: string): Promise<boolean> {
    return bcrypt.compare(password, this.password);
  }
}

// user.module.ts
@Module({
  imports: [TypeOrmModule.forFeature([User])],
  controllers: [UserController],
  providers: [UserService],
})
export class UserModule implements OnModuleInit {
  constructor(private readonly userService: UserService) {}

  async onModuleInit() {
    await this.createDefaultUsers();
  }

  async createDefaultUsers() { /** create a default users  */}
}

The Auth controller, module and services is as follows:

// auth.controller.ts
@Controller('auth')
@UseInterceptors(ClassSerializerInterceptor)
export class AuthController {
  constructor(
    private readonly authService: AuthService,
    private readonly userService: UserService,
  ) {}

  @Public()
  @Post('sign-up')
  async signUp(@Body() createUserDto: CreateUserDto) {
    return this.userService.create(createUserDto);
  }

  // @Public()
  @Post('sign-in')
  async signIn(@Body() signInDto: SignInAuthDto) {
    return this.authService.signIn(signInDto);
  }
}

// auth.module.ts
@Module({
  imports: [
    TypeOrmModule.forFeature([Auth, User]),
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.register({
      secret: process.env.JWT_MY_SECRET || 'secret',
      signOptions: { expiresIn: '1h' },
    }),
  ],
  controllers: [AuthController],
  providers: [AuthService, UserService],
})
export class AuthModule {}

// auth.services.ts
@Injectable()
export class AuthService {
  constructor(
    private readonly usersService: UserService,
    private readonly jwtService: JwtService,
  ) {}

  async signIn(signInDto: SignInAuthDto) {
    const { name, password, email } = signInDto;

    const user = await this.usersService.findUserByName(name);

    if (!user) {
      throw new UnauthorizedException('Invalid username or password');
    }

    if (user.email !== email) {
      throw new UnauthorizedException('Invalid username, email or password');
    }

    const passwordIsValid = await user.validatePassword(password);

    if (!passwordIsValid) {
      throw new UnauthorizedException('Invalid username or password');
    }

    const payload = { sub: user.id, username: user.name };
    const accessToken = await this.jwtService.signAsync(payload);

    return { access_token: accessToken };
  }
}

And the error is as follows:

Oct 26 08:53:00 AM  Node.js v18.18.2
Oct 26 08:54:38 AM  ==> Requesting node version 18
Oct 26 08:54:41 AM  ==> Using Node version 18.18.2 via environment variable NODE_VERSION
Oct 26 08:54:41 AM  ==> Docs on specifying a Node version: https://render.com/docs/node-version
Oct 26 08:54:41 AM  ==> Running 'npm run start:prod'
Oct 26 08:54:44 AM  
Oct 26 08:54:44 AM  > sib-be@1.0.0 start:prod
Oct 26 08:54:44 AM  > node dist/main
Oct 26 08:54:44 AM  
Oct 26 08:54:53 AM  [Nest] 61  - 10/26/2023, 12:54:53 PM     LOG [NestFactory] Starting Nest application...
Oct 26 08:54:54 AM  [Nest] 61  - 10/26/2023, 12:54:54 PM     LOG [InstanceLoader] TypeOrmModule dependencies initialized +292ms
Oct 26 08:54:54 AM  [Nest] 61  - 10/26/2023, 12:54:54 PM     LOG [InstanceLoader] PassportModule dependencies initialized +0ms
Oct 26 08:54:54 AM  [Nest] 61  - 10/26/2023, 12:54:54 PM     LOG [InstanceLoader] JwtModule dependencies initialized +0ms
Oct 26 08:54:54 AM  [Nest] 61  - 10/26/2023, 12:54:54 PM     LOG [InstanceLoader] ConfigHostModule dependencies initialized +1ms
Oct 26 08:54:54 AM  [Nest] 61  - 10/26/2023, 12:54:54 PM     LOG [InstanceLoader] AppModule dependencies initialized +0ms
Oct 26 08:54:54 AM  [Nest] 61  - 10/26/2023, 12:54:54 PM     LOG [InstanceLoader] ConfigModule dependencies initialized +0ms
Oct 26 08:54:54 AM  query: SELECT * FROM current_schema()
Oct 26 08:55:02 AM  query: SELECT version();
Oct 26 08:55:02 AM  query: SELECT * FROM "information_schema"."tables" WHERE "table_schema" = 'public' AND "table_name" = 'migrations'
Oct 26 08:55:02 AM  query: SELECT * FROM "migrations" "migrations" ORDER BY "id" DESC
Oct 26 08:55:02 AM  [Nest] 61  - 10/26/2023, 12:55:02 PM     LOG [InstanceLoader] TypeOrmCoreModule dependencies initialized +8412ms
Oct 26 08:55:02 AM  [Nest] 61  - 10/26/2023, 12:55:02 PM     LOG [InstanceLoader] TypeOrmModule dependencies initialized +0ms
//  ===== more load endpoints
Oct 26 08:55:02 AM  [Nest] 61  - 10/26/2023, 12:55:02 PM     LOG [InstanceLoader] TypeOrmModule dependencies initialized +0ms
Oct 26 08:55:02 AM  query: SELECT "User"."id" AS "User_id", "User"."name" AS "User_name", "User"."password" AS "User_password", "User"."email" AS "User_email", "User"."created_at" AS "User_created_at", "User"."updated_at" AS "User_updated_at" FROM "user" "User"
Oct 26 08:55:02 AM  query failed: SELECT "User"."id" AS "User_id", "User"."name" AS "User_name", "User"."password" AS "User_password", "User"."email" AS "User_email", "User"."created_at" AS "User_created_at", "User"."updated_at" AS "User_updated_at" FROM "user" "User"
Oct 26 08:55:02 AM  error: error: relation "user" does not exist
Oct 26 08:55:02 AM  /opt/render/project/src/node_modules/typeorm/driver/postgres/PostgresQueryRunner.js:211
Oct 26 08:55:02 AM              throw new QueryFailedError_1.QueryFailedError(query, parameters, err);
Oct 26 08:55:02 AM                    ^
Oct 26 08:55:02 AM  
Oct 26 08:55:02 AM  QueryFailedError: relation "user" does not exist
Oct 26 08:55:02 AM      at PostgresQueryRunner.query (/opt/render/project/src/node_modules/typeorm/driver/postgres/PostgresQueryRunner.js:211:19)
Oct 26 08:55:02 AM      at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Oct 26 08:55:02 AM      at async SelectQueryBuilder.loadRawResults (/opt/render/project/src/node_modules/typeorm/query-builder/SelectQueryBuilder.js:2183:25)
Oct 26 08:55:02 AM      at async SelectQueryBuilder.executeEntitiesAndRawResults (/opt/render/project/src/node_modules/typeorm/query-builder/SelectQueryBuilder.js:2034:26)
Oct 26 08:55:02 AM      at async SelectQueryBuilder.getRawAndEntities (/opt/render/project/src/node_modules/typeorm/query-builder/SelectQueryBuilder.js:684:29)
Oct 26 08:55:02 AM      at async SelectQueryBuilder.getMany (/opt/render/project/src/node_modules/typeorm/query-builder/SelectQueryBuilder.js:750:25)
Oct 26 08:55:02 AM      at async UserModule.createDefaultUsers (/opt/render/project/src/dist/user/user.module.js:26:23)
Oct 26 08:55:02 AM      at async UserModule.onModuleInit (/opt/render/project/src/dist/user/user.module.js:23:9)
Oct 26 08:55:02 AM      at async callModuleInitHook (/opt/render/project/src/node_modules/@nestjs/core/hooks/on-module-init.hook.js:51:9)
Oct 26 08:55:02 AM      at async NestApplication.callInitHook (/opt/render/project/src/node_modules/@nestjs/core/nest-application-context.js:223:13) {
Oct 26 08:55:02 AM    query: 'SELECT "User"."id" AS "User_id", "User"."name" AS "User_name", "User"."password" AS "User_password", "User"."email" AS "User_email", "User"."created_at" AS "User_created_at", "User"."updated_at" AS "User_updated_at" FROM "user" "User"',
Oct 26 08:55:02 AM    parameters: [],
Oct 26 08:55:02 AM    driverError: error: relation "user" does not exist
Oct 26 08:55:02 AM        at /opt/render/project/src/node_modules/pg/lib/client.js:526:17
Oct 26 08:55:02 AM        at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Oct 26 08:55:02 AM        at async PostgresQueryRunner.query (/opt/render/project/src/node_modules/typeorm/driver/postgres/PostgresQueryRunner.js:178:25)
Oct 26 08:55:02 AM        at async SelectQueryBuilder.loadRawResults (/opt/render/project/src/node_modules/typeorm/query-builder/SelectQueryBuilder.js:2183:25)
Oct 26 08:55:02 AM        at async SelectQueryBuilder.executeEntitiesAndRawResults (/opt/render/project/src/node_modules/typeorm/query-builder/SelectQueryBuilder.js:2034:26)
Oct 26 08:55:02 AM        at async SelectQueryBuilder.getRawAndEntities (/opt/render/project/src/node_modules/typeorm/query-builder/SelectQueryBuilder.js:684:29)
Oct 26 08:55:02 AM        at async SelectQueryBuilder.getMany (/opt/render/project/src/node_modules/typeorm/query-builder/SelectQueryBuilder.js:750:25)
Oct 26 08:55:02 AM        at async UserModule.createDefaultUsers (/opt/render/project/src/dist/user/user.module.js:26:23)
Oct 26 08:55:02 AM        at async UserModule.onModuleInit (/opt/render/project/src/dist/user/user.module.js:23:9)
Oct 26 08:55:02 AM        at async callModuleInitHook (/opt/render/project/src/node_modules/@nestjs/core/hooks/on-module-init.hook.js:51:9) {
Oct 26 08:55:02 AM      length: 104,
Oct 26 08:55:02 AM      severity: 'ERROR',
Oct 26 08:55:02 AM      code: '42P01',
Oct 26 08:55:02 AM      detail: undefined,
Oct 26 08:55:02 AM      hint: undefined,
Oct 26 08:55:02 AM      position: '222',
Oct 26 08:55:02 AM      internalPosition: undefined,
Oct 26 08:55:02 AM      internalQuery: undefined,
Oct 26 08:55:02 AM      where: undefined,
Oct 26 08:55:02 AM      schema: undefined,
Oct 26 08:55:02 AM      table: undefined,
Oct 26 08:55:02 AM      column: undefined,
Oct 26 08:55:02 AM      dataType: undefined,
Oct 26 08:55:02 AM      constraint: undefined,
Oct 26 08:55:02 AM      file: 'parse_relation.c',
Oct 26 08:55:02 AM      line: '1395',
Oct 26 08:55:02 AM      routine: 'parserOpenTable'
Oct 26 08:55:02 AM    },
Oct 26 08:55:02 AM    length: 104,
Oct 26 08:55:02 AM    severity: 'ERROR',
Oct 26 08:55:02 AM    code: '42P01',
Oct 26 08:55:02 AM    detail: undefined,
Oct 26 08:55:02 AM    hint: undefined,
Oct 26 08:55:02 AM    position: '222',
Oct 26 08:55:02 AM    internalPosition: undefined,
Oct 26 08:55:02 AM    internalQuery: undefined,
Oct 26 08:55:02 AM    where: undefined,
Oct 26 08:55:02 AM    schema: undefined,
Oct 26 08:55:02 AM    table: undefined,
Oct 26 08:55:02 AM    column: undefined,
Oct 26 08:55:02 AM    dataType: undefined,
Oct 26 08:55:02 AM    constraint: undefined,
Oct 26 08:55:02 AM    file: 'parse_relation.c',
Oct 26 08:55:02 AM    line: '1395',
Oct 26 08:55:02 AM    routine: 'parserOpenTable'
Oct 26 08:55:02 AM  }
Oct 26 08:55:02 AM  
Oct 26 08:55:02 AM  Node.js v18.18.2

I have the following configurations for the render web service which is where I am deploying the nest.js application

  • Branch: develop
  • Root Directory: empty
  • Build Filters: not configuret
  • Build Commands: npm install && npx @nestjs/cli build (Note: I moved the "@nestjs/cli":"^10.0.0", dependency from devDependencies to dependencies.)
  • Start Command: npm run start:prod

Hi,

The error in the logs you shared seems to be:

QueryFailedError: relation "user" does not exist

It sounds like your database may not setup/migrated correctly.

Alan

Hello Alan yes, I add the migrations scripts to package.json but the error keep going, and show another error when I remove the migrations config

If there’s a different error, please could you share the details.

Alan

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.