Skip to content

Commit

Permalink
Add rateLimiter
Browse files Browse the repository at this point in the history
  • Loading branch information
likui628 committed Sep 28, 2024
1 parent 0fb5fb2 commit 34836c9
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 3 deletions.
2 changes: 1 addition & 1 deletion .env.sample
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
NODE_ENV=development
NODE_ENV=production

ACCESS_TOKEN_SECRET='your_access_token_secret'
REFRESH_TOKEN_SECRET='your_refresh_token_secret'
Expand Down
16 changes: 16 additions & 0 deletions package-lock.json

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

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,17 @@
"license": "MIT",
"dependencies": {
"@prisma/client": "^5.20.0",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.21.0",
"express-rate-limit": "^7.4.0",
"helmet": "^7.1.0",
"jsonwebtoken": "^9.0.2",
"morgan": "^1.10.0",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"zod": "^3.23.8",
"cookie-parser": "^1.4.6"
"zod": "^3.23.8"
},
"devDependencies": {
"@types/cookie-parser": "^1.4.7",
Expand Down
4 changes: 4 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import cookieParser from 'cookie-parser'
import routes from './routes/v1'
import { errorHandler, notFound } from './middlewares'
import { jwtStrategy } from './config/passport'
import { rateLimiter } from './middlewares/rate-limiter'

dotenv.config()

Expand All @@ -23,6 +24,9 @@ app.use(cors())
app.use(cookieParser())
app.use(express.json())

if (process.env.NODE_ENV === 'production') {
app.use('/v1/auth', rateLimiter)
}
app.use('/v1', routes)

app.use(notFound)
Expand Down
16 changes: 16 additions & 0 deletions src/middlewares/rate-limiter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import rateLimit from 'express-rate-limit'
import { errorResponse } from '../utils'

export const rateLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 2,
skipSuccessfulRequests: true,
handler: (_req, res, _next) => {
return errorResponse(
res,
'rate-limit',
429,
'Too many requests, please try again later.',
)
},
})

0 comments on commit 34836c9

Please sign in to comment.