-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
71 lines (62 loc) · 1.63 KB
/
Copy pathmiddleware.ts
File metadata and controls
71 lines (62 loc) · 1.63 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { NextResponse } from "next/server"
import type { NextRequest } from "next/server"
import arcjet, { slidingWindow, tokenBucket } from "@arcjet/next"
// General rate limit: 50 req / 60s
const aj = arcjet({
key: process.env.ARCJET_KEY!,
rules: [
slidingWindow({
mode: "LIVE",
interval: "60s",
max: 50,
}),
],
})
// Research-specific rate limit: 5 req / 60s
const ajResearch = arcjet({
key: process.env.ARCJET_KEY!,
rules: [
tokenBucket({
mode: "LIVE",
refillRate: 5,
interval: "60s",
capacity: 5,
}),
],
})
// Status polling rate limit: 120 req / 60s (more lenient for polling)
const ajStatus = arcjet({
key: process.env.ARCJET_KEY!,
rules: [
slidingWindow({
mode: "LIVE",
interval: "60s",
max: 120,
}),
],
})
export async function middleware(request: NextRequest) {
// Skip middleware for Inngest webhook endpoint
if (request.nextUrl.pathname.startsWith("/api/inngest")) {
return NextResponse.next()
}
let decision;
// More lenient rate limit for status polling endpoints
if (request.nextUrl.pathname.includes("/status")) {
decision = await ajStatus.protect(request)
} else if (request.nextUrl.pathname.startsWith("/api/research")) {
decision = await ajResearch.protect(request, { requested: 1 })
} else {
decision = await aj.protect(request)
}
if (decision.isDenied()) {
return NextResponse.json(
{ error: "Too Many Requests", reason: decision.reason },
{ status: 429 }
)
}
return NextResponse.next()
}
export const config = {
matcher: ["/dashboard/:path*", "/onboarding", "/api/:path*"],
}