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 bb4ceba
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
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.NODE_ENV !== "production" || !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 } = await ratelimit.limit(ip);

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

0 comments on commit bb4ceba

Please sign in to comment.