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 で HTTPS 通信に対応する

Posted at

環境変数からファイルを指定できるとなお良し。

src/main.ts
import { NestApplicationOptions, ValidationPipe } from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import * as fs from "fs";
import { AppModule } from "./app.module";

async function bootstrap() {
  const options: Partial<NestApplicationOptions> = (() => {
    if (process.env.HTTPS_KEY) {
      console.log("Run on HTTPS");
      return {
        httpsOptions: {
          key: fs.readFileSync(process.env.HTTPS_KEY),
          cert: fs.readFileSync(process.env.HTTPS_CERT),
        },
      };
    }
    console.log("Run on HTTP");
    return {};
  })();
  const app = await NestFactory.create(AppModule, options);
  // リクエストのバリデーションチェックをグローバルに有効にする
  // `transform: true`でオブジェクトをDTOに変換する
  app.useGlobalPipes(new ValidationPipe({ transform: true }));
  app.enableCors();
  await app.listen(parseInt(process.env.PORT));
}
bootstrap();
.env.development.local
PORT=3000
# 中略
HTTPS_KEY=/home/{ユーザー名}/server.key
HTTPS_CERT=/home/{ユーザー名}/server.crt
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?