The withRateLimit helper provides a simpler way to add rate limiting:
Copy
Ask AI
// app/api/users/route.tsimport { Limitly } from '@limitly/limitly-nextjs';const limitly = new Limitly({ apiKey: process.env.LIMITLY_API_KEY!});async function handleGetUsers(request: Request) { // Your API logic here return Response.json({ users: [] });}// Wrap your handler with rate limitingexport const GET = limitly.withRateLimit(handleGetUsers);
// middleware.tsimport { NextResponse } from 'next/server';import type { NextRequest } from 'next/server';import { Limitly } from '@limitly/limitly-nextjs';const limitly = new Limitly({ apiKey: process.env.LIMITLY_API_KEY!});export function middleware(request: NextRequest) { // Only apply to API routes if (request.nextUrl.pathname.startsWith('/api/')) { const apiKey = request.headers.get('authorization')?.replace('Bearer ', ''); if (!apiKey) { return NextResponse.json( { error: 'API Key required' }, { status: 401 } ); } // Note: This is a simplified example // In practice, you'd want to handle the async validation properly return NextResponse.next(); } return NextResponse.next();}export const config = { matcher: '/api/:path*',};