06 Rate Limit - jp7io/typescript-crud-api GitHub Wiki

Rate Limit

Add express-rate-limit

yarn add express-rate-limit
yarn add @types/express-rate-limit --dev

Create middleware

mkdir ./src/middlewares
code ./src/middlewares/rateLimiter.ts
import rateLimit from 'express-rate-limit';

export const rateLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100,
  message: {
    status: 429,
    message: 'Too many requests, please try again later.',
  },
});

Add middleware to app

code ./src/app.ts
...
import { rateLimiter } from './middlewares/rateLimiter';

export const app = async (port: number) => {
  ...
  app.use(cors());
  app.use(rateLimiter);
  ...
};

Test application

yarn dev
curl "http://localhost:4000/articles?[1-101]"
# ...
# {"status":429,"message":"Too many requests, please try again later."}

Commit

git add .
git commit -m "Rate Limit"

Next step: Seed