JAVASCRIPT

Implement Server-Side API Rate Limiting

Prevent abuse and control traffic to your API by implementing server-side rate limiting using middleware in Node.js with Express, ensuring fair resource usage.

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

const app = express();

// Apply to all requests
const apiLimiter = 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 to specific routes, e.g., login
const loginLimiter = rateLimit({
  windowMs: 60 * 60 * 1000, // 1 hour window
  max: 5, // 5 attempts per IP per hour
  message: 'Too many login attempts from this IP, please try again after an hour',
  standardHeaders: true,
  legacyHeaders: false,
});

// Apply the general rate limit to all requests
app.use(apiLimiter);

// Apply the login specific rate limit
app.post('/login', loginLimiter, (req, res) => {
  res.send('Login successful');
});

app.get('/data', (req, res) => {
  res.json({ message: 'This is some data.' });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: This snippet demonstrates how to implement server-side API rate limiting using the `express-rate-limit` middleware in a Node.js Express application. It defines two limiters: a general `apiLimiter` applied to all routes, and a more restrictive `loginLimiter` specifically for the `/login` route. The `windowMs` sets the time window, and `max` defines the number of allowed requests within that window per IP address. This helps protect your API from brute-force attacks and ensures fair usage by preventing a single client from overwhelming the server.

Need help integrating this into your project?

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

Hire DigitalCodeLabs