1. ํ์ ์ฌ์ ์ค์น ์๊ฑด & ๊ฐ๋ฐ ํ๊ฒฝ ๊ตฌ์ฑ (Prerequisites)
๐ป ์์คํ ์ค์น ๋ฐ ์คํ ์๊ตฌ์ฌ์ (System Requirements)
| ํญ๋ชฉ | ์ต์ ์ฌ์ (Minimum) | ๊ถ์ฅ ์ฌ์ (Recommended) | ์ฐธ๊ณ ๋ฐ ๋น๊ณ |
|---|---|---|---|
| ์ด์์ฒด์ (OS) | Linux, macOS, Windows 10/11 | Ubuntu 22.04 LTS / Debian 12, macOS (Apple Silicon) | ์ปจํ ์ด๋(Docker/K8s) ๋ฐฐํฌ์ ์ต์ ํ |
| CPU | 1 ์ฝ์ด (x86_64 ๋๋ ARM64) | 2 ์ฝ์ด ~ 4 ์ฝ์ด ์ด์ | V8 JIT ์ต์ ํ ๋ฐ Ajv ์คํค๋ง ์ปดํ์ผ |
| ๋ฉ๋ชจ๋ฆฌ (RAM) | 512 MB ์ด์ | 2 GB ~ 4 GB ์ด์ | ํ๋ก๋์ Pino ๋ฒํผ๋ง ๋ฐ ๊ณ ์ฑ๋ฅ ์ฒ๋ฆฌ ๊ถ์ฅ |
| ๋์คํฌ (Storage) | 300 MB ์ด์์ ์ฌ์ ๊ณต๊ฐ | 2 GB ์ด์์ ๊ณ ์ SSD | node_modules ๋ฐ TypeScript ๋น๋ ์ฐ์ถ๋ฌผ |
| ๋คํธ์ํฌ / ๋ฐํ์ | Node.js 18.x LTS (๊ถ์ฅ: 20.x+) | Node.js 22 LTS ๋๋ 20 LTS (Active) | TypeScript 5.4+ ํ๊ฒฝ ๊ถ์ฅ |
Fastify(ํจ์คํฐํ์ด)๋ Node.js ์ํ๊ณ์์ ๊ฐ์ฅ ๋ฎ์ ์ค๋ฒํค๋์ ๊ทนํ์ ์ฒ๋ฆฌ๋(Throughput)์ ์ ๊ณตํ๋๋ก ์ค๊ณ๋ ์น ํ๋ ์์ํฌ์ ๋๋ค. Express ๋๋น ์ต๋ 4~5๋ฐฐ ๋์ ์ด๋น ์์ฒญ ์ฒ๋ฆฌ(RPS) ์ฑ๋ฅ์ ๋ณด์ด๋ฉฐ, Ajv ๊ธฐ๋ฐ JSON ์คํค๋ง ์ ํจ์ฑ ๊ฒ์ฆ, fast-json-stringify ๊ธฐ๋ฐ ์ด๊ณ ์ JSON ์ง๋ ฌํ, ๊ทธ๋ฆฌ๊ณ TypeProvider๋ฅผ ํตํ ์ปดํ์ผ ํ์ ์๋ํฌ์๋ ์ ์ ํ์ ์ถ๋ก ์ ๋ค์ดํฐ๋ธ๋ก ์ง์ํฉ๋๋ค.
๐ข 1. Node.js ๋ฐํ์ ๋ฐ ํจํค์ง ๋งค๋์ ์ค๋น
# 1. Node.js LTS ๋ฒ์ ํ์ธ (20.x ์ด์ ๊ถ์ฅ)
node -v
npm -v
# 2. ์ต์ pnpm ๋๋ npm ์ต์ ํ (pnpm ์ฌ์ฉ ๊ถ์ฅ)
npm install -g pnpm
pnpm -v
๐ ๏ธ 2. TypeScript ํ๋ก์ ํธ ์ด๊ธฐํ ๋ฐ ํต์ฌ ์์กด์ฑ ์ค์น
Fastify์ TypeBox ๊ธฐ๋ฐ TypeProvider ํ๊ฒฝ์ ๊ตฌ์ถํฉ๋๋ค:
# 1. ํ๋ก์ ํธ ๋๋ ํ ๋ฆฌ ์์ฑ ๋ฐ ์ด๊ธฐํ
mkdir fastify-api-server && cd fastify-api-server
pnpm init
# 2. Fastify ํต์ฌ ๋ฐํ์ ๋ฐ TypeProvider ํจํค์ง ์ค์น
pnpm add fastify @fastify/type-provider-typebox @sinclair/typebox
# 3. ๊ฐ๋ฐ ํธ์ ๋ฐ ์ค๋ฌด ํ๋ฌ๊ทธ์ธ ์ค์น (Swagger, CORS, Sensible ๋ฑ)
pnpm add @fastify/cors @fastify/helmet @fastify/swagger @fastify/swagger-ui @fastify/sensible fastify-plugin
# 4. TypeScript ๋ฐ ์คํ ๋๊ตฌ ๊ฐ๋ฐ ์์กด์ฑ(devDependencies) ์ค์น
pnpm add -D typescript @types/node tsx
โ๏ธ 3. tsconfig.json ๊ตฌ์ฑ (ํ์
์ถ๋ก ํ์ ์ต์
)
Fastify์ TypeProvider์ ๊ฐ๋ ฅํ ํ์
์ถ๋ก ์ ์๋ฒฝํ ํ์ฉํ๋ ค๋ฉด strict: true ๋ฐ ์ ์ ํ ๋ชจ๋ ํด์ ์ค์ ์ด ํ์์ ์
๋๋ค:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2022"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"]
}
2. Fastify ๋ฉํ ๋ชจ๋ธ & ํต์ฌ ์ํคํ ์ฒ ๋ค์ด์ด๊ทธ๋จ
Fastify์ ๋๋ผ์ด ์๋์ ๊ฒฌ๊ณ ํจ์ 3๊ฐ์ง ํต์ฌ ์ํคํ ์ฒ ๊ธฐ๋ฅ์์ ๋น๋กฏ๋ฉ๋๋ค:
- ํ๋ฌ๊ทธ์ธ ์บก์ํ ํธ๋ฆฌ (Encapsulation Tree): ๋ค์์คํ์ด์ค์ ํ ์ ๋ถ๋ชจ-์์ ๊ฐ์ ๊ฒฉ๋ฆฌํ์ฌ ๊ฑฐ๋ํ ๋ชจ๋ ธ๋ฆฌ์ค ์ ํ๋ฆฌ์ผ์ด์ ๋ ์์ ํ๊ฒ ๋ชจ๋ํ.
- ๋จ๋ฐฉํฅ ์์ฒญ ์๋ช ์ฃผ๊ธฐ ํ (Request Lifecycle Pipeline): ๋จ๊ณ๋ณ ๋ช ํํ ์ธํฐ์ ํฐ ์ ๊ณต.
- TypeProvider & Ajv ์คํค๋ง ํ์ดํ๋ผ์ธ: ๋ฐํ์ ์ ํจ์ฑ ๊ฒ์ฆ๊ณผ ์ปดํ์ผ ํ์ ํ์ ์ถ๋ก ์ ์๋ฒฝํ ์ตํฉ.
๐ Fastify ์์ฒญ ์๋ช ์ฃผ๊ธฐ ๋ฐ TypeProvider ํ์ดํ๋ผ์ธ
[ํด๋ผ์ด์ธํธ HTTP Request ์ ์ก]
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Fastify Request Lifecycle โ
โ โ
โ 1. onRequest โโโโโโโโโโโโ> ์ ์ญ ๋ก๊น
, IP ์ฐจ๋จ, ์์ ์์ฒญ ์ธก์ โ
โ โ โ
โ 2. preParsing โโโโโโโโโโโ> ์์ถ ํด์ , ์์ ์คํธ๋ฆผ ์ ์ฒ๋ฆฌ โ
โ โ โ
โ 3. Parsing โโโโโโโโโโโโโโ> application/json ๋ฑ Body ํ์ฑ โ
โ โ โ
โ 4. preValidation โโโโโโโโ> [Ajv Schema Validation] โ
โ โ โข TypeBox/Zod ์คํค๋ง๋ก Query/Param/Body ๊ฒ์ฆโ
โ โ โข ์ ํจ์ฑ ๊ฒ์ฆ ์คํจ ์ ์ฆ์ 400 Bad Requestโ
โ โ โ
โ 5. preHandler โโโโโโโโโโโ> ์ธ์ฆ(JWT), ๊ถํ ์ธ๊ฐ(RBAC) ๊ฐ๋ ์ํ โ
โ โ โ
โ 6. Route Handler โโโโโโโโ> [ํ์
์์ ๋น์ฆ๋์ค ๋ก์ง ์คํ] โ
โ โ โข request.body (์๋ ํ์
์ถ๋ก ์์ฑ) โ
โ โ โข request.query (์๋ ํ์
์ถ๋ก ์์ฑ) โ
โ โผ โ
โ 7. preSerialization โโโโโ> [fast-json-stringify ์ง๋ ฌํ] โ
โ โ โข ์๋ต ์คํค๋ง ๊ธฐ๋ฐ ํํฐ๋ง (๋ฏผ๊ฐ ๋ฐ์ดํฐ ๋ฐฉ์ง)โ
โ โ โข JSON.stringify ๋๋น 2๋ฐฐ ๋น ๋ฅธ C-์คํ์ผ ์ถ๋ ฅโ
โ โ โ
โ 8. onSend โโโโโโโโโโโโโโโ> ์ต์ข
ํค๋(CORS, Helmet) ๋ฐ ๋ณธ๋ฌธ ๋ณ์กฐ โ
โ โ โ
โ 9. onResponse โโโโโโโโโโโ> ์๋ต ์๋ฃ ํ ๋ฉํธ๋ฆญ ๊ธฐ๋ก ๋ฐ ๋ก๊น
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
[ํด๋ผ์ด์ธํธ HTTP 200/201 Response ์์ ]
๐งฉ ํ๋ฌ๊ทธ์ธ ์บก์ํ (Encapsulation) vs fastify-plugin (fp) ๋ชจ๋ธ
[๋ฃจํธ Fastify ์ธ์คํด์ค (Root Scope)]
โโโ [์ผ๋ฐ register] /api/v1 (๋
๋ฆฝ๋ ์บก์ํ ์ค์ฝํ)
โ โโโ ํ
/๋ฐ์ฝ๋ ์ดํฐ๋ ํ์ ์์์๊ฒ๋ง ์์๋จ
โ โโโ ํ์ ๋ ๋ถ๋ชจ ์ค์ฝํ๋ฅผ ์ค์ผ์ํค์ง ์์ (์์ ๊ฒฉ๋ฆฌ)
โ
โโโ [fastify-plugin (fp) register] (๊ณต์ ๊ธ๋ก๋ฒ ์ค์ฝํ)
โโโ DB ํ (fastify.pg, fastify.prisma)
โโโ ์ ์ญ ์ธ์ฆ ๋ฐ์ฝ๋ ์ดํฐ (fastify.authenticate)
โโโ ์บก์ํ ๋ฒฝ์ ํ๋ฌผ์ด ๋ถ๋ชจ ๋ฐ ํ์ ๋ผ์ฐํธ์ ์ ํ
3. [์ด๋ณด์ 1๋จ๊ณ] ํฌ๋ก์๋ ๋ฐ ์ต์ ๋์ ์์
Fastify์ ๊ณต์ ๋นํธ์ธ ๋ก๊ฑฐ์ธ Pino๋ฅผ ํ์ฑํํ๊ณ , ํ์ ์คํฌ๋ฆฝํธ๋ก ๊ธฐ๋ณธ GET/POST ์๋ฒ๋ฅผ ์์ฑํฉ๋๋ค.
๐ src/server.ts (์ต์ ์คํ ๊ฐ๋ฅํ ์ ์ฒด ์ฝ๋)
// src/server.ts
import Fastify, { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
// 1. Fastify ์ธ์คํด์ค ์์ฑ (Pino ๋ก๊ฑฐ ํ์ฑํ)
const app: FastifyInstance = Fastify({
logger: {
level: 'info',
transport: {
target: 'pino-pretty', // ๊ฐ๋
์ฑ ๋์ ์ปฌ๋ฌ ์ฝ์ ์ถ๋ ฅ (๊ฐ๋ฐ์ฉ)
options: {
colorize: true,
translateTime: 'HH:MM:ss Z',
ignore: 'pid,hostname',
},
},
},
});
// 2. ํฌ์ค์ฒดํฌ ๋ผ์ฐํธ ๋ฑ๋ก
app.get('/health', async (request: FastifyRequest, reply: FastifyReply) => {
return {
status: 'ok',
uptime: process.uptime(),
timestamp: new Date().toISOString(),
};
});
// 3. ๊ฐ๋จํ ํ์ ๋ฉ์์ง ๋ผ์ฐํธ (Query ํ๋ผ๋ฏธํฐ ์ ๋ฌ)
app.get('/hello', async (request: FastifyRequest<{ Querystring: { name?: string } }>, reply: FastifyReply) => {
const name = request.query.name || '๋ฐฉ๋ฌธ์';
return {
message: `์๋
ํ์ธ์, ${name}๋! Fastify ์ธ๊ณ์ ์ค์ ๊ฒ์ ํ์ํฉ๋๋ค. ๐`,
};
});
// 4. ์๋ฒ ์์ ํจ์ (Docker ๋ฐฐํฌ๋ฅผ ๊ณ ๋ คํ์ฌ host: '0.0.0.0' ํ์ ์ง์ )
const start = async () => {
try {
const port = Number(process.env.PORT) || 3000;
const host = '0.0.0.0';
await app.listen({ port, host });
app.log.info(`์๋ฒ๊ฐ http://${host}:${port} ์์ ๋๊ธฐ ์ค์
๋๋ค.`);
} catch (err) {
app.log.error(err);
process.exit(1);
}
};
start();
๐ป ์คํ ๋ฐ cURL ํ ์คํธ
# tsx๋ฅผ ํตํด TypeScript ์ฆ์ ์คํ
npx tsx src/server.ts
# [ํ
์คํธ 1] ํฌ์ค์ฒดํฌ ํธ์ถ
curl -i http://localhost:3000/health
# [์์ ์ถ๋ ฅ 1]
# HTTP/1.1 200 OK
# content-type: application/json; charset=utf-8
# {"status":"ok","uptime":1.24,"timestamp":"2026-10-31T03:15:00.000Z"}
# [ํ
์คํธ 2] ์ฟผ๋ฆฌ์คํธ๋ง ์ ๋ฌ ํธ์ถ
curl -i "http://localhost:3000/hello?name=LuckyTech"
# [์์ ์ถ๋ ฅ 2]
# HTTP/1.1 200 OK
# {"message":"์๋
ํ์ธ์, LuckyTech๋! Fastify ์ธ๊ณ์ ์ค์ ๊ฒ์ ํ์ํฉ๋๋ค. ๐"}
4. [2๋จ๊ณ] ํต์ฌ ๊ธฐ๋ฅ: TypeProvider & ํ์ ์์ ๋ผ์ฐํ
๊ธฐ์กด Node.js ํ๋ ์์ํฌ(Express ๋ฑ)๋ TypeScript๋ฅผ ์ฐ๋๋ผ๋ req.body as MyType์ฒ๋ผ ๋ถ์์ ํ ๋จ์ธ(Type Assertion)์ ์ฌ์ฉํด์ผ ํ์ต๋๋ค.
Fastify๋ TypeProvider๋ฅผ ๋์
ํ์ฌ ์คํค๋ง(๋ฐํ์ ๊ฒ์ฆ)๋ฅผ ํ ๋ฒ๋ง ์์ฑํ๋ฉด ์์ฒญ ๊ฐ์ฒด(req.body, req.params, req.query)์ ์๋ต ๋ฐํ ํ์
์ด ์๋์ผ๋ก 100% ์ถ๋ก ๋ฉ๋๋ค.
๐ ์ต์
A: @sinclair/typebox ๊ธฐ๋ฐ TypeProvider (๊ณต์ ๊ฐ๋ ฅ ์ถ์ฒ)
TypeBox๋ ํ์ค JSON Schema๋ฅผ ์์ฑํ๋ ๊ฐ์ฅ ๋น ๋ฅด๊ณ ๊ฐ๋ฒผ์ด TypeScript ์คํค๋ง ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ ๋๋ค. Fastify์ Ajv ๋ฐ fast-json-stringify์ 100% ๋ค์ดํฐ๋ธ ํธํ๋ฉ๋๋ค.
๐ src/typebox-server.ts (TypeBox ์์ ๊ตฌ๋ ์์ )
// src/typebox-server.ts
import Fastify from 'fastify';
import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox';
import { Type, Static } from '@sinclair/typebox';
// 1. withTypeProvider๋ฅผ ์ฐ๊ฒฐํ์ฌ ์ธ์คํด์ค ์์ฑ
const app = Fastify({ logger: true }).withTypeProvider<TypeBoxTypeProvider>();
// 2. TypeBox ์คํค๋ง ์ ์ (๋ฐํ์ ์ ํจ์ฑ ๊ฒ์ฆ + ์ ์ ํ์
)
const CreateUserBodySchema = Type.Object({
username: Type.String({ minLength: 3, maxLength: 20 }),
email: Type.String({ format: 'email' }),
age: Type.Integer({ minimum: 1, maximum: 120 }),
roles: Type.Array(Type.Union([Type.Literal('admin'), Type.Literal('user')]), { default: ['user'] }),
});
const UserResponseSchema = Type.Object({
id: Type.String({ format: 'uuid' }),
username: Type.String(),
email: Type.String(),
age: Type.Integer(),
roles: Type.Array(Type.String()),
createdAt: Type.String(),
});
const ErrorResponseSchema = Type.Object({
statusCode: Type.Integer(),
error: Type.String(),
message: Type.String(),
});
// ์ ์ ํ์
์ถ์ถ (ํ์ ์ ๋น์ฆ๋์ค ์๋น์ค ๊ณ์ธต์์ ์ฌ์ฉ)
export type CreateUserBody = Static<typeof CreateUserBodySchema>;
export type UserResponse = Static<typeof UserResponseSchema>;
// 3. ํ์
์์ ๋ผ์ฐํธ ์ ์ธ
app.post(
'/api/users',
{
schema: {
tags: ['Users'],
summary: '์ ๊ท ์ฌ์ฉ์ ๋ฑ๋ก',
body: CreateUserBodySchema,
response: {
201: UserResponseSchema,
400: ErrorResponseSchema,
},
},
},
async (request, reply) => {
// ๐ request.body๋ ์ด์ CreateUserBody ํ์
์ผ๋ก ์๋ฒฝํ๊ฒ ์๋ ์ถ๋ก ๋ฉ๋๋ค!
// ๋ณ๋์ `as` ์บ์คํ
์ด๋ ๊ฒ์ฆ ์ฝ๋ ๋ถํ์!
const { username, email, age, roles } = request.body;
const newUser: UserResponse = {
id: '123e4567-e89b-12d3-a456-426614174000',
username,
email,
age,
roles,
createdAt: new Date().toISOString(),
};
// 201 ์๋ต ์ฝ๋๋ก ์ ์ก (UserResponseSchema์ ์๋ ํ๋๋ ์๋์ผ๋ก ํํฐ๋ง ๋๋ฝ๋จ)
return reply.status(201).send(newUser);
}
);
// 4. ๊ฒฝ๋ก ํ๋ผ๋ฏธํฐ(Params) ๋ฐ ์ฟผ๋ฆฌ(Querystring) ๊ฒ์ฆ ์์
const GetUserParamsSchema = Type.Object({
userId: Type.String({ minLength: 1 }),
});
const GetUserQuerySchema = Type.Object({
details: Type.Optional(Type.Boolean()),
});
app.get(
'/api/users/:userId',
{
schema: {
params: GetUserParamsSchema,
querystring: GetUserQuerySchema,
response: {
200: UserResponseSchema,
},
},
},
async (request, reply) => {
const { userId } = request.params; // string ํ์
์๋ ์ถ๋ก
const { details } = request.query; // boolean | undefined ํ์
์๋ ์ถ๋ก
return {
id: userId,
username: 'lucky_developer',
email: 'dev@luckytech.world',
age: 28,
roles: ['admin'],
createdAt: new Date().toISOString(),
};
}
);
const start = async () => {
await app.listen({ port: 3000, host: '0.0.0.0' });
};
start();
๐ป cURL์ ํตํ ์ ํจ์ฑ ๊ฒ์ฆ ํ ์คํธ
# 1. ์ ์ ๋ฑ๋ก ์์ฒญ (201 Created)
curl -X POST http://localhost:3000/api/users \
-H "Content-Type: application/json" \
-d '{"username": "fastify_king", "email": "king@test.com", "age": 25, "roles": ["admin"]}'
# [์ถ๋ ฅ ๊ฒฐ๊ณผ]
# {"id":"123e4567-e89b-12d3-a456-426614174000","username":"fastify_king","email":"king@test.com","age":25,"roles":["admin"],"createdAt":"2026-10-31T03:20:00.000Z"}
# 2. ๋น์ ์ ์์ฒญ (์ด๋ฉ์ผ ํฌ๋งท ์ค๋ฅ ๋ฐ ๋์ด 1 ๋ฏธ๋ง -> Ajv 400 ์๋ ์ฐจ๋จ)
curl -X POST http://localhost:3000/api/users \
-H "Content-Type: application/json" \
-d '{"username": "ab", "email": "invalid-email", "age": -5}'
# [์ถ๋ ฅ ๊ฒฐ๊ณผ (Fastify ํ์ค ์๋ฌ ํ์)]
# {
# "statusCode": 400,
# "code": "FST_ERR_VALIDATION",
# "error": "Bad Request",
# "message": "body/username must NOT have fewer than 3 characters, body/email must match format \"email\", body/age must be >= 1"
# }
๐ก ์ต์
B: Zod๋ฅผ ์ ํธํ๋ ๊ฒฝ์ฐ (@fastify/type-provider-zod)
ํ ๋ด์์ ์ด๋ฏธ Zod๋ฅผ ํ์ค์ผ๋ก ์ฌ์ฉ ์ค์ธ ๊ฒฝ์ฐ, ๋ค์๊ณผ ๊ฐ์ด ์ปดํ์ผ๋ฌ ์ค์ ์ ๋งคํํ์ฌ ๋์ผํ ํ์ ์์ ์ฑ์ ํ๋ณดํ ์ ์์ต๋๋ค:
pnpm add @fastify/type-provider-zod zod
// zod-setup.ts
import Fastify from 'fastify';
import { serializerCompiler, validatorCompiler, ZodTypeProvider } from '@fastify/type-provider-zod';
import { z } from 'zod';
const app = Fastify()
.setValidatorCompiler(validatorCompiler)
.setSerializerCompiler(serializerCompiler)
.withTypeProvider<ZodTypeProvider>();
app.post(
'/api/login',
{
schema: {
body: z.object({
account: z.string().min(4),
password: z.string().min(8),
}),
response: {
200: z.object({
token: z.string(),
}),
},
},
},
async (request, reply) => {
const { account, password } = request.body; // ์๋ ํ์
์ถ๋ก
return { token: `jwt-token-for-${account}` };
}
);
5. [3๋จ๊ณ] ์ค๋ฌด ์์ฉ ํจํด: ํ๋ฌ๊ทธ์ธ ๋ชจ๋ํ, Swagger & ๋ณด์
Fastify ์ ํ๋ฆฌ์ผ์ด์
์ ํ๋ก๋์
๊ตฌ์กฐ๋ ํ๋ฌ๊ทธ์ธ ์บก์ํ๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ์์ฑ๋ฉ๋๋ค.
๋น์ฆ๋์ค ๋ผ์ฐํธ, ๊ณตํต ์ ํธ๋ฆฌํฐ(Swagger, CORS), ์ธ์ฆ ๋ฏธ๋ค์จ์ด๋ฅผ ์๋ฒฝํ๊ฒ ๋ถ๋ฆฌํ๋ ์ค๋ฌด ์ํคํ
์ฒ์
๋๋ค.
fastify-api-server/
โโโ src/
โ โโโ plugins/
โ โ โโโ swagger.ts # Swagger / OpenAPI ๋ฌธ์ํ ํ๋ฌ๊ทธ์ธ
โ โ โโโ security.ts # CORS, Helmet, Sensible ํ๋ฌ๊ทธ์ธ
โ โโโ routes/
โ โ โโโ items.ts # ์์ดํ
๊ด๋ จ CRUD ๋น์ฆ๋์ค ๋ผ์ฐํธ
โ โโโ app.ts # ํ๋ฌ๊ทธ์ธ ๊ฒฐํฉ ๋ฐ ์๋ฒ ์ธ์คํด์ค ์ํธ๋ฆฌ
โโโ tsconfig.json
๐ 1) Swagger/OpenAPI ์๋ ๋ฌธ์ํ ํ๋ฌ๊ทธ์ธ (src/plugins/swagger.ts)
// src/plugins/swagger.ts
import fp from 'fastify-plugin';
import swagger from '@fastify/swagger';
import swaggerUi from '@fastify/swagger-ui';
export default fp(async (fastify) => {
// 1. OpenAPI ์คํ ์ ๋๋ ์ดํฐ ๋ฑ๋ก
await fastify.register(swagger, {
openapi: {
info: {
title: 'LuckyTechWorld Fastify Core API',
description: 'TypeProvider ๊ธฐ๋ฐ์ ์ด๊ณ ์ ํ์
์ธ์ดํ RESTful API ๋ช
์ธ์',
version: '1.0.0',
},
servers: [
{
url: 'http://localhost:3000',
description: '๋ก์ปฌ ๊ฐ๋ฐ ์๋ฒ',
},
],
tags: [
{ name: 'Items', description: '์์ดํ
๊ด๋ฆฌ API' },
{ name: 'Health', description: '์์คํ
์ํ ์ ๊ฒ' },
],
},
});
// 2. Swagger UI ์น ์ฝ์ ๋ฑ๋ก (/docs)
await fastify.register(swaggerUi, {
routePrefix: '/docs',
uiConfig: {
docExpansion: 'list',
deepLinking: false,
},
});
fastify.log.info('Swagger UI๊ฐ /docs ์๋ํฌ์ธํธ์ ์ฑ๊ณต์ ์ผ๋ก ๋ง์ดํธ๋์์ต๋๋ค.');
});
๐ 2) ๋ณด์ ๋ฐ ์ ์ญ ํ๋ฌ๊ทธ์ธ (src/plugins/security.ts)
// src/plugins/security.ts
import fp from 'fastify-plugin';
import helmet from '@fastify/helmet';
import cors from '@fastify/cors';
import sensible from '@fastify/sensible';
export default fp(async (fastify) => {
// 1. HTTP ๋ณด์ ํค๋ ์๋ ์ฃผ์
await fastify.register(helmet, {
contentSecurityPolicy: false, // Swagger UI ์ถฉ๋ ๋ฐฉ์ง์ฉ ์ค์
});
// 2. Cross-Origin Resource Sharing (CORS) ๊ตฌ์ฑ
await fastify.register(cors, {
origin: (origin, cb) => {
// ๋ก์ปฌ ๊ฐ๋ฐ ๋ฐ ์ ๋ขฐํ ์ ์๋ ๋๋ฉ์ธ ํ์ฉ
cb(null, true);
},
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
credentials: true,
});
// 3. fastify-sensible: reply.notFound(), reply.badRequest() ๋ฑ HTTP ์ค๋ฅ ํฌํผ ์ ๊ณต
await fastify.register(sensible);
});
๐ 3) ๋น์ฆ๋์ค ๋ผ์ฐํธ ๋ชจ๋ํ (src/routes/items.ts)
// src/routes/items.ts
import { FastifyPluginAsync } from 'fastify';
import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox';
import { Type } from '@sinclair/typebox';
// ๋ฉ๋ชจ๋ฆฌ DB ๋ชจ์ ๋ฐ์ดํฐ
interface Item {
id: number;
name: string;
price: number;
stock: number;
}
const itemsDb: Item[] = [
{ id: 1, name: '๋งฅ๋ถ ํ๋ก M3', price: 2900000, stock: 15 },
{ id: 2, name: '๊ธฐ๊ณ์ ํค๋ณด๋', price: 180000, stock: 50 },
];
const ItemSchema = Type.Object({
id: Type.Integer(),
name: Type.String(),
price: Type.Number(),
stock: Type.Integer(),
});
const CreateItemBody = Type.Object({
name: Type.String({ minLength: 2 }),
price: Type.Number({ minimum: 100 }),
stock: Type.Integer({ minimum: 0, default: 0 }),
});
const itemRoutes: FastifyPluginAsync = async (fastify) => {
const app = fastify.withTypeProvider<TypeBoxTypeProvider>();
// [๋ชฉ๋ก ์กฐํ] GET /api/v1/items
app.get(
'/',
{
schema: {
tags: ['Items'],
summary: '์์ดํ
์ ์ฒด ๋ชฉ๋ก ์กฐํ',
response: {
200: Type.Array(ItemSchema),
},
},
},
async (request, reply) => {
return itemsDb;
}
);
// [์ ๊ท ์์ฑ] POST /api/v1/items
app.post(
'/',
{
schema: {
tags: ['Items'],
summary: '์ ์์ดํ
์์ฑ',
body: CreateItemBody,
response: {
201: ItemSchema,
},
},
},
async (request, reply) => {
const { name, price, stock } = request.body;
const newItem: Item = {
id: itemsDb.length + 1,
name,
price,
stock,
};
itemsDb.push(newItem);
return reply.status(201).send(newItem);
}
);
// [๋จ๊ฑด ์กฐํ] GET /api/v1/items/:id
app.get(
'/:id',
{
schema: {
tags: ['Items'],
summary: '์์ดํ
์์ธ ์กฐํ',
params: Type.Object({ id: Type.Integer() }),
response: {
200: ItemSchema,
404: Type.Object({ statusCode: Type.Integer(), error: Type.String(), message: Type.String() }),
},
},
},
async (request, reply) => {
const { id } = request.params;
const found = itemsDb.find((item) => item.id === id);
if (!found) {
// fastify-sensible์ ํธ์ ๋ฉ์๋ ์ฌ์ฉ
return reply.notFound(`ID๊ฐ ${id}์ธ ์์ดํ
์ ์ฐพ์ ์ ์์ต๋๋ค.`);
}
return found;
}
);
};
export default itemRoutes;
๐ 4) ๋ฉ์ธ ์ฑ ๊ตฌ์ฑ ๋ฐ Graceful Shutdown (src/app.ts)
// src/app.ts
import Fastify from 'fastify';
import swaggerPlugin from './plugins/swagger.js';
import securityPlugin from './plugins/security.js';
import itemRoutes from './routes/items.js';
export const buildApp = async () => {
const app = Fastify({
logger: {
level: process.env.LOG_LEVEL || 'info',
},
});
// 1. ๊ณตํต ํ๋ฌ๊ทธ์ธ ๋ฑ๋ก
await app.register(securityPlugin);
await app.register(swaggerPlugin);
// 2. ๋น์ฆ๋์ค ๋ผ์ฐํธ ๋ฑ๋ก (URL Prefix ์ ์ฉ)
await app.register(itemRoutes, { prefix: '/api/v1/items' });
// 3. ์ ์ญ ์๋ฌ ํธ๋ค๋ฌ ์ปค์คํฐ๋ง์ด์ง
app.setErrorHandler((error, request, reply) => {
app.log.error(error);
// Ajv ์คํค๋ง ๊ฒ์ฆ ์ค๋ฅ ์ฒ๋ฆฌ
if (error.validation) {
return reply.status(400).send({
statusCode: 400,
error: 'Bad Request',
message: error.message,
details: error.validation,
});
}
// ์ผ๋ฐ 500 ์ธํฐ๋ ์๋ฒ ์๋ฌ
return reply.status(error.statusCode || 500).send({
statusCode: error.statusCode || 500,
error: error.name || 'Internal Server Error',
message: error.message || '์๋ฒ ๋ด๋ถ ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค.',
});
});
return app;
};
// ์ง์ ์คํ ์ ๊ตฌ๋๋ถ
const start = async () => {
const app = await buildApp();
const port = Number(process.env.PORT) || 3000;
const host = '0.0.0.0';
// Graceful Shutdown (SIGINT, SIGTERM)
const signals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM'];
for (const signal of signals) {
process.on(signal, async () => {
app.log.info(`[${signal}] ์ ํธ๋ฅผ ์์ ํ์ต๋๋ค. ์๋ฒ๋ฅผ ์์ ํ๊ฒ ์ข
๋ฃํฉ๋๋ค...`);
try {
await app.close();
app.log.info('๋ชจ๋ ํ์ฑ ์ปค๋ฅ์
์ด ์ข
๋ฃ๋์์ต๋๋ค. ํ๋ก์ธ์ค๋ฅผ ์ ์ ์ข
๋ฃํฉ๋๋ค.');
process.exit(0);
} catch (err) {
app.log.error(err, '์๋ฒ ์ข
๋ฃ ์ค ์ค๋ฅ ๋ฐ์');
process.exit(1);
}
});
}
try {
await app.listen({ port, host });
console.log(`\n======================================================`);
console.log(`๐ Fastify ์๋ฒ ์ค๋น ์๋ฃ!`);
console.log(`๐ก ์๋ํฌ์ธํธ: http://localhost:${port}/api/v1/items`);
console.log(`๐ Swagger UI: http://localhost:${port}/docs`);
console.log(`======================================================\n`);
} catch (err) {
app.log.error(err);
process.exit(1);
}
};
start();
6. ๋ฐ์ฝ๋ ์ดํฐ & ํ (Hooks)์ ์ด์ฉํ ์ธ์ฆ ๋ฏธ๋ค์จ์ด ํจํด
Fastify์์๋ Express ๋ฏธ๋ค์จ์ด ๋์ **๋ฐ์ฝ๋ ์ดํฐ(decorate)**์ preHandler ์๋ช
์ฃผ๊ธฐ ํ
์ ์ฌ์ฉํ์ฌ ์ฌ์ฉ์ ์ธ์ฆ ๋ฐ ๊ถํ์ ๊ฒ์ฆํฉ๋๋ค.
// src/plugins/auth.ts
import fp from 'fastify-plugin';
import { FastifyRequest, FastifyReply } from 'fastify';
// 1. Fastify ์ธ์คํด์ค ๋ฐ Request ํ์
ํ์ฅ (TypeScript ์ธํฐํ์ด์ค ๋ณํฉ)
declare module 'fastify' {
interface FastifyInstance {
authenticate: (request: FastifyRequest, reply: FastifyReply) => Promise<void>;
}
interface FastifyRequest {
user?: {
id: string;
role: 'admin' | 'user';
};
}
}
export default fp(async (fastify) => {
// 2. authenticate ๋ฐ์ฝ๋ ์ดํฐ ํจ์ ๋ฑ๋ก
fastify.decorate('authenticate', async (request: FastifyRequest, reply: FastifyReply) => {
const authHeader = request.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return reply.status(401).send({
statusCode: 401,
error: 'Unauthorized',
message: '์ ํจํ Bearer ์ธ์ฆ ํ ํฐ์ด ๋๋ฝ๋์์ต๋๋ค.',
});
}
const token = authHeader.substring(7);
// ์ค์ ํ๊ฒฝ์์๋ jwt.verify() ๋ฑ์ ์ํ
if (token !== 'secret-admin-token') {
return reply.status(403).send({
statusCode: 403,
error: 'Forbidden',
message: '์ ๊ทผ ๊ถํ์ด ์๋ ํ ํฐ์
๋๋ค.',
});
}
// ๊ฒ์ฆ๋ ์ฌ์ฉ์ ์ ๋ณด๋ฅผ request ๊ฐ์ฒด์ ์ฃผ์
request.user = { id: 'usr_admin_001', role: 'admin' };
});
});
๐ ๋ผ์ฐํธ์ ์ธ์ฆ ๊ฐ๋ ์ ์ฉ
// ๋ผ์ฐํธ ์ ์ ์ preHandler์ fastify.authenticate ์ฐ๊ฒฐ
app.delete(
'/api/v1/items/:id',
{
preHandler: [fastify.authenticate], // ์ธ์ฆ ๊ฐ๋ ํต๊ณผ ํ์๋ง ํธ๋ค๋ฌ ์คํ
schema: {
tags: ['Items'],
summary: '์์ดํ
์ญ์ (๊ด๋ฆฌ์ ์ ์ฉ)',
params: Type.Object({ id: Type.Integer() }),
},
},
async (request, reply) => {
const { id } = request.params;
const currentUser = request.user!; // ์ธ์ฆ ๊ฐ๋๋ฅผ ํต๊ณผํ์ผ๋ฏ๋ก ์์ ํ๊ฒ ์ ๊ทผ ๊ฐ๋ฅ
return {
message: `์์ดํ
${id}๋ฒ์ด ๊ด๋ฆฌ์(${currentUser.id})์ ์ํด ์ ์ ์ญ์ ๋์์ต๋๋ค.`,
};
}
);
7. ์ค๋ฌด ์ฃผ์์ฌํญ & ํ๋ก๋์ ์ฒดํฌ๋ฆฌ์คํธ
โ ๏ธ 1. ํ๋ฌ๊ทธ์ธ ์บก์ํ ํจ์ (fastify-plugin ๋ฏธ์ฌ์ฉ ์ค์)
- ์ฆ์: ํ๋ฌ๊ทธ์ธ ํ์ผ ์์์
fastify.decorate('db', dbClient)๋ฅผ ์คํํ๋๋ฐ, ๋ค๋ฅธ ๋ผ์ฐํธ ํ์ผ์์fastify.db๊ฐundefined๋ก ์กฐํ๋จ. - ์์ธ: Fastify๋ ๊ธฐ๋ณธ์ ์ผ๋ก
app.register()๋ก ๋ฑ๋ก๋ ํ๋ฌ๊ทธ์ธ์ ์๋ก์ด ์์ ์ค์ฝํ๋ก ์บก์ํํฉ๋๋ค. - ํด๊ฒฐ์ฑ
: ๋ฃจํธ ์ค์ฝํ ์ ์ฒด์์ ๊ณต์ ํด์ผ ํ๋ ๋ฐ์ฝ๋ ์ดํฐ, ์ ํธ๋ฆฌํฐ, DB ์ปค๋ฅ์
ํ ํ๋ฌ๊ทธ์ธ์ ๋ฐ๋์ **
fastify-plugin(fp)**์ผ๋ก ๋ํํ์ฌ ๋ด๋ณด๋ด์ผ ํฉ๋๋ค.
import fp from 'fastify-plugin';
export default fp(async (fastify) => {
fastify.decorate('db', new DatabasePool());
});
โ ๏ธ 2. async ํจ์์์ return reply.send() ์ค๋ณต ํธ์ถ ๊ธ์ง
- ์ฆ์: ์ฝ์์
FST_ERR_REP_ALREADY_SENT: Response was already sent์ค๋ฅ๊ฐ ๋ฐ์ํจ. - ์์ธ:
async๋ผ์ฐํธ ํธ๋ค๋ฌ์์ ๊ฐ์returnํ๋ฉด Fastify๊ฐ ํด๋น ๋ฐํ๊ฐ์ ์๋์ผ๋ก ์๋ต์ผ๋ก ์ ์กํฉ๋๋ค. ๋ง์ฝreturn reply.send(data)๋ฅผ ํธ์ถํ๋ฉดreply.send()๋ก ํ ๋ฒ,return์ผ๋ก ๋ ํ ๋ฒ ์๋ต์ ์๋ํ๊ฒ ๋ฉ๋๋ค. - ๊ท์น:
asyncํจ์ ๋ด์์๋ ์์ ๊ฐ์ฒด๋ฅผ ๋ฐ๋กreturn dataํ๊ฑฐ๋,- ์ํ ์ฝ๋๋ฅผ ์ปค์คํ
ํ ๋๋
return reply.status(201).send(data)ํํ๋ก ํธ์ถํ์ญ์์ค.
โ ๏ธ 3. Docker ๋ฐฐํฌ ์ host: '0.0.0.0' ๋ฐ์ธ๋ฉ ํ์
- ์ฆ์: ๋ก์ปฌ ๋จธ์ ์์๋ ์ ์ ์๋์ง๋ง, Docker ์ปจํ
์ด๋๋ Kubernetes Pod์ ๋ฐฐํฌํ๋ฉด ์ธ์ธก์์
Connection Refused๊ฐ ๋ฐ์ํจ. - ์์ธ: Fastify์ ๊ธฐ๋ณธ ๋ฆฌ์จ ์ฃผ์๋
127.0.0.1(localhost)์ ๋๋ค. ์ปจํ ์ด๋ ๋ด๋ถ์ localhost๋ ์ธ๋ถ ํฌํธ ํฌ์๋ฉ์ ์์ ํ์ง ๋ชปํฉ๋๋ค. - ํด๊ฒฐ์ฑ
:
await app.listen({ port: 3000, host: '0.0.0.0' });
โ ๏ธ 4. fast-json-stringify ์ง๋ ฌํ์ ์ํ ํ๋ ๋๋ฝ ์ฃผ์
- ๋์ ์๋ฆฌ: Fastify๋
schema.response[200]์ ๋ช ์๋ ์คํค๋ง๋ฅผ ๋ฐํ์ผ๋ก C ์ธ์ด ์์ค์ ๊ณ ์ ์ง๋ ฌํ ํจ์๋ฅผ ๋ฐํ์์ ๋์ ์ผ๋ก ์ปดํ์ผ(JIT)ํฉ๋๋ค. - ์ฃผ์์ : ํธ๋ค๋ฌ์์ ๋ฐํํ ๊ฐ์ฒด์ ์คํค๋ง์ ์ ์๋์ง ์์ ์ถ๊ฐ ์์ฑ(
extraProperty)์ด ํฌํจ๋์ด ์๋๋ผ๋, ์คํค๋ง์ ์ ํ์์ง ์์ ํ๋๋ ์ต์ข JSON ์๋ต์์ ์๋์ผ๋ก ํํฐ๋ง๋์ด ๋๋ฝ๋ฉ๋๋ค. - ์ฅ์ : ์๋์น ์์ ํจ์ค์๋ ํด์, ๋ด๋ถ ๋๋ฒ๊ทธ ํ๋๊ทธ ๋ฑ ๋ฏผ๊ฐ ๋ฐ์ดํฐ๊ฐ ์ธ๋ถ๋ก ์ ์ถ๋๋ ์ฌ๊ณ ๋ฅผ ์์ฒ ๋ฐฉ์งํฉ๋๋ค.
- ํ: ์๋ต์ ํน์ ํ๋๊ฐ ๋๋ฝ๋๋ค๋ฉด
schema.response์ ์์ ํด๋น ํ๋๊ฐ ๋๋ฝ๋์๋์ง ํ์ธํ์ญ์์ค.
โ ๏ธ 5. ํ๋ก๋์ Pino ๋ก๊ฑฐ ์ต์ ํ
- ๋ก์ปฌ ๊ฐ๋ฐ ํ๊ฒฝ์์๋
pino-pretty๊ฐ ํธ๋ฆฌํ์ง๋ง, CPU ๋ถํ๊ฐ ๋์ผ๋ฏ๋ก ํ๋ก๋์ ์์๋ ๋ฐ๋์ ๊ธฐ๋ณธ Raw JSON ์คํธ๋ฆผ์ ์ฌ์ฉํด์ผ ํฉ๋๋ค. - ์ด๋น ์๋ง ๊ฑด ์ด์์ ํธ๋ํฝ์ด ๋ฐ์ํ๋ ํ๊ฒฝ์์๋
pino.destination({ sync: false })๋ฅผ ์ ์ฉํ์ฌ ๋น๋๊ธฐ ๋ฒํผ๋ง์ ํ์ฑํํ์ญ์์ค.
8. ์์ฃผ ์ฐ์ด๋ Fastify ํต์ฌ CLI & ์์กด์ฑ ์์ฝ
| ํจํค์ง๋ช | ๋ชฉ์ ๋ฐ ํน์ง | ์ค์น ๋ช ๋ น์ด |
|---|---|---|
fastify | Fastify ํต์ฌ ์น ํ๋ ์์ํฌ ์์ง | pnpm add fastify |
@fastify/type-provider-typebox | TypeBox ๊ธฐ๋ฐ ์ปดํ์ผ ํ์ ํ์ ์ถ๋ก ํ๋ฌ๊ทธ์ธ | pnpm add @fastify/type-provider-typebox @sinclair/typebox |
@fastify/type-provider-zod | Zod ์คํค๋ง ๊ฒ์ฆ๊ธฐ ๋ฐ ์๋ฆฌ์ผ๋ผ์ด์ ๊ณต๊ธ์ | pnpm add @fastify/type-provider-zod zod |
fastify-plugin | ํ๋ฌ๊ทธ์ธ ์บก์ํ๋ฅผ ํด์ ํ๊ณ ์ ์ญ ์ค์ฝํ์ ์ฃผ์
(fp) | pnpm add fastify-plugin |
@fastify/swagger | OpenAPI 3.0 / Swagger ์คํ ์๋ ์์ฑ | pnpm add @fastify/swagger |
@fastify/swagger-ui | ๋ํํ Swagger ์น UI (/docs) ๋์๋ณด๋ | pnpm add @fastify/swagger-ui |
@fastify/cors | Cross-Origin ๋ฆฌ์์ค ๊ณต์ ํค๋ ์ค์ | pnpm add @fastify/cors |
@fastify/helmet | 15๊ฐ์ง ์ด์์ ํ์ค ๋ณด์ HTTP ์๋ต ํค๋ ์๋ ์ ์ฉ | pnpm add @fastify/helmet |
@fastify/sensible | reply.notFound(), reply.badRequest() ๋ฑ HTTP ํฌํผ | pnpm add @fastify/sensible |
@fastify/rate-limit | IP ๋ฐ ํด๋ผ์ด์ธํธ๋ณ API ํธ์ถ ์๋ ์ ํ ๊ฐ๋ | pnpm add @fastify/rate-limit |
@fastify/jwt | ์ด๊ณ ์ JSON Web Token(JWT) ์๋ช ๋ฐ ๊ฒ์ฆ | pnpm add @fastify/jwt |
fastify-cli | Fastify ๊ณต์ ํ๋ก์ ํธ ์ค์บํด๋ฉ ๋ฐ ์คํ CLI | npm install -g fastify-cli |
์๊ฒฌ ๋ฐ ์ง๋ฌธ
0์์ง ๋ฑ๋ก๋ ์๊ฒฌ์ด ์์ต๋๋ค. ์ฒซ ๋ฒ์งธ ๋๊ธ์ ๋จ๊ฒจ๋ณด์ธ์!
๋๊ธ ์์
๋๊ธ ์ญ์