2.2 Examples
Different type of middleware is shown below.
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?
- Every request logs the method and URL.
next()
ensures that the request proceeds to the next handler.
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?
- The
express.json()
middleware automatically parses incoming JSON data and makes it available inreq.body
.
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?
- This middleware parses the data sent via HTML forms and makes it available in
req.body
.
extended
option β whatβs the difference?
The extended
option controls how the incoming data is parsed.
β
extended: true
- Uses the
qs
library, which can parse nested objects. - Example:
Becomes:
Terminal window name=John&details[age]=30{ name: 'John', details: { age: '30' } }
β extended: false
- Uses the
querystring
library, 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)
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?
- The
checkAuth
middleware checks theAuthorization
header 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
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?
- When an error is thrown in the
/error
route, itβs passed to the error-handling middleware. - The error-handling middleware logs the error and sends a
500
status code with a message.
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?
- Files inside the
public
folder are served directly when requested. - For example,
public/images/logo.png
will be available at/images/logo.png
.
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?
- The middleware logs when the
/admin
route is accessed. - Only the
/admin
route uses this middleware, not others.
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?
- CORS middleware allows requests from different origins (domains).
- In this case, itβs enabling cross-origin requests from any domain.