☰ Mục lục series
Tài liệu NestJS tiếng Việt
  1. Nhập môn (Overview)
    1. Giới thiệu
    2. First steps
    3. Controllers
    4. Providers
    5. Modules
    6. Middleware
    7. Exception filters
    8. Pipes
    9. Guards
    10. Interceptors
    11. Custom decorators
  2. Nền tảng (Fundamentals)
    1. Custom providers
    2. Asynchronous providers
    3. Dynamic modules
    4. Injection scopes
    5. Circular dependency
    6. Module reference
    7. Lazy-loading modules
    8. Execution context
    9. Lifecycle events
    10. Discovery service
    11. Platform agnosticism
    12. Testing
  3. Kỹ thuật (Techniques)
    1. Configuration
    2. Database (SQL)
    3. MongoDB
    4. Validation
    5. Caching
    6. Serialization
    7. Versioning
    8. Task scheduling
    9. Queues
    10. Logging
    11. Cookies
    12. Events
    13. Compression
    14. File upload
    15. Streaming files
    16. HTTP module
    17. Session
    18. MVC
    19. Performance (Fastify)
    20. Server-Sent Events
  4. Bảo mật (Security)
    1. Authentication
    2. Authorization
    3. Encryption & Hashing
    4. Helmet
    5. CORS
    6. CSRF
    7. Rate limiting
    8. Vòng đời request
  5. OpenAPI (Swagger)
    1. Introduction
    2. Types and parameters
    3. Operations
    4. Security
    5. Mapped types
    6. Decorators
    7. CLI plugin
    8. Other features
  6. Recipes
    1. REPL
    2. CRUD generator
    3. SWC (fast compiler)
    4. Passport (auth)
    5. Hot reload
    6. MikroORM
    7. Router module
    8. Health checks (Terminus)
    9. CQRS
    10. Prisma
    11. Serve static
    12. Commander
    13. Async local storage
  7. WebSockets
    1. Gateways
    2. Exception filters
    3. Pipes
    4. Guards
    5. Interceptors
    6. Adapters
  8. Microservices
    1. Overview
    2. Redis
    3. MQTT
    4. NATS
    5. RabbitMQ
    6. Kafka
    7. gRPC
    8. Custom transporters
    9. Exception filters
    10. Pipes
    11. Pre-request hooks
    12. Guards
    13. Interceptors
  9. GraphQL
    1. Quick start
    2. Resolvers
    3. Mutations
    4. Subscriptions
    5. Scalars
    6. Directives
    7. Interfaces
    8. Unions and enums
    9. Field middleware
    10. Mapped types
    11. Plugins
    12. Complexity
    13. Extensions
    14. CLI plugin
    15. Generating SDL
    16. Sharing models
    17. Other features
    18. Federation
  10. CLI & triển khai
    1. CLI overview
    2. Workspaces
    3. Libraries
    4. Usage
    5. Scripts
    6. Deployment
    7. Standalone apps
  11. FAQ
    1. Serverless
    2. HTTP adapter
    3. Keep-Alive connections
    4. Global path prefix
    5. Raw body
    6. Hybrid application
    7. HTTPS & multiple servers
    8. Common errors
  12. Phụ lục
    1. Bảng thuật ngữ
Kỹ thuật (Techniques)

Cookies

Bản dịch từ docs.nestjs.com/techniques/cookies

HTTP cookie là một mẩu dữ liệu nhỏ được browser của người dùng lưu trữ. Cookie được thiết kế để làm cơ chế đáng tin cậy cho website ghi nhớ thông tin trạng thái (stateful). Khi người dùng truy cập lại website, cookie sẽ tự động được gửi kèm request.

Use with Express (default) (Dùng với Express - mặc định)

Đầu tiên, cài package cần thiết (và type của nó cho người dùng TypeScript):

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

Sau khi cài xong, áp dụng middleware cookie-parser như một global middleware (ví dụ, trong file main.ts của bạn).

import cookieParser from 'cookie-parser';
// đặt ở đâu đó trong file khởi tạo của bạn
app.use(cookieParser());

Bạn có thể truyền một số option cho middleware cookieParser:

  • secret một string hoặc mảng dùng để ký (sign) cookie. Tùy chọn này là optional, và nếu không chỉ định, sẽ không parse các signed cookie. Nếu một string được cung cấp, nó sẽ được dùng làm secret. Nếu một mảng được cung cấp, sẽ có nỗ lực unsign cookie với từng secret theo thứ tự.
  • options một object được truyền vào cookie.parse như tham số thứ hai. Xem cookie để biết thêm thông tin.

