-
Book Overview & Buying
-
Table Of Contents
Full-Stack Web Development with TypeScript 5
By :
Request throttling or rate limiting is a technique that helps us against DoS attacks. It essentially counts the number of requests per user and doesn’t allow the user to perform too many requests in a given time frame. Typically, we would also identify the IP of the caller to protect our non-authorized endpoints, but as we cannot get such a low-level detail of the connection in hono, we will focus on how to implement middleware that will do request throttling of the authorized endpoints based on userId.
Let’s write middleware in which we will count how many requests a user has made in the last 15 minutes and throw a 429 status code, which means a user has made more than 100 requests:
src/middlewares/rateLimiting.ts
import type { Context } from "hono";
import type { ContextVariables } from "../constants";
const requestCounts = new Map<string, { count: number; resetTime: number }>();...