Skip to content

Instantly share code, notes, and snippets.

@riccardogiorato
Last active February 16, 2023 20:40
Show Gist options
  • Save riccardogiorato/86317d568502b16b1db9dff86a92bfc4 to your computer and use it in GitHub Desktop.
Save riccardogiorato/86317d568502b16b1db9dff86a92bfc4 to your computer and use it in GitHub Desktop.
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