Skip to content

Commit

Permalink
feat(web): upstash rate limiting
Browse files Browse the repository at this point in the history
  • Loading branch information
ixahmedxi committed Feb 7, 2024
1 parent d015658 commit 1fc5734
Show file tree
Hide file tree
Showing 5 changed files with 69 additions and 0 deletions.
2 changes: 2 additions & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
"@trpc/client": "^10.45.1",
"@trpc/react-query": "^10.45.1",
"@trpc/server": "^10.45.1",
"@upstash/ratelimit": "^1.0.1",
"@upstash/redis": "^1.28.3",
"geist": "^1.2.2",
"next": "14.1.0",
"next-themes": "^0.2.1",
Expand Down
4 changes: 4 additions & 0 deletions apps/web/src/env.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,15 @@ export const env = createEnv({
server: {
NODE_ENV: z.enum(['development', 'test', 'production']).optional(),
PORT: z.coerce.number().default(3000),
UPSTASH_REDIS_REST_URL: z.string().min(1),
UPSTASH_REDIS_REST_TOKEN: z.string().min(1),
},
client: {},
runtimeEnv: {
NODE_ENV: process.env.NODE_ENV,
PORT: process.env['PORT'],
UPSTASH_REDIS_REST_URL: process.env['UPSTASH_REDIS_REST_URL'],
UPSTASH_REDIS_REST_TOKEN: process.env['UPSTASH_REDIS_REST_TOKEN'],
},
emptyStringAsUndefined: true,
});
32 changes: 32 additions & 0 deletions apps/web/src/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { NextResponse } from 'next/server';

import type { NextRequest } from 'next/server';

import { Ratelimit } from '@upstash/ratelimit';
import { Redis } from '@upstash/redis';

import { env } from './env';

const redis = new Redis({
url: env.UPSTASH_REDIS_REST_URL,
token: env.UPSTASH_REDIS_REST_TOKEN,
});

const ratelimit = new Ratelimit({
redis: redis,
limiter: Ratelimit.slidingWindow(10, '3 s'),
});

export default async function middleware(
request: NextRequest,
): Promise<Response | undefined> {
const ip = request.ip ?? '127.0.0.1';
const { success } = await ratelimit.limit(ip);
return success
? NextResponse.next()
: NextResponse.redirect(new URL('/blocked', request.url));
}

export const config = {
matcher: ['/((?!.*\\..*|_next).*)', '/', '/(api|trpc)(.*)'],
};
2 changes: 2 additions & 0 deletions cspell.config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ words:
- nextjs
- orbitkit
- packagejson
- Ratelimit
- shadcn
- stylesheet
- superjson
Expand All @@ -35,4 +36,5 @@ words:
- turborepo
- typecheck
- typeof
- upstash
- viewports
29 changes: 29 additions & 0 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 1fc5734

Please sign in to comment.