Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Middleware in Express.js

Introduction

Middleware in Express.js is a fundamental concept that allows developers to handle requests and responses in a flexible way. Middleware functions can execute any code, make changes to the request and response objects, end the request-response cycle, and call the next middleware function in the stack.

What is Middleware?

Middleware is a series of functions that are invoked by the Express.js framework during the request-response cycle. They can perform a variety of tasks, such as:

  • Executing code
  • Modifying the request and response objects
  • Ending the request-response cycle
  • Calling the next middleware function

Middleware can be applied globally to all routes or locally to specific routes.

Types of Middleware

In Express.js, middleware can be categorized into several types:

  1. Application-level middleware: Defined at the application level and can be used with all routes.
  2. Router-level middleware: Defined for specific routers and used with routes defined in that router.
  3. Error-handling middleware: Defined to handle errors that occur during request processing.
  4. Built-in middleware: Provided by Express.js for common tasks, such as parsing request bodies.
  5. Third-party middleware: Middleware developed by the community that can be added to Express applications.

Creating Middleware

Creating a middleware function in Express.js is straightforward. Here’s a simple example:

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

// Custom middleware function
const myMiddleware = (req, res, next) => {
    console.log('Middleware executed!');
    next(); // Pass control to the next middleware
};

app.use(myMiddleware); // Apply middleware globally

app.get('/', (req, res) => {
    res.send('Hello, World!');
});

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

Using Middleware

Middleware can be used in different ways:

  • Globally with app.use().
  • Locally with app.get(), app.post(), etc.:
  • app.get('/user', myMiddleware, (req, res) => {
        res.send('User Profile');
    });
  • Error-handling middleware should be defined after all other middleware and routes:
  • app.use((err, req, res, next) => {
        console.error(err.stack);
        res.status(500).send('Something went wrong!');
    });

Best Practices

When working with middleware in Express.js, consider the following best practices:

  • Keep middleware functions small and focused.
  • Order middleware functions thoughtfully, as the order of execution matters.
  • Use error-handling middleware to capture errors consistently.
  • Document middleware clearly, especially when used across multiple routes.

FAQ

What is the purpose of middleware?

Middleware serves as a bridge between the request and response in an Express application, allowing for code execution, request/response modification, and error handling.

Can middleware be asynchronous?

Yes, middleware can be asynchronous. You can use async/await within middleware functions, as long as you properly handle errors and call the next function.

How do I skip a middleware function?

You can skip a middleware function by not calling the next() function. However, this should be done cautiously as it will end the request-response cycle.