Middleware functions are a crucial feature of Express.js. This tutorial will help you understand the purpose and functionality of middleware in Express.js, along with practical examples of implementing and using middleware in your applications.



What is Middleware in Express.js?

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 Middleware

  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().
  5. Third-party middleware: Provided by the community, like Morgan, for logging.

Implementing Middlewares

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
});

// Route handler for the root URL
app.get('/', (req, res) => {
  res.send('Hello, World!');
});

// Start the server
app.listen(3000, () => {
  console.log('The server is running on port 3000.');
});

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();

// Middleware function for router
router.use((req, res, next) => {
  console.log('Request URL:', req.originalUrl);
  next(); // Proceed to the next middleware
});

// Route handler
router.get('/', (req, res) => {
  res.send('Router Middleware');
});

app.use('/router', router); // Apply 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();

// Middleware to trigger an error
app.get('/', (req, res) => {
  throw new Error('BROKEN'); // Express will catch this on its own.
});

// 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();

// Built-in middleware to parse JSON
app.use(express.json());

app.post('/data', (req, res) => {
  res.send(`Received data: ${JSON.stringify(req.body)}`);
});

app.listen(3000, () => {
  console.log('The server is running on port 3000.');
});

Third-Party Middleware

Many third-party middleware is available to add specific functionality to your Express application. Morgan is a popular logging middleware.

Example:

const express = require('express');
const morgan = require('morgan');
const app = express();

// Using third-party middleware for logging
app.use(morgan('combined'));

app.get('/', (req, res) => {
  res.send('Logging with Morgan');
});

app.listen(3000, () => {
  console.log('The server is running on port 3000.');
});

Conclusion

In this tutorial, you learned about the different types of middleware in Express.js, including application-level, router-level, error-handling, built-in, and third-party middleware. Understanding and implementing these middleware functions allows you to build more modular, maintainable, and robust web applications. You will explore these middleware types in more detail in future tutorials.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram