diff --git a/package.json b/package.json index b18b170..46ff04d 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index eee127b..a5c14ff 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -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 diff --git a/server.mjs b/server.mjs index f5ce69d..8c2f6ff 100755 --- a/server.mjs +++ b/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, {