JAVASCRIPT

Implement Basic API Rate Limiting in Node.js with express-rate-limit

Protect your Node.js Express APIs from abuse and brute-force attacks by implementing effective rate limiting using the express-rate-limit middleware.

// First, install the package: npm install express express-rate-limit
const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
const port = 3000;

// 1. Basic Rate Limiter for all API requests
// Allows 100 requests per 15 minutes per IP address.
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) => req.ip, // Use IP address to identify client
    handler: (req, res, next, options) => {
        res.status(options.statusCode).send(options.message);
    },
});

// 2. Stricter Rate Limiter for login attempts
// Allows 5 login attempts per 5 minutes per IP.
const loginLimiter = rateLimit({
    windowMs: 5 * 60 * 1000, // 5 minutes
    max: 5, // Limit each IP to 5 login requests per windowMs
    message: 'Too many login attempts from this IP, please try again after 5 minutes',
    standardHeaders: true,
    legacyHeaders: false,
});

// Apply the general API rate limiter to all routes starting with /api/
app.use('/api/', apiLimiter);

// Apply the stricter login rate limiter to the login route
app.post('/api/login', loginLimiter, (req, res) => {
    // In a real application, you'd process login credentials here
    // For demonstration:
    res.json({ message: 'Login attempt received (rate limited).' });
});

// A public API endpoint (will be covered by apiLimiter)
app.get('/api/data', (req, res) => {
    res.json({ data: 'This is some public data.' });
});

// A non-API route (not rate limited by default in this setup)
app.get('/', (req, res) => {
    res.send('Welcome to the homepage!');
});

app.listen(port, () => {
    console.log(`Server listening at http://localhost:${port}`);
    console.log('Try accessing /api/data multiple times quickly.');
    console.log('Or try POSTing to /api/login multiple times quickly.');
});
How it works: This Node.js snippet demonstrates how to implement API rate limiting using the popular `express-rate-limit` middleware. It shows two different rate limiters: a general one for most API routes and a stricter one specifically for login endpoints. Rate limiting helps protect your API from brute-force attacks, DDoS attempts, and general abuse by restricting the number of requests a client can make within a specified time window, enhancing the stability and security of your web services.

Need help integrating this into your project?

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

Hire DigitalCodeLabs