Communitygithub.com

Express.js 및 Fastify 패턴

미들웨어, 라우트 구성, Zod를 통한 검증, 에러 처리, 플러그인 시스템, 요청 라이프사이클, TypeScript 설정 등 Express.js와 Fastify의 개발 패턴을 제공합니다.

Express.js 및 Fastify 패턴란 무엇인가요?

이 스킬은 Express.js와 Fastify를 사용하는 Node.js 백엔드 개발자를 위한 포괄적인 패턴 가이드입니다. 라우트를 도메인별로 구성하고, Zod를 사용한 입력 검증, 중앙화된 에러 처리, 일관된 에러 응답 형식, TypeScript 제네릭 활용 등 모범 사례를 제시합니다. Express에서는 CORS, body parser, 인증, 속도 제한, 라우트, 에러 핸들러 순서로 미들웨어를 배치하고, Fastify에서는 플러그인 시스템과 `@fastify/type-provider-zod`를 통한 타입 안전한 스키마 검증을 권장합니다. 또한 헬스 체크 엔드포인트, Graceful Shutdown, 비동기 에러 처리 등 운영에 필요한 패턴도 포함하고 있습니다. 각 패턴은 실제 코드 예제와 함께 제공되어, 개발자가 즉시 프로젝트에 적용할 수 있도록 돕습니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/YepAPI/skills/tree/HEAD/skills/express-fastify

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

Express & Fastify

규칙

  • 라우트를 도메인별로 구성: routes/users.ts, routes/orders.ts — 리소스당 하나의 라우터
  • 모든 입력을 Zod로 검증: 처리 전 req.body, req.params, req.query 파싱
  • 중앙화된 에러 핸들러: Express는 catch-all 미들웨어, Fastify는 setErrorHandler
  • 일관된 에러 형식 반환: { error: { code: string, message: string, details?: unknown } }
  • TypeScript: 제네릭으로 요청/응답 타입 지정 — Request<Params, ResBody, ReqBody, Query>
  • 미들웨어 순서: CORS, body parser, 인증, 속도 제한, 라우트, 에러 핸들러
  • 비동기 라우트 핸들러 사용 — 에러 캐치로 감싸거나 express-async-errors 사용
  • Fastify: 플러그인 시스템을 사용하여 라우트와 데코레이터 캡슐화 — fastify.register()
  • Fastify 스키마: JSON Schema 정의 또는 @fastify/type-provider-zod를 사용한 검증 + 직렬화
  • 헬스 체크: GET /health — DB/Redis 연결 상태와 함께 200 반환
  • Graceful Shutdown: SIGTERM 수신, 새 연결 중단, 진행 중인 요청 완료

패턴

// Express + Zod 검증
import { Router } from "express";
import { z } from "zod";

const router = Router();
const CreateUserSchema = z.object({ email: z.string().email(), name: z.string().min(1) });

router.post("/users", async (req, res, next) => {
  try {
    const body = CreateUserSchema.parse(req.body);
    const user = await createUser(body);
    res.status(201).json(user);
  } catch (err) { next(err); }
});
// Fastify + Zod 타입 프로바이더
import Fastify from "fastify";
import { serializerCompiler, validatorCompiler, ZodTypeProvider } from "fastify-type-provider-zod";

const app = Fastify().withTypeProvider<ZodTypeProvider>();
app.setValidatorCompiler(validatorCompiler);
app.setSerializerCompiler(serializerCompiler);

app.post("/users", { schema: { body: CreateUserSchema } }, async (req) => {
  return createUser(req.body); // 완전히 타입이 지정됨
});

피해야 할 것

  • 라우트 핸들러에 비즈니스 로직을 넣지 말 것 — 서비스/도메인 레이어로 추출
  • Express에서 비동기 에러 처리를 잊지 말 것 — 처리되지 않은 거절은 프로세스를 중단시킴
  • 모든 라우트를 하나의 파일에 임포트하지 말 것 — 모듈화를 위해 router.use() 또는 Fastify 플러그인 사용
  • "프론트엔드가 검증하니까" 입력 검증을 건너뛰지 말 것 — 항상 서버 측에서 검증

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

YepAPI/skills

WCAG 2.1 AA — semantic HTML, keyboard navigation, screen readers.

YepAPI/skills

Experiment setup, variant splitting, statistical significance, and feature flag integration.

YepAPI/skills

CRUD generators, data tables, user management, role-based access, and bulk operations.

YepAPI/skills

Monitor what ChatGPT and Gemini say about your brand using YepAPI.

YepAPI/skills

Queue workers with BullMQ/Inngest/Trigger.dev, job retries, dead letter queues, concurrency.

YepAPI/skills

Commander.js, interactive prompts with Clack, spinners, colors, config files, exit codes, and npm publishing.

YepAPI/skills

cmdk integration, Cmd+K trigger, fuzzy search, grouped actions, keyboard navigation, and dynamic action registration.

YepAPI/skills

Content planning with trend and sentiment data from YepAPI.

YepAPI/skills

Content calendar, keyword-driven planning, and content briefs.

YepAPI/skills

Theme switching with CSS variables, system preference detection, next-themes, and persistence.

YepAPI/skills

Threaded comments, @mentions, reactions, moderation queue, optimistic UI, and cursor pagination.

YepAPI/skills

Competitive analysis between domains using YepAPI.

YepAPI/skills

Layout grids, KPI cards, data tables with sorting/filtering, sidebar navigation, and responsive breakpoints.

YepAPI/skills

Data encryption — TLS everywhere, AES-256-GCM for PII, bcrypt passwords, encrypted backups.

YepAPI/skills

Chart patterns with Recharts/Nivo/D3, responsive containers, color scales, and accessibility.

YepAPI/skills

Drizzle schema definition, push vs migrate, type-safe queries, relations, transactions, and prepared statements.

YepAPI/skills

Upload handling, resize/compress, CDN delivery, blur placeholders, and next/image patterns.

YepAPI/skills

Local business and Google Maps research using YepAPI.

YepAPI/skills

Cursor-based pagination, IntersectionObserver, virtualized lists with @tanstack/react-virtual, and scroll position restoration.

YepAPI/skills

Chat UI components, streaming responses with AI SDK, context window management, and RAG patterns.

관련 스킬