Node.js & Express
Express Middleware
Understanding Middleware
Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application's request-response cycle. Middleware is the heart of Express.js.
What is Middleware?
Think of middleware as a series of functions that a request passes through before reaching its final destination. Each middleware function can:
- Execute any code
- Make changes to the request and response objects
- End the request-response cycle
- Call the next middleware function in the stack
Analogy: Middleware is like a series of checkpoints. A request travels through each checkpoint (middleware), where it can be inspected, modified, or stopped before reaching the final handler.
Middleware Syntax
const express = require('express');
const app = express();
// Basic middleware structure
app.use((req, res, next) => {
// Do something
console.log('Middleware executed');
// Pass control to the next middleware
next();
});
Critical: Always call
next() unless you're ending the response. Forgetting next() will cause your request to hang indefinitely.
Built-in Express Middleware
Express comes with several built-in middleware functions:
1. express.json() - Parse JSON Bodies
// Parse incoming JSON payloads
app.use(express.json());
app.post('/api/users', (req, res) => {
// Now you can access req.body
console.log(req.body.name);
console.log(req.body.email);
res.json({ message: 'User created', data: req.body });
});
2. express.urlencoded() - Parse URL-Encoded Bodies
// Parse form data (application/x-www-form-urlencoded)
app.use(express.urlencoded({ extended: true }));
app.post('/submit-form', (req, res) => {
console.log(req.body.username);
console.log(req.body.password);
res.send('Form submitted');
});
extended: true vs false:
- true: Uses
qslibrary, supports nested objects - false: Uses
querystringlibrary, simple key-value pairs
3. express.static() - Serve Static Files
// Serve files from 'public' directory
app.use(express.static('public'));
// Multiple static directories
app.use(express.static('public'));
app.use(express.static('uploads'));
// With path prefix
app.use('/static', express.static('public'));
// Now: http://localhost:3000/static/style.css
Custom Middleware
You can create your own middleware functions for logging, authentication, validation, and more.
Simple Logger Middleware
// Custom logger
const logger = (req, res, next) => {
const timestamp = new Date().toISOString();
console.log(`[${timestamp}] ${req.method} ${req.url}`);
next();
};
app.use(logger);
Exercise: Build a Middleware Chain
- Create an Express app with custom middleware for logging, authentication, and validation
- Install and configure CORS, Helmet, and Morgan
- Create protected and public routes
- Add proper error handling middleware
- Test with Postman/Thunder Client