-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddleware.ts
More file actions
33 lines (27 loc) · 775 Bytes
/
middleware.ts
File metadata and controls
33 lines (27 loc) · 775 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
import { type NextRequest, NextResponse } from "next/server";
const ratelimit = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(5, "30 s"),
ephemeralCache: new Map(),
prefix: "@upstash/ratelimit",
});
export default async function middleware(
request: NextRequest
): Promise<Response | undefined> {
const ip =
request.headers.get("x-forwarded-for") ??
request.headers.get("x-real-ip") ??
"127.0.0.1";
const { success } = await ratelimit.limit(ip);
if (!success) {
return new Response("Too Many Requests", {
status: 429,
});
}
return NextResponse.next();
}
export const config = {
matcher: "/api/session",
};