Last active
February 16, 2023 20:40
-
-
Save riccardogiorato/86317d568502b16b1db9dff86a92bfc4 to your computer and use it in GitHub Desktop.
Redis with Vercel Edge: https://github.com/riccardogiorato/redis-with-vercel-edge
This file contains hidden or 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