Blog>
Snippets

API Rate Limiter

Use middleware to implement a rate-limiting mechanism on API routes to prevent abuse.
const rateLimit = require('express-rate-limit');

// Apply rate limiting to all requests
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100 // limit each IP to 100 requests per windowMs
});

// Apply the rate limiting middleware to all requests
app.use(limiter);
This code uses the 'express-rate-limit' middleware to limit incoming requests. Requests are limited to 100 per IP address every 15 minutes. The 'limiter' is then applied as middleware to all routes.
const express = require('express');
const app = express();
const PORT = 3000;

app.use(limiter); // Assuming 'limiter' is defined as above

// Routes go here

app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
This example shows a basic Express server setup. The 'limiter' middleware is attached to the app, which applies the rate limiting to all routes defined after 'app.use(limiter)'. The server listens on port 3000.