JAVASCRIPT

Implement Server-Side Rate Limiting for API Endpoints

Protect your API endpoints from abuse, brute-force attacks, and DoS by implementing server-side rate limiting using the `express-rate-limit` middleware in Node.js.

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

// Basic API Rate Limiter: 100 requests per 15 minutes per IP
const apiLimiter = rateLimit({
    windowMs: 15 * 60 * 1000, // 15 minutes
    max: 100, // Max 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
});

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

// Apply the API limiter to all requests under /api/
app.use('/api/', apiLimiter);

// Apply the login limiter to the specific login endpoint
app.post('/login', loginLimiter, (req, res) => {
    // Handle login logic here
    res.send('Login attempt processed.');
});

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

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}`);
});
// To run this, install express and express-rate-limit:
// npm install express express-rate-limit
// Then save as app.js and run `node app.js`
How it works: This Node.js (Express) snippet demonstrates how to implement server-side rate limiting using the `express-rate-limit` middleware. It defines two distinct rate limiters: `apiLimiter` for general API endpoints (100 requests/15 min) and `loginLimiter` for a sensitive login endpoint (5 requests/5 min), both per IP address. When a client exceeds the defined limit, subsequent requests are blocked, preventing brute-force attacks, resource exhaustion, and spam. This is crucial for maintaining the availability and security of your application.

Need help integrating this into your project?

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

Hire DigitalCodeLabs