Fullstack Node.js & React
Trang chủ / Module 4
🌐 Module 4 / 19 · 4 ngày 📅 Tuần 3 ●○○○ Dễ

HTTP & REST API với Node: Express 5 / Fastify từ đúng đến chuẩn

HTTP vừa đủ sâu, thiết kế REST đúng, cấu trúc một API Node theo lớp (route → controller → service → repository), validate, xử lý lỗi tập trung, logging có cấu trúc.

HTTPRESTExpress 5FastifyValidationError handling
📌 Vì sao module này quan trọng

Đây là module "dễ" của phần backend nhưng là nơi phân loại ứng viên nhanh nhất: chỉ cần nhìn status code, cách trả lỗi và cấu trúc thư mục của một repo là reviewer biết bạn đã từng làm production hay chưa. Một API chuẩn có lỗi nhất quán, validate ở biên, không rò stack trace, có request ID trong log — những thứ rẻ tiền nhưng 80% portfolio thiếu.

🎯 Mục tiêu học tập

  • Nắm method, status code, header, idempotency, caching header của HTTP
  • Thiết kế resource REST, phân trang, lọc, sắp xếp, versioning
  • Cấu trúc API theo lớp, tách logic nghiệp vụ khỏi framework
  • Validate request bằng Zod, xử lý lỗi tập trung theo chuẩn Problem Details
  • Logging có cấu trúc với pino và request ID

HTTP vừa đủ sâu

MethodNgữ nghĩaIdempotentStatus thường dùng
GETĐọcCó200, 304, 404
POSTTạo / hành độngKhông (cần Idempotency-Key)201 + Location, 202
PUTThay thế toàn bộCó200, 204
PATCHSửa một phầnTuỳ thiết kế200
DELETEXoáCó204, 404
  • 400 sai định dạng · 401 chưa đăng nhập · 403 không đủ quyền · 404 không có · 409 xung đột trạng thái · 422 đúng cú pháp nhưng sai nghiệp vụ · 429 quá giới hạn · 5xx lỗi server (không bao giờ là lỗi của client).
  • Header quan trọng: Cache-Control, ETag/If-None-Match, Content-Type, Authorization, Retry-After, các header CORS.
  • HTTP/2 multiplexing và keep-alive: vì sao không còn cần gộp request như thời HTTP/1.1.

Thiết kế REST: resource, phân trang, lọc

GET    /v1/projects?status=active&sort=-createdAt&limit=20&cursor=eyJpZCI6...
GET    /v1/projects/{projectId}
POST   /v1/projects
PATCH  /v1/projects/{projectId}
GET    /v1/projects/{projectId}/tasks
POST   /v1/projects/{projectId}/archive        # hành động không vừa CRUD → sub-resource động từ

200 OK
{
  "data": [ ... ],
  "pageInfo": { "nextCursor": "eyJpZCI6...", "hasMore": true }
}
Phân trangƯuNhược
Offset (?page=3)Dễ, nhảy trang đượcChậm ở trang sâu (OFFSET 100000), lặp/mất dòng khi dữ liệu thay đổi
Cursor / keysetNhanh ổn định, đúng khi có dữ liệu mớiKhông nhảy trang; cần sort ổn định (createdAt, id)

Cấu trúc dự án theo lớp

src/
├── app.ts                  # tạo app, gắn middleware, route — không listen (để test)
├── server.ts               # listen + graceful shutdown
├── config/env.ts           # Zod parse process.env
├── modules/
│   └── projects/
│       ├── projects.routes.ts      # HTTP: parse, validate, gọi service, map status code
│       ├── projects.service.ts     # nghiệp vụ thuần, không biết req/res
│       ├── projects.repository.ts  # truy vấn DB
│       ├── projects.schemas.ts     # Zod schema request/response
│       └── projects.test.ts
├── shared/
│   ├── errors.ts           # AppError, NotFoundError, ConflictError...
│   ├── middleware/         # requestId, auth, errorHandler
│   └── logger.ts
└── db/

