Web II Middleware in Express Lesson012
Web II Middleware in Express Lesson012
Middleware in Express.js refers to functions that have access to the request and
response objects, as well as the next middleware function in the application’s
request-response cycle.
These functions can perform various operations, including executing code,
modifying the request and response objects, terminating the request-response
cycle, handling cookies, logging requests, and passing control to subsequent
middleware functions.
Types of middlewares
1. Application-level middleware: Binds to an instance of the app object.
2. Router-level middleware: Binds to an instance of express.Router().
3. Error-handling middleware: Special middleware that handles errors.
4. Built-in middleware: Provided by Express, such
as express.json() and express.static().
Implementing middleware
Implementing middleware in Express.js involves using app.use() for application-
level middleware and router.use() for router-level middleware. Middleware
functions can be chained and executed sequentially, allowing for complex request
processing and response handling. Error-handling middleware is defined with four
arguments and used after other middleware and route definitions. Express also
provides built-in middleware for common tasks, and you can also utilize third-
party middleware to extend functionality.
Application-level middleware
Application-level middleware is attached to an instance of the app object
through app.use() and app.METHOD(), where the METHOD is an HTTP method.
Example
const express = require('express');
const app = express();
// Application-level middleware
app.use((req, res, next) => {
console.log('Application-level middleware.');
console.log(`Request method: ${req.method}, URL: ${req.url}, Time: $
{Date.now()}`);
next(); // Proceed to the next middleware
});
Router-level middleware
Router-level middleware works like application-level middleware, except it is
bound to an instance of express.Router(). Router-level middleware can be scoped
to specific URL paths within a router.
Example
const express = require('express');
const app = express();
const router = express.Router();
// Route handler
router.get('/', (req, res) => {
res.send('Router Middleware');
});
app.listen(3000, () => {
console.log('The server is running on port 3000.');
});
Error-handling middleware
Error-handling middleware functions have four arguments: (err, req, res, next).
They are defined after other app.use() and route calls.
Example:
const express = require('express');
const app = express();
// Error-handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
app.listen(3000, () => {
console.log('The server is running on port 3000.');
});
Built-in middleware
Express provides built-in middleware to handle common tasks. For
instance, express.json() and express.urlencoded() parse JSON and URL-encoded
data.
Example
const express = require('express');
const app = express();
app.listen(3000, () => {
console.log('The server is running on port 3000.');
});
Server.js
const express = require('express'); // Importing express
const app = express(); // Creating an express app
const homeRoutes =require ('./routes/homeRoutes')
const customMiddleware = require('./middleware/customMiddleware');
// Use routes
app.use('/', homeRoutes);
HomeRoute.js
const express = require('express');
const router = express.Router();
const customMiddleware = require('../middleware/customMiddleware');
customMiddleware.js
// Custom middleware examples
const customMiddleware = {
// Logger middleware to log request details
logger: (req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next();
},
// Authentication check (simple example)
authCheck: (req, res, next) => {
// In a real app, you'd check for a valid token or session
console.log("Authentication check running...");
next();
},
module.exports = customMiddleware;