Skip to content

Instantly share code, notes, and snippets.

@victory-sokolov
Created February 4, 2024 15:33
Show Gist options
  • Save victory-sokolov/0da5130b1868b8940a13b513cf428d77 to your computer and use it in GitHub Desktop.
Save victory-sokolov/0da5130b1868b8940a13b513cf428d77 to your computer and use it in GitHub Desktop.
Ratelimit using upstash with nextjs
import { Ratelimit } from '@upstash/ratelimit';
import { Redis } from '@upstash/redis';
import type { NextRequest, NextFetchEvent } from 'next/server';
import { NextResponse } from 'next/server';
type MiddlewareFactory = (middleware: NextMiddleware) => NextMiddleware;
export const withRateLimit: MiddlewareFactory =
next => async (request: NextRequest, _next: NextFetchEvent) => {
const url = process.env.UPSTASH_REDIS_REST_URL!;
const token = process.env.UPSTASH_REDIS_REST_TOKEN!;
const ip = request.ip ?? '127.0.0.1';
const redis = new Redis({
url,
token,
});
const ratelimit = new Ratelimit({
redis,
limiter: Ratelimit.slidingWindow(10, `10 s`), # 10 requests every 10 seconds
});
const { success, limit, reset, remaining } = await ratelimit.limit(ip);
if (!success) {
return NextResponse.json({ message: 'Rate limit exceeded' }, { status: 429 });
}
return next(request, _next);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment