Day 76

Middleware

12 min
JavaScript 100 Days

Middleware functions route handlers ke beech mein chalti hain — request modify karo, authentication check karo, log karo. Express ka power middleware se aata hai.

Custom Middleware

Apna middleware likho.

middleware.js
javascript
// Logger middleware
function logger(req, res, next) {
  const start = Date.now();
  console.log(`→ ${req.method} ${req.path}`);
  
  res.on("finish", () => {
    const duration = Date.now() - start;
    console.log(`← ${res.statusCode} ${req.path} (${duration}ms)`);
  });
  
  next(); // zaroori hai — baad wala middleware chalega
}

// Auth middleware
function requireAuth(req, res, next) {
  const token = req.headers.authorization?.split(" ")[1];
  
  if (!token) {
    return res.status(401).json({ error: "Token required" });
  }
  
  try {
    const user = verifyToken(token); // JWT verify
    req.user = user; // user attach karo request pe
    next();
  } catch {
    res.status(401).json({ error: "Invalid token" });
  }
}

// Rate limiting (simple)
const rateLimit = new Map();
function rateLimiter(maxRequests, windowMs) {
  return (req, res, next) => {
    const ip = req.ip;
    const now = Date.now();
    const window = rateLimit.get(ip) || { count: 0, start: now };
    
    if (now - window.start > windowMs) {
      window.count = 1;
      window.start = now;
    } else {
      window.count++;
    }
    
    rateLimit.set(ip, window);
    
    if (window.count > maxRequests) {
      return res.status(429).json({ error: "Too many requests" });
    }
    
    next();
  };
}

// Apply middleware
app.use(logger);
app.use(rateLimiter(100, 60000)); // 100 req per minute
app.get("/protected", requireAuth, (req, res) => {
  res.json({ user: req.user });
});

🎯 Practice Challenge

Request validation middleware banao jo required fields check kare. Response time header add karo. CORS middleware setup karo.