2.2 Examples
Different type of middleware is shown below.
1. π§βπ» Basic Logging Middleware
Section titled β1. π§βπ» Basic Logging MiddlewareβLogging middleware captures each incoming request and logs the HTTP method and URL.
const express = require('express');const app = express();
// Basic logging middlewareapp.use((req, res, next) => { console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`); next(); // Pass to the next middleware or route handler});
// Sample routeapp.get('/', (req, res) => { res.send('Hello, World!');});
app.listen(3000, () => { console.log('Server running on port 3000');});What happens?
Section titled βWhat happens?β- Every request logs the method and URL.
next()ensures that the request proceeds to the next handler.
2. π§βπ» JSON Body Parsing Middleware
Section titled β2. π§βπ» JSON Body Parsing MiddlewareβWhen handling requests with JSON data, we need express.json() to parse the body and make it available as req.body.
const express = require('express');const app = express();
app.use(express.json()); // Middleware to parse JSON bodies
app.post('/data', (req, res) => { console.log(req.body); // The parsed JSON data res.send('Received JSON data');});
app.listen(3000, () => { console.log('Server running on port 3000');});What happens?
Section titled βWhat happens?β- The
express.json()middleware automatically parses incoming JSON data and makes it available inreq.body.
3. π§βπ» URL-Encoded Form Data Parsing Middleware
Section titled β3. π§βπ» URL-Encoded Form Data Parsing MiddlewareβFor handling application/x-www-form-urlencoded data (like HTML form submissions), use express.urlencoded().
const express = require('express');const app = express();
app.use(express.urlencoded({ extended: true })); // Middleware to parse form data
app.post('/form', (req, res) => { console.log(req.body); // Parsed form data res.send('Received form data');});
app.listen(3000, () => { console.log('Server running on port 3000');});What happens?
Section titled βWhat happens?β- This middleware parses the data sent via HTML forms and makes it available in
req.body.
extended option β whatβs the difference?
Section titled βextended option β whatβs the difference?βThe extended option controls how the incoming data is parsed.
β
extended: true
Section titled ββ
extended: trueβ- Uses the
qslibrary, which can parse nested objects. - Example:
Becomes:
Terminal window name=John&details[age]=30{ name: 'John', details: { age: '30' } }
β extended: false
Section titled ββ extended: falseβ- Uses the
querystringlibrary, which only parses flat key-value pairs. - Same example:
Becomes:
Terminal window name=John&details[age]=30{ name: 'John', 'details[age]': '30' }
4. π§βπ» Authentication Middleware (Custom Middleware)
Section titled β4. π§βπ» Authentication Middleware (Custom Middleware)βYou can create custom middleware for authentication. Hereβs a simple one that checks for an Authorization header.
const express = require('express');const app = express();
// Custom authentication middlewarefunction checkAuth(req, res, next) { const authHeader = req.headers['authorization']; if (!authHeader || authHeader !== 'Bearer mysecrettoken') { return res.status(401).send('Unauthorized'); } next(); // Proceed to the next middleware/route}
app.use('/private', checkAuth); // Apply to all routes under /private
app.get('/private/data', (req, res) => { res.send('Private Data: You are authorized!');});
app.listen(3000, () => { console.log('Server running on port 3000');});What happens?
Section titled βWhat happens?β- The
checkAuthmiddleware checks theAuthorizationheader in the request. - If the header is missing or incorrect, it sends a 401 Unauthorized error.
- If the header is valid, it allows the request to continue.
5. π§βπ» Error Handling Middleware
Section titled β5. π§βπ» Error Handling MiddlewareβExpress allows you to create custom error-handling middleware. Itβs used to catch errors from route handlers or other middleware.
const express = require('express');const app = express();
// Sample route that throws an errorapp.get('/error', (req, res, next) => { const error = new Error('Something went wrong!'); next(error); // Pass error to the error handler});
// Custom error-handling middlewareapp.use((err, req, res, next) => { console.error(err.stack); // Log the error res.status(500).send('Something went wrong!');});
app.listen(3000, () => { console.log('Server running on port 3000');});What happens?
Section titled βWhat happens?β- When an error is thrown in the
/errorroute, itβs passed to the error-handling middleware. - The error-handling middleware logs the error and sends a
500status code with a message.
6. π§βπ» Static File Serving Middleware
Section titled β6. π§βπ» Static File Serving MiddlewareβYou can use express.static() to serve static files (like images, CSS, or JavaScript files) in your app.
const express = require('express');const path = require('path');const app = express();
// Middleware to serve static filesapp.use(express.static(path.join(__dirname, 'public')));
// Example routeapp.get('/', (req, res) => { res.send('<h1>Home Page</h1><img src="/images/logo.png" alt="Logo">');});
app.listen(3000, () => { console.log('Server running on port 3000');});What happens?
Section titled βWhat happens?β- Files inside the
publicfolder are served directly when requested. - For example,
public/images/logo.pngwill be available at/images/logo.png.
7. π§βπ» Route-Specific Middleware
Section titled β7. π§βπ» Route-Specific MiddlewareβMiddleware can be applied to specific routes only.
const express = require('express');const app = express();
// Route-specific middlewareapp.get('/admin', (req, res, next) => { console.log('Admin route accessed'); next(); // Proceed to the next route handler}, (req, res) => { res.send('Welcome to the Admin Page');});
app.listen(3000, () => { console.log('Server running on port 3000');});What happens?
Section titled βWhat happens?β- The middleware logs when the
/adminroute is accessed. - Only the
/adminroute uses this middleware, not others.
8. π§βπ» Middleware for Performance (CORS)
Section titled β8. π§βπ» Middleware for Performance (CORS)βCORS (Cross-Origin Resource Sharing) middleware helps handle cross-origin requests.
const express = require('express');const cors = require('cors');const app = express();
// Enable CORS for all routesapp.use(cors());
// Sample routeapp.get('/data', (req, res) => { res.json({ message: 'Data from server' });});
app.listen(3000, () => { console.log('Server running on port 3000');});What happens?
Section titled βWhat happens?β- CORS middleware allows requests from different origins (domains).
- In this case, itβs enabling cross-origin requests from any domain.