Rate limiting plays a crucial role in preventing abuse by controlling the number of requests a user can make within a certain period. While, to keep track of requests and ips, we need to store them in-memory for ease of access and speed in response. ⛔✋
Running your Next.js app on Vercel’s serverless or edge runtimes offers incredible speed and scalability. These environments handle requests in isolation, spinning up lightweight instances as needed to deliver lightning-fast responses. However, this architecture has a key limitation: data stored in an instance’s memory isn’t accessible to others, as each instance is stateless.
To address this, we often need external solutions like Redis, a high-performance in-memory database. Services like Upstash Redis complement Vercel perfectly by enabling shared, low-latency data access across instances.
With that foundation set, let’s dive into the implementation!
Upstash Redis 🙌
In your Vercel project page, go to Storage tab.
Click on Create Database button, then select Upstash for Redis:
Don't forget to put this line in your
.gitignore:
.env*.local
Install the following modules:
npm i @upstash/redis @upstash/ratelimit
Create a ratelimit instance and use it
// route.ts
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
const rateLimiter = new Ratelimit({
limiter: Ratelimit.fixedWindow(1, "60 s"),
redis: Redis.fromEnv(),
analytics: true,
prefix: "@upstash/ratelimit",
});
const getIP = (req: Request) => {
const ip =
req.headers.get("cf-connecting-ip") ||
req.headers.get("x-forwarded-for") ||
undefined;
return Array.isArray(ip) ? ip[0] : ip;
};
export async function POST(req: Request) {
// ...
// Here we check if limit hit! 👇
const { success } = await rateLimiter.limit(ip || "unknown");
if (!success) return Response.json({ error: "Too many requests" }, { status: 429 } );
// ...
}
Congratulations! 🎉 You’ve unlocked the power of combining Vercel’s serverless capabilities with Upstash Redis. This setup will not only elevate your app’s performance but also open the door to building highly scalable, fast, and reliable applications. With this powerful foundation, your Next.js app is ready to handle whatever comes next—smoothly and efficiently. 🚀
SOCIAL SHARE CARD GENERATOR