Express Middleware

Build request pipelines that validate, transform, authorize, and terminate requests.

Lesson content

🎯 Goal By the end of this lesson, you'll understand: What is Middleware? Why do we use Middleware? How Middleware works Types of Middleware Built-in Middleware Custom Middleware Real-world examples Interview questions What is Middleware? Middleware is a function that executes between the client request and the server response . It can: Read the request Modify the request Execute code End the request Pass control to the next middleware Simple Definition: Middleware is a function that runs before the request reaches the route handler . Why Do We Need Middleware? Middleware is commonly used for: Authentication Authorization Logging Validation Error Handling Parsing Request Body Real-Life Example 🚪 Imagine entering a company. Visitor │ ▼ Security Check │ ▼ Reception │ ▼ Office Security Check = Middleware Office = Route Handler How Middleware Works Client Request │ ▼ Middleware 1 │ ▼ Middleware 2 │ ▼ Route Handler │ ▼ Response Basic Middleware const express = require ( "express" ); const app = express (); app . use(( req , res , next ) => { console . log( "Middleware Executed" ); next (); }); app . get( "/" , ( req , res ) => { res . send( "Home Page" ); }); app . listen( 3000 ); Output Middleware Executed Home Page What is next() ? next() passes control to the next middleware or route handler. app . use(( req , res , next ) => { console . log( "Before Route" ); next (); }); Without calling next() (or sending a response), the request will remain pending. Request Flow Client │ ▼ Middleware │ next() │ ▼ Route │ ▼ Response Built-in Middleware express.json() Parses JSON request bodies. app . use( express . json()); Example Request { "name": "Ajay" } You can access it using: req . body . name express.urlencoded() Parses HTML form data. app . use( express . urlencoded({ extended: true })); express.static() Serves static files. app . use( express . static( "public" )); Folder Structure project/ │ ├── public/ │ ├── logo.png │ └── style.css Now: http://localhost:3000/logo.png Custom Middleware function logger ( req , res , next ) { console . log( ` ${ req . method} ${ req . url} ` ); next (); } app . use( logger ); Output GET / Route-Level Middleware function auth ( req , res , next ) { console . log( "Authentication Successful" ); next (); } app . get( "/profile" , auth , ( req , res ) => { res . send( "Profile" ); }); Only /profile uses this middleware. Multiple Middleware app . use(( req , res , next ) => { console . log( "Middleware 1" ); next (); }); app . use(( req , res , next ) => { console . log( "Middleware 2" ); next (); }); app . get( "/" , ( req , res ) => { res . send( "Done" ); }); Output Middleware 1 Middleware 2 Done Types of Middleware Type Purpose Application Middleware Runs for the entire application Route Middleware Runs for specific routes Built-in Middleware Provided by Express Third-party Middleware Installed using npm (e.g., cors , morgan ) Error Middleware Handles application errors Error Middleware app . use(( err , req , res , next ) => { res . status( 500 ) . json({ message: err . message }); }); Error-handling middleware always has 4 parameters : (err, req, res, next) . Middleware Flow Client │ ▼ Logger Middleware │ ▼ Authentication Middleware │ ▼ Validation Middleware │ ▼ Route Handler │ ▼ Response Real-Life Example 🏦 ATM Transaction Insert Card │ ▼ PIN Verification │ ▼ Balance Check │ ▼ Withdraw Cash Each step acts like middleware before the final action. Interview Question What is Middleware? Answer Middleware is a function that executes between the request and response cycle. It can modify the request/response, execute code, end the request, or pass control using next() . What happens if next() is not called? Answer If the middleware neither calls next() nor sends a response, the request will hang and the client will not receive a response. Best Practices ✅ Keep middleware focused on one responsibility. ✅ Use express.json() for JSON APIs. ✅ Place authentication middleware before protected routes. ✅ Handle errors using error-handling middleware. ❌ Don't forget to call next() if the middleware should continue processing. Key Points ✅ Middleware runs before the route handler. ✅ next() passes control to the next middleware or route. ✅ Express provides built-in middleware like express.json() , express.urlencoded() , and express.static() . ✅ Middleware can be application-level, route-level, built-in, third-party, or error-handling. ✅ Error middleware requires four parameters: (err, req, res, next) . 🧠 Easy Formula Client Request │ ▼ Middleware 1 │ next() │ ▼ Middleware 2 │ next() │ ▼ Route Handler │ ▼ Response app.use() → Application Middleware express.json() → Parse JSON express.urlencoded()→ Parse Form Data express.static() → Serve Static Files next() → Go to Next Middleware Remember: 🚪 Middleware = Runs before the route handler 🔄 next() = Continue to the next middleware 📦 express.json() = Parse JSON requests 🚀 Middleware is used for logging, authentication, validation, error handling, and much more.