JAVASCRIPT

Add Basic API Rate Limiting to Express.js

Implement a basic rate limiting middleware for Express.js applications to protect against brute-force attacks and API abuse by restricting the number of requests per client.

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

// Basic rate limiting middleware
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
    keyGenerator: (req, res) => {
        // Use IP address as the default key.
        // For authenticated users, consider using req.user.id for more granular control.
        return req.ip;
    }
});

// Apply the rate limiting middleware to all requests or specific routes
// app.use(apiLimiter); // Apply to all requests

// Apply to specific routes, e.g., login or sensitive APIs
app.post('/login', apiLimiter, (req, res) => {
    // Handle login logic
    res.send('Login successful (or failed, but rate-limited).');
});

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

// Other routes without rate limiting
app.get('/', (req, res) => {
    res.send('Welcome to the homepage!');
});

// const PORT = process.env.PORT || 3000;
// app.listen(PORT, () => {
//     console.log(`Server running on port ${PORT}`);
// });
How it works: This JavaScript snippet demonstrates how to implement a basic API rate limiter using the `express-rate-limit` middleware in an Express.js application. It defines `apiLimiter` to restrict each IP address to `max` (e.g., 100) requests within a `windowMs` (e.g., 15 minutes). If the limit is exceeded, subsequent requests receive a 429 "Too Many Requests" status with a custom message. This mechanism effectively protects against brute-force attacks, denial-of-service attempts, and general API abuse by controlling the request frequency from individual clients.

Need help integrating this into your project?

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

Hire DigitalCodeLabs