Skip to content

Commit

Permalink
Add ratelimiting for api routes
Browse files Browse the repository at this point in the history
  • Loading branch information
aron committed Dec 8, 2023
1 parent bdc2a1f commit 4a52aae
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { NextRequest, NextResponse } from 'next/server';
import { Ratelimit } from '@upstash/ratelimit';
import { kv } from '@vercel/kv';

const ratelimit = new Ratelimit({
redis: kv,
// 5 requests from the same IP in 10 seconds
limiter: Ratelimit.slidingWindow(5, '10s'),
prefix: "zoo/ratelimit",
timeout: 1000,
});

// Define which routes you want to rate limit
export const config = {
matcher: ['/api/:path*'],
};

export default async function middleware(request: NextRequest) {
if (!process.env.VERCEL_ENV || !process.env.KV_REST_API_URL || !process.env.KV_REST_API_URL) {
console.warn('Skipping ratelimiting middleware');
return NextResponse.next();
}

const ip = request.ip ?? '127.0.0.1';
const { success, limit, remaining, reset } = await ratelimit.limit(ip);
const headers = {
'X-Ratelimit-Hit': String(success),
'X-Ratelimit-Limit': String(limit),
'X-Ratelimit-Remaining': String(remaining),
'X-Ratelimit-Reset': String(reset),
}

return success
? NextResponse.next({headers})
: NextResponse.json({}, { status: 429, headers });
}

0 comments on commit 4a52aae

Please sign in to comment.