DEV Community

Md. Khalid Hossen
Md. Khalid Hossen

Posted on

Added rate limit in api enpoint in node express js

Rate Limiting in Express: Protect Your API from Brute Force Attacks

Rate limiting is an essential feature to safeguard your API against brute force attacks. It helps control the number of requests a user can make within a specific time frame. Implementing rate limiting in an Express application is simple, thanks to the express-rate-limit package.

At first you need to install: yarn add express-rate-limit

Then create a middleware where you can limit your api request:

import rateLimit from 'express-rate-limit'

export const rateLimiter = rateLimit({
  windowMs: 60 * 1000,
  max: 100,
  message: 'You have exceeded the 100 requests in 1 min limit!',
  standardHeaders: true,
  legacyHeaders: false,
})

Enter fullscreen mode Exit fullscreen mode

In this example, users are allowed up to 100 requests per minute. If they exceed this limit, theyโ€™ll receive a message stating the limit has been reached. also include rate limit info in the RateLimit-* headers and disable X-RateLimit-* headers

Then you need to add this middleware into **index file:**

import express from 'express';
import { rateLimiter } from '@/middlewares/rateLimit';

const app = express();

// Apply the rate limiter middleware to all routes
app.use(rateLimiter);

// Your other middleware and routes go here...

Enter fullscreen mode Exit fullscreen mode

Conclusion
With these steps, youโ€™ve successfully added rate limiting to your Express application. This feature helps ensure your API remains protected from abuse while maintaining a smooth experience for legitimate users.

Top comments (0)