forked from Rakshit-gen/Slanine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
42 lines (34 loc) · 1.13 KB
/
middleware.ts
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
import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { ratelimit } from './lib/ratelimit';
const isProtectedRoute = createRouteMatcher([
'/dashboard(.*)',
]);
async function ratelimitMiddleware(request: NextRequest) {
const ip = request.ip ?? request.headers.get('x-forwarded-for') ?? 'unknown';
const { success, limit, reset, remaining } = await ratelimit.limit(
`ratelimit_middleware_${ip}`
);
if (!success) {
return new NextResponse('Too Many Requests', {
status: 429,
headers: {
'X-RateLimit-Limit': limit.toString(),
'X-RateLimit-Remaining': remaining.toString(),
'X-RateLimit-Reset': reset.toString(),
},
});
}
return null;
}
export default clerkMiddleware(async (auth, req) => {
if (isProtectedRoute(req)) {
await auth().protect();
}
const ratelimitResponse = await ratelimitMiddleware(req);
if (ratelimitResponse) return ratelimitResponse;
});
export const config = {
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};