Quy tắc vàng: service không import Express. Nhờ vậy test service không cần HTTP, và đổi framework (Express → Fastify → NestJS) chỉ chạm lớp routes. Tổ chức theo tính năng (projects, billing) chứ không theo loại file (controllers/, services/).

Express 5 hay Fastify?

Express 5Fastify
Phổ biến / tuyển dụngNhiều nhất, code legacy khắp nơiTăng nhanh
Hiệu năngĐủ cho đa sốNhanh hơn rõ rệt, serialize bằng schema
Lỗi trong async handlerExpress 5 tự chuyển tới error handler (Express 4 thì không)Có sẵn
Validation / OpenAPITự lắp (Zod + zod-to-openapi)Tích hợp JSON Schema, type provider cho Zod/TypeBox

Khoá học dùng Express 5 để hiểu nền ở module này, sau đó chuyển sang NestJS (chạy trên Express hoặc Fastify) ở Module 5 vì đó là lựa chọn phổ biến nhất cho backend Node quy mô lớn ở các công ty trả lương cao.

Validate và xử lý lỗi tập trung

// shared/errors.ts
export class AppError extends Error {
  constructor(public status: number, public code: string, message: string, public details?: unknown) {
    super(message);
  }
}
export const notFound = (what: string) => new AppError(404, 'NOT_FOUND', `${what} not found`);

// middleware/validate.ts
export const validate = <T extends z.ZodTypeAny>(schema: T) =>
  (req: Request, _res: Response, next: NextFunction) => {
    const r = schema.safeParse(req.body);
    if (!r.success) throw new AppError(400, 'VALIDATION_ERROR', 'Invalid body', z.flattenError(r.error));
    req.body = r.data;
    next();
  };

// middleware/errorHandler.ts — đăng ký CUỐI CÙNG
export const errorHandler: ErrorRequestHandler = (err, req, res, _next) => {
  const isApp = err instanceof AppError;
  if (!isApp) req.log.error({ err }, 'unhandled error');      // chỉ log stack cho lỗi không lường trước
  res.status(isApp ? err.status : 500).type('application/problem+json').json({
    type: `https://api.example.com/errors/${isApp ? err.code : 'INTERNAL'}`,
    title: isApp ? err.message : 'Internal Server Error',     // KHÔNG trả stack trace ra ngoài
    status: isApp ? err.status : 500,
    code: isApp ? err.code : 'INTERNAL',
    details: isApp ? err.details : undefined,
    requestId: req.id,
  });
};

Logging có cấu trúc và tài liệu API

  • pino + pino-http: log JSON, mỗi dòng có reqId, userId, thời gian xử lý. Không console.log trên production; không log mật khẩu/token (dùng redact).
  • Trả X-Request-Id trong response để người dùng báo lỗi kèm ID.
  • OpenAPI sinh từ Zod schema → Swagger UI / Scalar. Frontend sinh client type-safe từ đó (openapi-typescript).
  • Middleware nền: helmet, cors có allowlist, giới hạn body size, compression (hoặc để reverse proxy làm).

🏋️ Bài tập thực hành

API quản lý Project/Task bản đầu tiên

Xây REST API cho Project và Task (CRUD, gán người, đổi trạng thái) bằng Express 5 + TypeScript, tạm lưu trong bộ nhớ qua một repository interface (Module 6 sẽ thay bằng PostgreSQL). Yêu cầu: cấu trúc theo tính năng, Zod validate mọi input, lỗi theo Problem Details, cursor pagination, pino log có request ID, OpenAPI docs tại /docs, test bằng supertest cho mọi status code chính (200, 201, 400, 404, 409). Đây là nền móng của capstone.

📚 Tài nguyên học tập

✅ Tự đánh giá hoàn thành

  • Dùng đúng method và status code cho mọi endpoint
  • Service không phụ thuộc framework HTTP
  • Lỗi nhất quán theo Problem Details, không lộ stack trace
  • Có log JSON với request ID và tài liệu OpenAPI