0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

NestJsでつまづいたところと解決策

0
Posted at

NestJsに初めて手を出してみたのですが、スムーズにいかなかったところがあったので、メモを残しておきます。

仕様環境

機種 windows11
nodejs v24.9.0
nestjs 11.0.14

Error: SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string

コード(before)

prisma.service.ts
import { Injectable, OnModuleInit } from '@nestjs/common';
import { PrismaPg } from '@prisma/adapter-pg';
import { PrismaClient } from '@prisma/client';

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
    constructor() {
        const url = process.env.DATABASE_URL!;
        if (!url) {
            throw new Error('DATABASE_URL is not defined in .env');
        }
        console.info(`This is Connection "${url}"`);
        const pool = new PrismaPg({ connectionString: url });
        super({ adapter: pool });
    }
}
app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { HogeModule } from './hoge/hoge.module';
import { PrismaModule } from './prisma/prisma.module';
import { ConfigModule } from '@nestjs/config';

@Module({
  imports: [
    HogeModule,
    PrismaModule
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule { }


原因

process.env.DATABASE_URLが読み込まれていませんでした。

原因の特定方法

process.env.DATABASE_URLを取得した後にconsole.logした。
→ undefinedだった

解決した方法(変更部分)

app.module.ts
//~
imports: [
    HogeModule,
    PrismaModule,
    ConfigModule.forRoot({ //
      isGlobal: true,      // この3行を追加
    })                     //
  ]
//~

これをすることで、あらかじめ.envファイルを読み込んでくれます。
もし、.env.developmentなどほかの環境変数ファイルも読み込んでほしいなら

app.module.ts
imports: [
    HogeModule,
    PrismaModule,
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: ['.env.development.local', '.env.development'],
    })
  ]

このようにすると、これらのファイルも読み込んでくれます。
参考(公式サイト):https://docs.nestjs.com/techniques/configuration#getting-started

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?