feat: add rate limiter in fastify server
This commit is contained in:
parent
a21401eab2
commit
02cd6f4b5f
3 changed files with 35 additions and 0 deletions
|
@ -30,6 +30,7 @@
|
|||
"@ayco/astro-resume": "^0.4.4",
|
||||
"@ayco/astro-sw": "^0.8.14",
|
||||
"@fastify/middie": "^9.0.3",
|
||||
"@fastify/rate-limit": "^10.3.0",
|
||||
"@fastify/static": "^8.2.0",
|
||||
"astro": "^5.12.8",
|
||||
"astro-iconify": "^1.2.0",
|
||||
|
|
|
@ -26,6 +26,9 @@ importers:
|
|||
'@fastify/middie':
|
||||
specifier: ^9.0.3
|
||||
version: 9.0.3
|
||||
'@fastify/rate-limit':
|
||||
specifier: ^10.3.0
|
||||
version: 10.3.0
|
||||
'@fastify/static':
|
||||
specifier: ^8.2.0
|
||||
version: 8.2.0
|
||||
|
@ -591,6 +594,9 @@ packages:
|
|||
'@fastify/proxy-addr@5.0.0':
|
||||
resolution: {integrity: sha512-37qVVA1qZ5sgH7KpHkkC4z9SK6StIsIcOmpjvMPXNb3vx2GQxhZocogVYbr2PbbeLCQxYIPDok307xEvRZOzGA==}
|
||||
|
||||
'@fastify/rate-limit@10.3.0':
|
||||
resolution: {integrity: sha512-eIGkG9XKQs0nyynatApA3EVrojHOuq4l6fhB4eeCk4PIOeadvOJz9/4w3vGI44Go17uaXOWEcPkaD8kuKm7g6Q==}
|
||||
|
||||
'@fastify/send@4.1.0':
|
||||
resolution: {integrity: sha512-TMYeQLCBSy2TOFmV95hQWkiTYgC/SEx7vMdV+wnZVX4tt8VBLKzmH8vV9OzJehV0+XBfg+WxPMt5wp+JBUKsVw==}
|
||||
|
||||
|
@ -4394,6 +4400,12 @@ snapshots:
|
|||
'@fastify/forwarded': 3.0.0
|
||||
ipaddr.js: 2.2.0
|
||||
|
||||
'@fastify/rate-limit@10.3.0':
|
||||
dependencies:
|
||||
'@lukeed/ms': 2.0.2
|
||||
fastify-plugin: 5.0.1
|
||||
toad-cache: 3.7.0
|
||||
|
||||
'@fastify/send@4.1.0':
|
||||
dependencies:
|
||||
'@lukeed/ms': 2.0.2
|
||||
|
|
22
server.mjs
22
server.mjs
|
@ -7,6 +7,28 @@ import { fileURLToPath } from 'node:url'
|
|||
import { handler as ssrHandler } from './dist/server/entry.mjs'
|
||||
|
||||
const app = Fastify({ logger: true })
|
||||
await app.register(import('@fastify/rate-limit'), {
|
||||
global: true,
|
||||
max: 25,
|
||||
timeWindow: 1000,
|
||||
})
|
||||
|
||||
await app.setNotFoundHandler(
|
||||
{
|
||||
preHandler: app.rateLimit(),
|
||||
},
|
||||
function (request, reply) {
|
||||
reply.code(404).send({ nothing: 'to see here' })
|
||||
}
|
||||
)
|
||||
|
||||
await app.setErrorHandler(function (error, request, reply) {
|
||||
if (error.statusCode === 429) {
|
||||
reply.code(429)
|
||||
error.message = 'You hit the rate limit! Slow down please!'
|
||||
}
|
||||
reply.send(error)
|
||||
})
|
||||
|
||||
await app
|
||||
.register(fastifyStatic, {
|
||||
|
|
Loading…
Reference in a new issue