Skip to content

Commit

Permalink
feat(api): add rate-limiting with Upstash for dev and prod environments
Browse files Browse the repository at this point in the history
  • Loading branch information
pkmanas22 committed Dec 29, 2024
1 parent b2c5e96 commit b45c806
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 20 deletions.
31 changes: 29 additions & 2 deletions apps/api/app/v1/[[...route]]/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { handle } from "hono/vercel";
import { Hono } from "hono";
import { Context, Hono, Next } from "hono";
import mail from "./mail";
import test from "./test";
import session from "./session";
Expand All @@ -10,6 +10,9 @@ import user from "./user";
import contributors from "./contributors";
import { cors } from "hono/cors";
import workspace from "./workspace";
import { Ratelimit } from '@upstash/ratelimit';
import { auth as Auth } from '@plura/auth';
import { cache } from "@plura/cache";

export const runtime = "edge";

Expand All @@ -36,12 +39,36 @@ app.use(
}),
);


const rateLimitHandler = async (c: Context, next: Next) => {
const session = await Auth.api.getSession({ headers: c.req.raw.headers });

// const limit = process.env.NODE_ENV === "production" ? 60 : 5; // for testing
const limit = process.env.NODE_ENV === "production" ? 60 : 100;

const rateLimit = new Ratelimit({
redis: cache,
limiter: Ratelimit.slidingWindow(limit, "1m"),
analytics: true, // store analytics data in redis db
})

const { success } = await rateLimit.limit(session?.session.ipAddress || session?.session.userId || "anonymous");

if (!success) {
return c.json({ message: "You hit the rate limit" }, 429);
}
return await next();
}

app.route("/health", health);
app.route("/status", status);

app.use(rateLimitHandler)
// apply rate limit to below routes
app.route("/session", session);
app.route("/test", test);
app.route("/mail", mail);
app.route("/auth", auth);
app.route("/status", status);
app.route("/user", user);
app.route("/contributors", contributors);
app.route("/workspace", workspace);
Expand Down
8 changes: 5 additions & 3 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,15 @@
"dependencies": {
"@hono/node-server": "^1.13.5",
"@hono/zod-validator": "^0.4.1",
"@prisma/client": "^5.22.0",
"@plura/auth": "workspace:*",
"@plura/cache": "workspace:*",
"@plura/crypt": "workspace:*",
"@plura/db": "workspace:*",
"@plura/mail": "workspace:*",
"@prisma/client": "^5.22.0",
"@repo/types": "workspace:*",
"@plura/cache": "workspace:*",
"@plura/crypt":"workspace:*",
"@upstash/ratelimit": "^2.0.5",
"@upstash/redis": "^1.34.3",
"hono": "^4.6.9",
"next": "15.1.1",
"prisma": "^5.22.0",
Expand Down
67 changes: 52 additions & 15 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit b45c806

Please sign in to comment.