미들웨어는 Express의 요청-응답 주기 동안 순차적으로 실행되는 함수입니다. 각각 (req, res, next)를 받아 요청과 응답을 검사/수정하거나, 응답을 끝내거나, next()를 호출하여 다음 미들웨어로 제어를 넘길 수 있습니다. 이는 Express 앱이 구조화되는 핵심입니다.
시그니처와 체인
js
app.( {
.();
();
});
핵심 원칙: 체인을 계속하려면 next()를 호출하세요. 이를 잊고(응답도 보내지 않으면) 요청이 영원히 멈춥니다.
Request → [logger] → [auth] → [body parser] → [route handler] → Response
next() next() next() res.send()
Each middleware runs in order; any can short-circuit by sending a response.
// 1. Application-level — runs for all (or path-matched) requests
app.use(express.json()); // built-in: parse JSON bodies
app.use(cors()); // third-party
// 2. Custom — e.g. authentication that can SHORT-CIRCUIT
function requireAuth(req, res, next) {
if (!req.headers.authorization) {
return res.status(401).json({ error: "Unauthorized" }); // STOP — don't call next()
}
req.user = decodeToken(req.headers.authorization); // attach data for later handlers
next(); // authorized → continue
}
// 3. Route-specific
app.get("/profile", requireAuth, (req, res) => res.json(req.user));
미들웨어는 단락(short-circuit)(응답을 보내고 next()를 호출하지 않음, 예: 인증되지 않은 요청 차단)하거나 요청을 보강(이후 핸들러를 위해 req.user 부착)할 수 있습니다.
// special signature with 4 params → Express treats it as an error handler
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ error: "Server error" });
});
// triggered by next(err) or a thrown error; place it LAST
에러 핸들러는 네 개의 매개변수(err가 첫 번째)를 가집니다. next(err)를 호출하여 도달하며, 마지막에 등록해야 합니다.
Middleware runs in the ORDER you register it. Body parser before routes that
read the body; auth before protected routes; error handler last.
미들웨어는 Express(및 유사 프레임워크)의 아키텍처적 근간입니다. 인증, 로깅, 본문 파싱, CORS, 검증, 에러 처리가 모두 미들웨어입니다.
(req, res, next) 계약(특히 next()를 호출하거나 응답을 보내야 한다는 점), 미들웨어가 요청을 단락하거나 보강하는 방법, 인자 4개의 에러 핸들러, 그리고 순서가 중요하다는 점을 이해하는 것은 모든 Express 애플리케이션을 구축하고 구조화하고 디버깅하는 데 필수적입니다.