← Back to all snippets
JAVASCRIPT

Implement Robust API Rate Limiting in Node.js

Prevent abuse and improve API stability by implementing rate limiting in your Node.js Express application using middleware to restrict request frequency.

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
    handler: (req, res, next, options) => {
        res.status(options.statusCode).send(options.message);
    }
});

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

app.get('/', (req, res) => {
    res.send('Hello World! Rate limited.');
});

app.listen(3000, () => {
    console.log('Server running on http://localhost:3000');
});
How it works: This snippet demonstrates how to implement API rate limiting using the `express-rate-limit` middleware for Node.js Express applications. It sets a limit of 100 requests per IP address within a 15-minute window. When the limit is exceeded, a `429 Too Many Requests` status is returned with a custom message, protecting your API from brute-force attacks and resource exhaustion.

Need help integrating this into your project?

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

Hire DigitalCodeLabs