Lädt...

🔧 Rate limiting in Next.js in under 2 minutes


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

Rate limiting is important for any production app, but it’s not as complicated as it seems. In this post, we’ll show you how to easily set up API rate limiting using Upstash and Redis.

In this example, I'll show you how I added rate limiting to my production app, Mylinx. Which handles

Sign Up for a Free Upstash Account

mylinx.cc
Upstash is a managed service for Redis and Kafka with a serverless setup, offering a generous free tier. We'll use Upstash to implement rate limiting, as their rate limit package makes it easy to set up with any API.

Set Up Your Upstash Database

Upstash create a new database

upstash finish setting up db

Copy the URL and Token to your .env

Upstash dashboard copy url and tokens

Adding Rate Limiting to Our API Endpoint

First, install the necessary packages:

npm install @upstash/redis @upstash/ratelimit request-ip

Next, choose the endpoint you want to protect and import the required modules:

import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
import requestIp from "request-ip";

Set Up Rate Limiter

const redis = new Redis({
  url: process.env.UPSTASH_REDIS_REST_URL as string,
  token: process.env.UPSTASH_REDIS_REST_TOKEN as string,
});

const rateLimiter = new Ratelimit({
  redis: redis,
  limiter: Ratelimit.slidingWindow(60, "1m"), // s: seconds m: minutes h: hours and d: days
});

Add Rate Limiting to API Handler

import { NextApiRequest, NextApiResponse } from 'next';
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
import requestIp from "request-ip";

const redis = new Redis({
  url: process.env.UPSTASH_REDIS_REST_URL as string,
  token: process.env.UPSTASH_REDIS_REST_TOKEN as string,
});

const rateLimiter = new Ratelimit({
  redis: redis,
  limiter: Ratelimit.slidingWindow(10, "1h"),
});

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'POST') {
    const clientIp = requestIp.getClientIp(req) || 'default-identifier';

    const { success } = await rateLimiter.limit(`${clientIp}-my-api-endpoint`);

    if (!success) {
      return res.status(429).json({ message: 'Rate limit exceeded, please try again later.' });
    }

    // Your API LOGIC HERE

    return res.status(200).json({ message: 'Request successful!' });
  } else {
    return res.status(405).json({ message: 'Method not allowed.' });
  }
}

This example provides a simple setup for rate limiting, allowing you to easily integrate it into your API endpoint.

Congratulations! You’ve successfully added rate limiting by IP to one of your endpoints.

Dusting hands finished

I can't express enough how Upstash and its free tier have saved my app from collapse. With the free tier barely touched, Mylinx handles over 175K hits a month.

https://mylinx.cc/features

...

🔧 🧠 Caching vs. Rate Limiting? 🤺 More Like Caching for Rate Limiting 🚀


📈 53.55 Punkte
🔧 Programmierung

🔧 What is Rate Limiting? Exploring the Role of Rate Limiting in Protecting Web APIs from Attacks


📈 53.55 Punkte
🔧 Programmierung

🔧 Rate limiting in Next.js in under 2 minutes


📈 50.61 Punkte
🔧 Programmierung

🔧 🚀 Introducing rate-bouncer: A Powerful Rate Limiting Middleware for Node.js


📈 38.02 Punkte
🔧 Programmierung

🔧 Introducing Rate Keeper: A Compact Utility for Robust Rate Limiting


📈 38.02 Punkte
🔧 Programmierung

🔧 Overcoming Hard Rate Limits: Efficient Rate Limiting with Token Bucketing and Redis


📈 38.02 Punkte
🔧 Programmierung

🔧 Scaling in Practice: Caching and Rate-Limiting With Redis and Next.js


📈 32.12 Punkte
🔧 Programmierung

🔧 Next 14 Rate Limiting serverless functions


📈 32.12 Punkte
🔧 Programmierung

🔧 Next 14 Rate Limiting serverless functions


📈 32.12 Punkte
🔧 Programmierung

🔧 Building an FAQ Generator API with Next.js, GPT-4, and Unkey: Making Rate Limiting Fun!


📈 32.12 Punkte
🔧 Programmierung

🔧 4 Best Rate Limiting Solutions for Next.js Apps (2024)


📈 32.12 Punkte
🔧 Programmierung

🔧 Implementing Rate Limiting in API Routes with Express and Next.js


📈 32.12 Punkte
🔧 Programmierung

🔧 How to Add Rate Limiting to Your Next.js App Router


📈 32.12 Punkte
🔧 Programmierung

🔧 Rate Limiting for Beginners: What It Is and How to Build One in Go


📈 26.77 Punkte
🔧 Programmierung

🔧 Managing Rate Limiting


📈 26.77 Punkte
🔧 Programmierung

🕵️ PHPJabbers Event Booking Calendar 4.0 Missing Rate Limiting


📈 26.77 Punkte
🕵️ Sicherheitslücken

🕵️ Yelp: No rate limiting for confirmation email lead to email flooding


📈 26.77 Punkte
🕵️ Sicherheitslücken

🔧 Scaling APIs without breaking them using Rate Limiting


📈 26.77 Punkte
🔧 Programmierung

🔧 Rate Limiting Algorithms and Techniques


📈 26.77 Punkte
🔧 Programmierung

🔧 How to Implement Effective Rate Limiting in Application Design


📈 26.77 Punkte
🔧 Programmierung

🎥 Setting up Rate Limiting in .NET 7 with Damien Edwards and David Fowler @ Microsoft Ignite


📈 26.77 Punkte
🎥 Video | Youtube

🔧 Rate Limiting Microservice in Rust


📈 26.77 Punkte
🔧 Programmierung

🔧 Custom SSL Configurations, Rate Limiting, and More in SafeLine's Latest Update


📈 26.77 Punkte
🔧 Programmierung

💾 PHPJabbers Cleaning Business Software 1.0 Missing Rate Limiting


📈 26.77 Punkte
💾 IT Security Tools

🕵️ Stripo Inc: No Rate Limiting on /reset-password-request/ endpoint


📈 26.77 Punkte
🕵️ Sicherheitslücken

🔧 Day 5: BackendChallenges.com - Building Rate Limiting for Scalable APIs 🚀


📈 26.77 Punkte
🔧 Programmierung

🔧 System Design 08 - Rate Limiting: The Bouncer That Keeps Your API Calm


📈 26.77 Punkte
🔧 Programmierung

🔧 ⚙️ Laravel Queues: Rate-Limiting jobs


📈 26.77 Punkte
🔧 Programmierung

🕵️ Weblate: No rate limiting for Remove Account lead to huge Mass mailings


📈 26.77 Punkte
🕵️ Sicherheitslücken

🔧 Supercharging API Rate Limiting with AIMD - A Deep Dive into Modern System Design


📈 26.77 Punkte
🔧 Programmierung

🔧 Rate limiting with Redis: An essential guide


📈 26.77 Punkte
🔧 Programmierung

🔧 API Rate Limiting in Node.js


📈 26.77 Punkte
🔧 Programmierung

💾 PHPJabbers Meeting Room Booking System 1.0 Missing Rate Limiting


📈 26.77 Punkte
💾 IT Security Tools