Middleware sẽ parse header Cookie trên request và expose dữ liệu cookie qua property req.cookies, và nếu có secret được cung cấp, qua property req.signedCookies. Các property này là các cặp tên-giá trị của tên cookie và giá trị cookie.

Khi một secret được cung cấp, module này sẽ unsign và validate mọi giá trị signed cookie, đồng thời chuyển các cặp tên-giá trị đó từ req.cookies sang req.signedCookies. Signed cookie là cookie có giá trị được thêm tiền tố s:. Signed cookie không qua được validation chữ ký sẽ có giá trị false thay vì giá trị đã bị sửa đổi.

Với thiết lập này, bạn có thể đọc cookie ngay trong route handler, như sau:

@Get()
findAll(@Req() request: Request) {
  console.log(request.cookies); // hoặc "request.cookies['cookieKey']"
  // hoặc console.log(request.signedCookies);
}

Gợi ý Decorator @Req() được import từ @nestjs/common, còn Request từ package express.

Để gắn một cookie vào response trả về, dùng phương thức Response#cookie():

@Get()
findAll(@Res({ passthrough: true }) response: Response) {
  response.cookie('key', 'value')
}

Cảnh báo Nếu bạn muốn để logic xử lý response cho framework, nhớ đặt option passthrough thành true, như minh họa trên. Đọc thêm tại đây.

Gợi ý Decorator @Res() được import từ @nestjs/common, còn Response từ package express.

Use with Fastify (Dùng với Fastify)

Đầu tiên, cài package cần thiết:

$ npm i @fastify/cookie

Sau khi cài xong, đăng ký plugin @fastify/cookie:

import fastifyCookie from '@fastify/cookie';

// đặt ở đâu đó trong file khởi tạo của bạn
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter());
await app.register(fastifyCookie, {
  secret: 'my-secret', // dùng để ký cookie
});

Với thiết lập này, bạn có thể đọc cookie ngay trong route handler, như sau:

@Get()
findAll(@Req() request: FastifyRequest) {
  console.log(request.cookies); // hoặc "request.cookies['cookieKey']"
}

Gợi ý Decorator @Req() được import từ @nestjs/common, còn FastifyRequest từ package fastify.

Để gắn một cookie vào response trả về, dùng phương thức FastifyReply#setCookie():

@Get()
findAll(@Res({ passthrough: true }) response: FastifyReply) {
  response.setCookie('key', 'value')
}

Để đọc thêm về phương thức FastifyReply#setCookie(), xem trang này.

Cảnh báo Nếu bạn muốn để logic xử lý response cho framework, nhớ đặt option passthrough thành true, như minh họa trên. Đọc thêm tại đây.

Gợi ý Decorator @Res() được import từ @nestjs/common, còn FastifyReply từ package fastify.

Creating a custom decorator (cross-platform) (Tạo decorator tùy chỉnh - cross-platform)

Để có một cách tiện lợi, khai báo rõ ràng (declarative) để truy cập cookie đến, chúng ta có thể tạo một custom decorator.

import { createParamDecorator, ExecutionContext } from '@nestjs/common';

export const Cookies = createParamDecorator((data: string, ctx: ExecutionContext) => {
  const request = ctx.switchToHttp().getRequest();
  return data ? request.cookies?.[data] : request.cookies;
});

Decorator @Cookies() sẽ trích xuất toàn bộ cookie, hoặc một cookie theo tên từ object req.cookies và điền giá trị đó vào tham số được decorate.

Với thiết lập này, chúng ta có thể dùng decorator này trong signature của route handler, như sau:

@Get()
findAll(@Cookies('name') name: string) {}

Ghi chú người dịch Tương tự cookie-parser trong Express thuần hoặc middleware đọc cookie ở Laravel (Illuminate\Cookie), Nest không tự làm điều đó — nó chỉ bọc lại middleware gốc của Express/Fastify. Nghĩa là bạn vẫn phải hiểu cách adapter bên dưới (Express hay Fastify) xử lý cookie, vì API và hành vi (ví dụ ký cookie, passthrough) khác nhau giữa hai adapter này.

Nội dung gốc: NestJS Documentation © Kamil Myśliwiec, giấy phép MIT. Bản dịch và ghi chú: Lê Văn Dũng.