OSS Ratelimit

Nextjs Integration with Oss Ratelimit Redis

A step-by-step guide on how to seamlessly integrate oss-ratelimit using Redis as a storage backend within your Next.js application, including middleware examples.

Next.js Integration

oss-ratelimit works well with Next.js. The key is obtaining a reliable identifier (usually the client's IP address) and applying the limit in the appropriate place (API Routes, Middleware, Route Handlers).

1. Getting the Client IP Address

Reliably getting the real client IP behind proxies requires checking specific headers. Use a dedicated utility function for this.

2. Applying Limits

Use the pattern shown in the "Basic Usage" example above. Get the IP using getIpFromRequest(req), get your limiter instance from the registry, call .limit(ip), and handle the response (setting headers, returning 429 on failure).

import type { NextApiRequest, NextApiResponse } from 'next';
import { rateLimiterRegistry } from '@/lib/ratelimit';
import { getIpFromRequest } from '@/utils/getIpFromRequest';
 
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const ip = getIpFromRequest(req);
  if (!ip) return res.status(400).json({ error: 'Cannot determine IP.' });
 
  try {
    const limiter = rateLimiterRegistry.get('apiGeneral'); // Or await register
    const { success, limit, remaining, reset, retryAfter } = await limiter.limit(ip);
 
    res.setHeader('X-RateLimit-Limit', limit);
    res.setHeader('X-RateLimit-Remaining', remaining);
    res.setHeader('X-RateLimit-Reset', Math.ceil(reset / 1000));
 
    if (!success) {
      if(retryAfter) res.setHeader('Retry-After', retryAfter);
      return res.status(429).json({ error: 'Too Many Requests' });
    }
 
    // SUCCESS: Proceed with API logic
    res.status(200).json({ data: 'Super secret stuff' });
 
  } catch (error) {
    console.error("Ratelimit error in API route:", error);
    return res.status(500).json({ error: 'Internal Server Error' });
  }
}

On this page