Skip to content

Instantly share code, notes, and snippets.

@periakteon
Created December 15, 2023 00:01
Show Gist options
  • Save periakteon/f32e1cf3186e413b148fa841284b92a8 to your computer and use it in GitHub Desktop.
Save periakteon/f32e1cf3186e413b148fa841284b92a8 to your computer and use it in GitHub Desktop.
Upstash & Clerk Rate Limiting
import { authMiddleware } from "@clerk/nextjs";
import { ratelimit } from "./utils/redis";
import { NextResponse } from "next/server";
export default authMiddleware({
async afterAuth(_auth, req, evt) {
const ip = req.ip ?? "127.0.0.1";
if (req.nextUrl.pathname === "/api/blocked") return NextResponse.next(req);
const { success, pending, limit, reset, remaining } = await ratelimit.limit(
`mw_${ip}`,
);
evt.waitUntil(pending);
const res = success
? NextResponse.next(req)
: NextResponse.redirect(new URL("/api/blocked", req.url));
res.headers.set("X-RateLimit-Limit", limit.toString());
res.headers.set("X-RateLimit-Remaining", remaining.toString());
res.headers.set("X-RateLimit-Reset", reset.toString());
return res;
},
publicRoutes: [
"/",
"/iletisim",
"/dashboard",
"/firma",
"/firma/kayit",
"/firma/kayit/personel",
"/api/trpc/company.sendContactMessage",
],
});
export const config = {
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment