Node.js Lesson 9: Middleware

🟢 Node.js CourseLesson 9 of 15 · 60% complete

Middleware are functions that run between a request arriving and a response being sent. They are how Express handles logging, authentication, error handling, and more.

How Middleware Works

// Middleware signature: (req, res, next)
function myMiddleware(req, res, next) {
  // Do something with the request
  console.log("Request received:", req.method, req.url);
  
  // Call next() to pass to the next middleware/route
  next();
  
  // If you don't call next(), the request hangs!
}

Built-in & Common Middleware

const express = require("express");
const app = express();

// Parse JSON bodies
app.use(express.json());

// Parse URL-encoded form data
app.use(express.urlencoded({ extended: true }));

// Serve static files from "public" folder
app.use(express.static("public"));

// CORS (install: npm install cors)
const cors = require("cors");
app.use(cors());

// Logger middleware (install: npm install morgan)
const morgan = require("morgan");
app.use(morgan("dev")); // logs: GET /api/users 200 5.2 ms

Custom Middleware

// Request logger
function logger(req, res, next) {
  const start = Date.now();
  res.on("finish", () => {
    const ms = Date.now() - start;
    console.log(`${req.method} ${req.url} ${res.statusCode} ${ms}ms`);
  });
  next();
}

// Auth check middleware
function requireAuth(req, res, next) {
  const token = req.headers.authorization;
  if (!token) {
    return res.status(401).json({ error: "Not authenticated" });
  }
  next();
}

// Apply globally
app.use(logger);

// Apply to specific routes only
app.get("/api/profile", requireAuth, (req, res) => {
  res.json({ message: "Your private profile" });
});

🏋️ Practice Task

Create 3 middleware functions: requestLogger (logs method, url, timestamp), rateLimiter (track requests per IP, reject with 429 if > 10 req/minute), validateJSON (catch JSON parse errors and return 400). Apply all three globally.

💡 Hint: For rateLimiter: use an object {ip: [timestamps]}. Filter timestamps to last 60 seconds. If count > 10, return 429.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *