속도 제한과 API 오류 처리
속도 제한으로 Next.js 경로 처리기를 보호하고, 올바른 HTTP 상태 코드와 일관되고 체계적인 오류 응답을 반환합니다.
속도 제한과 API 오류 처리은(는) CoddyKit의 무료 Next.js 15 Fullstack Web Apps 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Next.js 15 Fullstack Web Apps 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Next.js 15 Fullstack Web Apps 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Rate Limit
Public API routes are exposed to abuse: brute-force logins, scraping, and accidental floods. Rate limiting caps how many requests a client may make in a time window, protecting your backend and external service quotas.
Identifying the Client
You need a key to count requests per client. Common choices are the IP address, an API key, or the authenticated user ID. In route handlers, read the IP from headers set by your platform.
export async function GET(req) {
const ip = req.headers.get('x-forwarded-for') ?? 'unknown';
return Response.json({ ip });
}A Fixed-Window Counter
The simplest algorithm counts requests in a fixed time window per key. When the count exceeds the limit, reject further requests until the window resets.
function fixedWindow(store, key, limit, windowMs) {
const now = Date.now();
const entry = store[key] || { count: 0, reset: now + windowMs };
if (now > entry.reset) { entry.count = 0; entry.reset = now + windowMs; }
entry.count++;
store[key] = entry;
return entry.count <= limit;
}Trying the Limiter
Run the fixed-window logic locally to see it allow then block.
function fixedWindow(store, key, limit, windowMs) {
const now = Date.now();
const entry = store[key] || { count: 0, reset: now + windowMs };
if (now > entry.reset) { entry.count = 0; entry.reset = now + windowMs; }
entry.count++;
store[key] = entry;
return entry.count <= limit;
}
const store = {};
for (let i = 0; i < 4; i++) {
console.log(i, fixedWindow(store, 'ip1', 3, 1000));
}In-Memory vs Distributed
An in-memory store resets on every cold start and is not shared across serverless instances. For real deployments use a shared store like Redis (e.g. Upstash) so limits are consistent everywhere.
Returning 429
When a client is over the limit, respond with HTTP 429 Too Many Requests and a Retry-After header telling them when to try again.
export async function POST(req) {
if (!allowed) {
return new Response('Rate limit exceeded', {
status: 429,
headers: { 'Retry-After': '60' },
});
}
return Response.json({ ok: true });
}A Consistent Error Shape
Clients parse errors more easily when every failure has the same JSON shape. Standardize on a small envelope.
function apiError(message, status, code) {
return Response.json(
{ error: { message, code } },
{ status }
);
}Mapping Errors to Status Codes
Choose the status that matches the cause:
400bad input401not authenticated403not authorized404not found429rate limited500server fault
Catching Unexpected Errors
Wrap handler logic in try/catch so an unhandled exception becomes a controlled 500 rather than a leaked stack trace.
export async function GET() {
try {
const data = await loadData();
return Response.json(data);
} catch (e) {
console.error(e);
return Response.json({ error: { message: 'Internal error' } }, { status: 500 });
}
}Reusable Wrapper
Factor the boilerplate into a higher-order function that applies rate limiting and error catching to any handler.
function withGuards(handler) {
return async (req) => {
if (!checkLimit(req)) return apiError('Too many requests', 429);
try { return await handler(req); }
catch { return apiError('Internal error', 500); }
};
}Never Leak Internals
In production, never send raw error messages, stack traces, or SQL details to the client. Log them server-side and return a generic message with a stable error code.
Quick Check
Which HTTP status code and header best signal that a client has exceeded the rate limit?
Recap
You hardened your API routes:
- Identified clients and counted requests with a fixed-window limiter.
- Returned
429withRetry-After, preferring Redis for distributed limits. - Standardized a JSON error envelope and mapped causes to status codes.
- Caught exceptions and avoided leaking internals.
자주 묻는 질문
“속도 제한과 API 오류 처리” 강의는 무료인가요?
네 — “속도 제한과 API 오류 처리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Next.js 15 Fullstack Web Apps 강의 전체를 잠금 해제할 수 있습니다. Next.js 15 Fullstack Web Apps 강의에는 총 4개의 강의가 포함되어 있습니다.
“속도 제한과 API 오류 처리”에서 뭘 배우나요?
속도 제한으로 Next.js 경로 처리기를 보호하고, 올바른 HTTP 상태 코드와 일관되고 체계적인 오류 응답을 반환합니다. 브라우저에서 직접 실행하는 실습 코드로 Next.js 15 Fullstack Web Apps을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Next.js 15 Fullstack Web Apps을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Next.js 15 Fullstack Web Apps은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“속도 제한과 API 오류 처리” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Next.js 15 Fullstack Web Apps 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Next.js 15 Fullstack Web Apps 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- API 경로 처리기 구축
- 요청 유효성 검사와 보안
- 외부 서비스 통합
- 속도 제한과 API 오류 처리