İstek Hızı Sınırlama ve API Hatalarını İşleme
Next.js rota işleyicilerinizi istek hızı sınırlamayla koruyun ve doğru HTTP durum kodlarıyla tutarlı, iyi yapılandırılmış hata yanıtları döndürün.
İstek Hızı Sınırlama ve API Hatalarını İşleme, CoddyKit'te ücretsiz bir Next.js 15 Fullstack Web Apps dersidir. Bu, 4 dersinin 4. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Next.js 15 Fullstack Web Apps öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Next.js 15 Fullstack Web Apps kursu toplamda 4 dersten oluşur.
Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.
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.
Sıkça Sorulan Sorular
“İstek Hızı Sınırlama ve API Hatalarını İşleme” dersi ücretsiz mi?
Evet — “İstek Hızı Sınırlama ve API Hatalarını İşleme” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Next.js 15 Fullstack Web Apps kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Next.js 15 Fullstack Web Apps kursu toplamda 4 dersten oluşur.
“İstek Hızı Sınırlama ve API Hatalarını İşleme” dersinde ne öğreneceğim?
Next.js rota işleyicilerinizi istek hızı sınırlamayla koruyun ve doğru HTTP durum kodlarıyla tutarlı, iyi yapılandırılmış hata yanıtları döndürün. Next.js 15 Fullstack Web Apps ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.
Next.js 15 Fullstack Web Apps öğrenmeye başlamak için deneyim gerekli mi?
Önceden deneyim gerekmez. CoddyKit'te Next.js 15 Fullstack Web Apps, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 4. dersidir.
“İstek Hızı Sınırlama ve API Hatalarını İşleme” dersi ne kadar sürer?
Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.
Bu Next.js 15 Fullstack Web Apps dersinde kod yazıp çalıştırabilir miyim?
Evet. Her Next.js 15 Fullstack Web Apps dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.
Bu kursun tüm dersleri
- API Yol İşleyicileri Oluşturma
- İstek Doğrulama ve Güvenlik
- Harici Hizmetleri Entegre Etme
- İstek Hızı Sınırlama ve API Hatalarını İşleme