포시코딩

[Nest] set cookie-parser 본문

Node.js

[Nest] set cookie-parser

포시 2023. 9. 22. 10:21
728x90

설치

npm i cookie-parser
npm i -D @types/cookie-parser

 

 

세팅

tsconfig.json

{
  "compilerOptions": {
  	// ...
    "esModuleInterop": true,
  }
}

ES6 모듈 사양을 준수하여 CommonJS 모듈을 가져올 수 있게 설정

 

main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import cookieParser from 'cookie-parser';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.use(cookieParser());
  await app.listen(3000);
}
bootstrap();

 

사용 예시

import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";

@Injectable()
export class JwtAccessAuthGuard implements CanActivate {
  constructor(private jwtService: JwtService) {}
  
  async canActivate(context: ExecutionContext): Promise<any> {
    try {
      const request = context.switchToHttp().getRequest();
      const access_token = request.cookies['access_token'];  // 여기
      const user = await this.jwtService.verify(access_token);
      request.user = user;
      return user;
    } catch(err) {
      return false;
    }
  }
}

 

728x90