JAVASCRIPT

Implementing Server-Side API Rate Limiting

Protect your API endpoints from abuse, brute-force attacks, and denial-of-service attempts by implementing effective server-side rate limiting using `express-rate-limit` in Node.js.

const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();

// Apply a global rate limit for all requests to the API
const globalApiLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // Limit each IP to 100 requests per windowMs
  message: 'Too many requests from this IP, please try again after 15 minutes',
  standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
  legacyHeaders: false, // Disable the `X-RateLimit-*` headers
});

// Apply rate limit specifically to login attempts to prevent brute-force
const loginLimiter = rateLimit({
  windowMs: 5 * 60 * 1000, // 5 minutes
  max: 5, // Allow 5 login attempts per IP per 5 minutes
  message: 'Too many login attempts from this IP, please try again after 5 minutes',
  handler: (req, res) => {
    res.status(429).json({ message: 'Too many login attempts, please try again later.' });
  },
  standardHeaders: true,
  legacyHeaders: false,
});

// Apply the global rate limiter to all API routes
app.use('/api/', globalApiLimiter);

// Apply the login specific rate limiter to the login route
app.post('/api/login', loginLimiter, (req, res) => {
  // Handle login logic
  res.send('Login attempt received');
});

// Other API routes
// app.get('/api/data', (req, res) => {
//   res.json({ data: 'Some sensitive data' });
// });

// app.listen(3000, () => {
//   console.log('Server running on port 3000');
// });
How it works: This snippet demonstrates how to implement server-side API rate limiting in an Express.js application using the `express-rate-limit` middleware. Rate limiting is a crucial security measure to protect against brute-force attacks, denial-of-service (DoS) attempts, and API abuse. It works by restricting the number of requests an IP address can make within a specified time window. Two different rate limiters are configured: 1. `globalApiLimiter`: Applies a limit of 100 requests every 15 minutes to all routes under `/api/`. 2. `loginLimiter`: Applies a stricter limit of 5 requests every 5 minutes specifically to the `/api/login` route. This is particularly effective against brute-force password guessing attacks. When a client exceeds the limit, the middleware automatically sends a `429 Too Many Requests` status code and a custom message. The `standardHeaders` option ensures that `RateLimit-Limit`, `RateLimit-Remaining`, and `RateLimit-Reset` headers are included in the response, allowing clients to understand the current rate limit status.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs