Last active
April 23, 2023 13:10
-
-
Save tqmvt/67f17cbac15634ea44b950d8a73a820e to your computer and use it in GitHub Desktop.
rate limit - upstash redis with vercel edge / nextjs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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