Pembatasan Laju dan Penanganan Error API
Lindungi pengendali rute Next.js dengan pembatasan laju, lalu kembalikan respons error yang konsisten dan terstruktur baik dengan kode status HTTP yang tepat.
Pembatasan Laju dan Penanganan Error API adalah pelajaran Next.js 15 Fullstack Web Apps gratis di CoddyKit. Ini adalah pelajaran 4 dari 4. Kamu bisa membaca pelajaran lengkapnya di bawah secara gratis — lalu praktikkan langsung di browser dengan editor kode bawaan dan tutor AI 24/7. Ini adalah bagian dari jalur belajar Next.js 15 Fullstack Web Apps, dan progresmu tersinkronisasi di web dan aplikasi CoddyKit. Kursus Next.js 15 Fullstack Web Apps mencakup 4 pelajaran total.
Bagian dari pelajaran ini belum diterjemahkan dan ditampilkan dalam bahasa Inggris.
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.
Belajar TypeScript dengan tutor AI — gratis
Tulis dan jalankan kode asli di browser kamu, dapatkan bantuan instan dari tutor AI 24/7, dan lanjutkan di mana kamu tinggalkan di web atau aplikasi.
- Kursus
- 12
- Pelajaran
- 48
Pertanyaan yang Sering Diajukan
Apakah pelajaran “Pembatasan Laju dan Penanganan Error API” gratis?
Ya — teks lengkap “Pembatasan Laju dan Penanganan Error API” gratis dibaca di sini di web. Untuk praktiknya secara interaktif (editor kode bawaan dan tutor AI 24/7) dan buka sisa kursus Next.js 15 Fullstack Web Apps, upgrade ke CoddyKit PRO. Kursus Next.js 15 Fullstack Web Apps mencakup 4 pelajaran total.
Apa yang akan aku pelajari di “Pembatasan Laju dan Penanganan Error API”?
Lindungi pengendali rute Next.js dengan pembatasan laju, lalu kembalikan respons error yang konsisten dan terstruktur baik dengan kode status HTTP yang tepat. Kamu berlatih Next.js 15 Fullstack Web Apps dengan kode praktik yang langsung kamu jalankan di browser, dan tutor AI 24/7 menjawab pertanyaanmu saat kamu mengerjakan pelajaran ini.
Apakah aku perlu pengalaman untuk memulai Next.js 15 Fullstack Web Apps?
Tidak diperlukan pengalaman sebelumnya. Next.js 15 Fullstack Web Apps di CoddyKit dirancang untuk pemula hingga pelajar tingkat lanjut, jadi kamu bisa memulai di sini atau dari awal dan belajar sesuai kecepatan kamu sendiri. Ini adalah pelajaran 4 dari 4.
Berapa lama pelajaran “Pembatasan Laju dan Penanganan Error API” memakan waktu?
Sebagian besar pelajaran CoddyKit memakan waktu sekitar 5–10 menit. Setiap pelajaran ringkas dan interaktif, jadi kamu membuat kemajuan stabil dan melanjutkan dari tempat kamu tinggalkan di web dan aplikasi.
Bisakah aku menulis dan menjalankan kode dalam pelajaran Next.js 15 Fullstack Web Apps ini?
Ya. Setiap pelajaran Next.js 15 Fullstack Web Apps menyertakan editor kode bawaan, jadi kamu menulis dan menjalankan kode nyata langsung di browser dan mendapatkan umpan balik AI instan — tidak diperlukan penyiapan lokal.
Semua pelajaran dalam kursus ini
- Membangun Penangan Rute API
- Validasi Permintaan dan Keamanan
- Mengintegrasikan Layanan Eksternal
- Pembatasan Laju dan Penanganan Error API