Express.js is a web application framework for Node.js, designed for building web applications and APIs. One of its core features is 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. These functions can execute code, modify the request and response objects, end the request-response cycle, and call the next middleware function.
Middleware functions can perform the following tasks:
If the current middleware function does not end the request-response cycle, it must call next()
to pass control to the next middleware function. Otherwise, the request will be left hanging.
Application-level middleware is bound to an instance of the app
object using app.use()
or app.METHOD()
, where METHOD
is the HTTP method (GET, POST, etc.).
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log('Time:', Date.now());
next();
});
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
app.use()
is used to define middleware that logs the current timestamp for every request.next()
function is called to pass control to the next middleware function in the stack.http://localhost:3000/
, the console will log the current timestamp, and the browser will display “Hello World!”.Router-level middleware works in the same way as application-level middleware, except it is bound to an instance of express.Router()
.
const express = require('express');
const app = express();
const router = express.Router();
router.use((req, res, next) => {
console.log('Router Time:', Date.now());
next();
});
router.get('/', (req, res) => {
res.send('Hello from Router!');
});
app.use('/router', router);
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
router.use()
is used to define middleware for the router instance./router
.http://localhost:3000/router
, the console will log the router timestamp, and the browser will display “Hello from Router!”.Error-handling middleware functions have four arguments: (err, req, res, next).
const express = require('express');
const app = express();
app.get('/', (req, res) => {
throw new Error('Oops!');
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
http://localhost:3000/
, the console will log the error stack, and the browser will display “Something broke!”.Express comes with built-in middleware functions like express.static()
, express.json()
, and express.urlencoded()
.
const express = require('express');
const app = express();
app.use(express.json());
app.post('/user', (req, res) => {
res.send(`User name is ${req.body.name}`);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
express.json()
middleware parses incoming JSON requests and puts the parsed data in req.body
.http://localhost:3000/user
with JSON { "name": "John" }
will respond with “User name is John”.There are many third-party middleware functions for Express, such as morgan
for logging and body-parser
for parsing request bodies.
const express = require('express');
const morgan = require('morgan');
const app = express();
app.use(morgan('dev'));
app.get('/', (req, res) => {
res.send('Morgan Logger Example');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
morgan('dev')
logs HTTP requests in a concise format.http://localhost:3000/
logs the request details in the console.Custom middleware functions can be created by defining a function that takes req
, res
, and next
as arguments.
const express = require('express');
const app = express();
const customMiddleware = (req, res, next) => {
console.log('Custom Middleware');
next();
};
app.use(customMiddleware);
app.get('/', (req, res) => {
res.send('Hello from Custom Middleware!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
next()
.http://localhost:3000/
logs “Custom Middleware” and displays “Hello from Custom Middleware!”.The order of middleware is important. Middleware functions are executed sequentially.
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log('First Middleware');
next();
});
app.use((req, res, next) => {
console.log('Second Middleware');
next();
});
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
http://localhost:3000/
logs “First Middleware” followed by “Second Middleware”.Middleware is a powerful feature of Express.js, allowing developers to modularize and organize their code. Understanding how to create and use middleware functions is essential for building scalable and maintainable web applications.By leveraging different types of middleware, you can handle various aspects of your application, such as logging, authentication, error handling, and more. Custom middleware functions enable you to implement specific functionality tailored to your application's needs.Happy coding !❤️