DEV Community

Md. Khalid Hossen
Md. Khalid Hossen

Posted on

1

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.

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

Billboard image

Imagine monitoring that's actually built for developers

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

๐Ÿ‘‹ Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay