Middleware functions in Express.js are functions that have access to the request object (req
), the response object (res
), and the next
function in the application's request-response cycle. They can execute any code, make changes to the request and response objects, end the request-response cycle, or call the next middleware function in the stack. Express
Application-level Middleware
app.use()
or app.METHOD()
.const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log('Time:', Date.now());
next();
});
Router-level Middleware
express.Router()
.Expressconst express = require('express');
const router = express.Router();
router.use((req, res, next) => {
console.log('Request URL:', req.originalUrl);
next();
});
Error-handling Middleware
(err, req, res, next)
.app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
Built-in Middleware
express.static
, express.json
, and express.urlencoded
.Third-party Middleware
cookie-parser
, morgan
, cors
, etc.Express+1Express+1const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
app.use(cookieParser());
A custom middleware function is a function that takes three arguments: req
, res
, and next
.
const myLogger = function (req, res, next) {
console.log('LOGGED');
next();
};
app.use(myLogger);
This middleware logs "LOGGED" to the console every time a request is received. It's important to call next()
to pass control to the next middleware function. Express+2Express+2Express+2
next()
, the request will be left hanging.next()
, or