Skip to content

Commit

Permalink
rate limit
Browse files Browse the repository at this point in the history
  • Loading branch information
nichtsam committed Dec 3, 2024
1 parent ece6756 commit 20b1eb2
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
"drizzle-orm": "0.36.3",
"drizzle-zod": "0.5.1",
"express": "4.21.1",
"express-rate-limit": "7.4.1",
"get-port": "7.1.0",
"gray-matter": "4.0.3",
"helmet": "8.0.0",
Expand Down
13 changes: 13 additions & 0 deletions pnpm-lock.yaml

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

30 changes: 30 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import chalk from 'chalk'
import closeWithGrace from 'close-with-grace'
import compression from 'compression'
import express from 'express'
import { rateLimit } from 'express-rate-limit'
import getPort, { portNumbers } from 'get-port'
import helmet from 'helmet'
import morgan from 'morgan'
Expand Down Expand Up @@ -56,6 +57,35 @@ app.use(
}),
)

const rateLimitConfig = {
skip: () => MODE !== 'production',
windowMs: 60 * 1000,
max: 1000,
standardHeaders: true,
legacyHeaders: false,
keyGenerator: (req) => {
return req.get('fly-client-ip') ?? `${req.ip}`
},
}

const strongestRateLimit = rateLimit({ ...rateLimitConfig, max: 10 })
const strongRateLimit = rateLimit({ ...rateLimitConfig, max: 100 })
const generalRateLimit = rateLimit(rateLimitConfig)

app.use((req, res, next) => {
const criticalActions = ['/auth', '/onboarding']

if (req.method !== 'GET' && req.method !== 'HEAD') {
if (criticalActions.some((p) => req.path.startsWith(p))) {
return strongestRateLimit(req, res, next)
}

return strongRateLimit(req, res, next)
}

return generalRateLimit(req, res, next)
})

app.use((_, res, next) => {
res.locals.cspNonce = crypto.randomBytes(16).toString('hex')
next()
Expand Down

0 comments on commit 20b1eb2

Please sign in to comment.