pollo/middleware.ts

47 lines
1.3 KiB
TypeScript
Raw Normal View History

2023-10-15 00:13:18 -03:00
import { authMiddleware } from "@clerk/nextjs";
2023-09-24 23:49:24 -06:00
import { validateRequest } from "./app/_lib/unkey";
2023-10-15 00:15:22 -03:00
import { NextRequest, NextResponse } from "next/server";
2023-08-20 01:15:52 -06:00
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
import { env } from "./env.mjs";
const rateLimit = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(
Number(env.UPSTASH_RATELIMIT_REQUESTS),
`${Number(env.UPSTASH_RATELIMIT_SECONDS)}s`
),
analytics: true,
});
2023-08-12 17:12:42 -06:00
export default authMiddleware({
2023-10-05 00:58:00 -06:00
ignoredRoutes: ["/"],
2023-10-15 00:13:18 -03:00
publicRoutes: ["/api/external/(.*)", "/api/webhooks/(.*)"],
apiRoutes: ["/api/internal/(.*)"],
2023-10-15 00:15:22 -03:00
beforeAuth: async (req: NextRequest) => {
2023-10-05 00:58:00 -06:00
const { success } = await rateLimit.limit(req.ip || "");
if (success) {
if (req.nextUrl.pathname.includes("/api/external/private")) {
const isValid = await validateRequest(req);
if (!isValid) {
return new NextResponse("UNAUTHORIZED", {
status: 403,
statusText: "Unauthorized!",
});
}
2023-08-20 01:15:52 -06:00
}
2023-10-05 00:58:00 -06:00
return NextResponse.next();
2023-08-17 20:55:56 -06:00
}
2023-10-05 00:58:00 -06:00
return new NextResponse("TOO MANY REQUESTS", {
status: 429,
statusText: "Too many requests!",
});
2023-08-17 16:40:09 -06:00
},
2023-08-12 17:12:42 -06:00
});
export const config = {
2023-09-09 19:25:23 -06:00
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api)(.*)"],
2023-08-12 17:12:42 -06:00
};