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.

Postmark Image

"Please fix this..."

Focus on creating stellar experiences without email headaches. Postmark's reliable API and detailed analytics make your transactional emails as polished as your product.

Start free

Top comments (0)

Quickstart image

Django MongoDB Backend Quickstart! A Step-by-Step Tutorial

Get up and running with the new Django MongoDB Backend Python library! This tutorial covers creating a Django application, connecting it to MongoDB Atlas, performing CRUD operations, and configuring the Django admin for MongoDB.

Watch full video →

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay