What is Middleware?
Middleware = Functions that run before your route handlers.
Request ──► Middleware ──► Route Handler ──► Response
Example:
┌─────────┐ ┌─────────────┐ ┌──────────────┐ ┌──────────┐
│ Request │───►│ express.json│───►│ GET /products│───►│ Response │
└─────────┘ │ (parse body)│ │ (your code) │ └──────────┘
└─────────────┘ └──────────────┘
Built-in Middleware
1. express.json() - Parse JSON
Parses JSON data from POST/PUT requests:
const express = require('express');
const app = express();
// Enable JSON parsing
app.use(express.json());
app.post('/products', (req, res) => {
console.log(req.body); // { name: "Laptop", price: 999 }
res.json(req.body);
});
⚠️ Important: Without
express.json(), req.body will be undefined!
2. express.static() - Serve Files
Serve HTML, CSS, images from a folder:
// Serve files from 'public' folder
app.use(express.static('public'));
// Now these URLs work:
// http://localhost:3000/index.html
// http://localhost:3000/style.css
// http://localhost:3000/image.png
Custom Middleware
Logger Example
A middleware that logs every request:
const express = require('express');
const app = express();
// Custom logger middleware
function logger(req, res, next) {
console.log(`${req.method} ${req.url}`);
next(); // Continue to next middleware/route
}
// Use the middleware
app.use(logger);
app.get('/', (req, res) => {
res.send('Hello!');
});
app.listen(3000);
// When you visit /, console shows: GET /
💡 Remember: Always call
next() to continue to the next middleware or route!
Middleware Order
Critical Rule: Middleware runs in the order you define it, and runs before your route handlers. The order matters!
📌 Key Concept: Express processes middleware and routes in the order they are registered. If middleware sends a response (like
res.send() or res.json()), the request stops there and never reaches routes defined later.
✅ Correct Order: Middleware Before Routes
const express = require('express');
const app = express();
// 1. Parse JSON (middleware first)
app.use(express.json());
// 2. Logger middleware
app.use((req, res, next) => {
console.log(req.method, req.url);
next(); // Pass request to next middleware/route
});
// 3. Your routes (defined AFTER middleware)
app.get('/products', (req, res) => {
res.json([{ name: 'Laptop' }]);
});
// 4. 404 handler (last - catches unmatched routes)
app.use((req, res) => {
res.status(404).json({ error: 'Not found' });
});
app.listen(3000);
Request Flow (for GET /products):
Request ──► express.json() ──► Logger ──► GET /products route ──► Response
✅ All middleware runs, then the route handler executes
Request ──► express.json() ──► Logger ──► GET /products route ──► Response
✅ All middleware runs, then the route handler executes
❌ Wrong Order: Routes Before Middleware (Problematic!)
Watch what happens when you define routes before middleware that should protect them:
const express = require('express');
const app = express();
// ⚠️ Route defined FIRST - runs BEFORE middleware below
app.get('/products', (req, res) => {
res.json([{ name: 'Laptop' }]);
// Route handler sends response and stops - middleware below NEVER runs!
});
// ⚠️ Authentication middleware defined AFTER route
app.use((req, res, next) => {
// This middleware will NEVER run for /products because the route above already handled it!
if (!req.headers.authorization) {
res.status(401).json({ error: 'Unauthorized' });
return;
}
next();
});
// This route WILL be protected by auth middleware (because it's defined after)
app.get('/admin', (req, res) => {
res.json({ message: 'Admin data' });
});
app.listen(3000);
⚠️ Problem: When you visit
✅ Route handler executes immediately (middleware hasn't run yet)
✅ Response is sent
❌ Auth middleware is SKIPPED - never runs!
❌
When you visit
✅ Auth middleware runs first (it's defined before this route)
✅ Then route handler runs (if auth passes)
Result: Inconsistent behavior! Some routes are protected, others aren't.
GET /products:✅ Route handler executes immediately (middleware hasn't run yet)
✅ Response is sent
❌ Auth middleware is SKIPPED - never runs!
❌
/products is not protected!When you visit
GET /admin:✅ Auth middleware runs first (it's defined before this route)
✅ Then route handler runs (if auth passes)
Result: Inconsistent behavior! Some routes are protected, others aren't.
🚨 Critical Example: Middleware Stops Request Before Routes
Here's what happens when middleware that stops requests is defined before routes:
const express = require('express');
const app = express();
// Authentication middleware defined FIRST - runs BEFORE all routes
app.use((req, res, next) => {
if (!req.headers.authorization) {
// Stop here - send response, don't call next()
res.status(401).json({ error: 'Unauthorized' });
return; // Request STOPS here - routes below NEVER reached!
}
next(); // Only continue if authorized
});
// Routes defined AFTER middleware - only reached if middleware calls next()
app.get('/products', (req, res) => {
// This ONLY runs if auth middleware called next()
res.json([{ name: 'Laptop' }]);
});
app.get('/admin', (req, res) => {
// This ALSO only runs if auth middleware called next()
res.json({ secret: 'Secret data' });
});
app.listen(3000);
Request Flow (without authorization header):
Request ──► Auth Middleware (stops, sends 401) ──► ❌ Routes NEVER reached
Request Flow (with authorization header):
Request ──► Auth Middleware (calls next()) ──► Route Handler ──► Response ✅
Request ──► Auth Middleware (stops, sends 401) ──► ❌ Routes NEVER reached
Request Flow (with authorization header):
Request ──► Auth Middleware (calls next()) ──► Route Handler ──► Response ✅
💡 Key Point: All routes defined after middleware that doesn't call
next() will never be reached if that middleware handles the request. This is why order matters!
🔍 How Requests Pass Through Middleware
Understanding next() vs. sending a response:
Request Flow Through Middleware Chain:
Request comes in
↓
Middleware 1:
↓
Middleware 2:
↓
❌ Middleware 3: Never reached
❌ Route Handler: Never reached
Request comes in
↓
Middleware 1:
next() called → Continue↓
Middleware 2:
res.send() called → STOP! Response sent↓
❌ Middleware 3: Never reached
❌ Route Handler: Never reached
const express = require('express');
const app = express();
// Middleware 1: Always calls next() - passes request along
app.use((req, res, next) => {
console.log('Middleware 1: Request received');
next(); // ✅ Continue to next middleware
});
// Middleware 2: Sometimes stops the request
app.use((req, res, next) => {
if (req.path === '/blocked') {
console.log('Middleware 2: Blocking request');
res.status(403).json({ error: 'Blocked!' });
// ❌ No next() called - request STOPS here
return;
}
console.log('Middleware 2: Passing request');
next(); // ✅ Continue to next middleware/route
});
// Middleware 3: Only reached if Middleware 2 calls next()
app.use((req, res, next) => {
console.log('Middleware 3: Only runs if previous middleware called next()');
next();
});
// Route: Only reached if ALL middleware above called next()
app.get('/allowed', (req, res) => {
console.log('Route handler: Finally reached!');
res.json({ message: 'Success' });
});
app.listen(3000);
// Test scenarios:
// GET /allowed → Middleware 1 → Middleware 2 (passes) → Middleware 3 → Route Handler ✅
// GET /blocked → Middleware 1 → Middleware 2 (stops) → ❌ Middleware 3 never runs, Route never reached
💡 Key Rules:
next()= "Continue to the next middleware/route"res.send()/res.json()/res.status().send()= "Send response and STOP - don't continue"- If middleware sends a response without calling
next(), the request chain stops - Routes defined after middleware that stops requests will never be reached
✅ Best Practice: Proper Order
const express = require('express');
const app = express();
// 1. Setup middleware FIRST (parsing, logging, etc.)
app.use(express.json());
app.use((req, res, next) => {
console.log(req.method, req.url);
next();
});
// 2. Define your routes
app.get('/products', (req, res) => {
res.json([{ name: 'Laptop' }]);
});
// 3. Error/404 handlers LAST (catch unmatched routes)
app.use((req, res) => {
res.status(404).json({ error: 'Not found' });
});
app.listen(3000);
🎯 Key Takeaways:
- Middleware runs before routes - Define middleware first, then routes
- Order matters! Middleware executes in the order you register it
next()= Pass request to next middleware/route- No
next()afterres.send()= Stop the request chain - Routes after middleware that stops requests will never be reached
express.json()- Parse JSON bodyexpress.static('folder')- Serve files