Skip to content

Commit b5f144b

Browse files
redis rate limit
1 parent 7befe6f commit b5f144b

File tree

3 files changed

+56
-15
lines changed

3 files changed

+56
-15
lines changed

package.json

+2
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@
2424
"@react-pdf-viewer/zoom": "^3.12.0",
2525
"@t3-oss/env-nextjs": "^0.10.1",
2626
"@types/mongoose": "^5.11.97",
27+
"@upstash/ratelimit": "^2.0.3",
28+
"@vercel/kv": "^3.0.0",
2729
"axios": "^1.7.2",
2830
"bcrypt": "^5.1.1",
2931
"class-variance-authority": "^0.7.0",

pnpm-lock.yaml

+36
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/middleware.ts

+18-15
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,22 @@
1-
import { NextResponse } from "next/server";
2-
import { verifyToken } from "./lib/auth";
1+
import { type NextRequest, NextResponse } from 'next/server';
2+
import { Ratelimit } from '@upstash/ratelimit';
3+
import { kv } from '@vercel/kv';
34

4-
export async function middleware(request: Request) {
5-
const authtoken = request.headers.get("Authorization");
6-
if (!authtoken ?? !authtoken?.startsWith("Bearer ")) {
7-
return NextResponse.json({ message: "Unauthorized" }, { status: 401 });
8-
}
9-
const token = authtoken.split(" ")[1];
10-
const isValidToken = await verifyToken(token);
11-
if (!isValidToken) {
12-
return NextResponse.json({ message: "Unauthorized" }, { status: 401 });
13-
}
14-
return NextResponse.next();
15-
}
5+
const ratelimit = new Ratelimit({
6+
redis: kv,
7+
limiter: Ratelimit.slidingWindow(5, '900 s'),
8+
});
169

1710
export const config = {
18-
matcher: ["/api/admin/:path*"],
11+
matcher: '/api/mail',
1912
};
13+
14+
export default async function middleware(request: NextRequest) {
15+
const ip = request.ip ?? '127.0.0.1';
16+
const { success } = await ratelimit.limit(
17+
ip
18+
);
19+
return success
20+
? NextResponse.next()
21+
: NextResponse.json({ message: "You can upload a maximum of 5 papers every 15 minutes" }, { status: 429 });
22+
}

0 commit comments

Comments
 (0)