JAVASCRIPT

Implement Brute-Force Protection for Login Endpoints

Protect your login and sensitive endpoints from brute-force and denial-of-service attacks by implementing robust rate limiting in Node.js Express.

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

const app = express();
app.use(express.json()); // For parsing application/json

// Rate limit configuration for login attempts
const loginLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 5, // Limit each IP to 5 login requests per `windowMs`
  message: 'Too many login attempts from this IP, please try again after 15 minutes',
  handler: (req, res, next, options) => {
    res.status(options.statusCode).send(options.message);
  },
  standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
  legacyHeaders: false, // Disable the `X-RateLimit-*` headers
});

// Apply the rate limiter to specific routes
app.post('/api/login', loginLimiter, (req, res) => {
  const { username, password } = req.body;
  // In a real application, you would validate credentials here
  if (username === 'user' && password === 'password') {
    res.status(200).json({ message: 'Login successful' });
  } else {
    // Note: Always return a generic error message for failed login attempts
    // to avoid leaking information about valid usernames.
    res.status(401).json({ message: 'Invalid credentials' });
  }
});

// Other routes can be unprotected or have different limits
app.get('/api/public', (req, res) => {
  res.send('Public content');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: Rate limiting is crucial for protecting sensitive endpoints like login pages from brute-force attacks and denial-of-service (DoS) attempts. This Node.js Express snippet uses the `express-rate-limit` middleware to restrict the number of requests an IP address can make within a specified time window. For instance, the `loginLimiter` allows only 5 login attempts every 15 minutes. This helps prevent attackers from rapidly guessing credentials, significantly improving the security of your authentication process.

Need help integrating this into your project?

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

Hire DigitalCodeLabs