Skip to content

Instantly share code, notes, and snippets.

@tqmvt
Last active April 23, 2023 13:10
Show Gist options
  • Save tqmvt/67f17cbac15634ea44b950d8a73a820e to your computer and use it in GitHub Desktop.
Save tqmvt/67f17cbac15634ea44b950d8a73a820e to your computer and use it in GitHub Desktop.
rate limit - upstash redis with vercel edge / nextjs
import { NextRequest, NextResponse } from "next/server";
import { Redis } from "@upstash/redis";
export const config = {
runtime: "edge",
};
if (
!process.env.UPSTASH_REDIS_REST_URL ||
!process.env.UPSTASH_REDIS_REST_TOKEN
) {
throw new Error("Missing UPSTASH_REDIS_REST_URL or UPSTASH_REDIS_REST_TOKEN");
}
// Create a Redis client outside of the function
const redis = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL,
token: process.env.UPSTASH_REDIS_REST_TOKEN,
});
export async function middleware(req: NextRequest) {
const country = req.geo?.country || "fallback";
// Increment the country counter
const sameCountryVisits = await redis.incr(country);
// Increment the total counter
const totalVisits = await redis.incr("total");
return NextResponse.json({
sameCountryVisits,
totalVisits,
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment