Bytes

Middleware in Express JS

Introduction

In the world of web development, there is a key component that plays a vital role in how applications function: middleware. Middleware acts as a bridge between different parts of a web application, helping to facilitate communication and data exchange. It's the unsung hero that allows your favorite websites and apps to run smoothly behind the scenes. In this lesson, we'll dive into the world of middleware and explore its role in the popular web framework, Express.js. We'll cover everything from built-in middleware to third-party options, as well as error handling and security middleware. Get ready to take your understanding of web development to the next level with an introduction to middleware.

Understanding middleware in Express.js

Middleware in Express.js refers to a series of functions that are executed in sequence during the handling of a client request. These functions have access to the request and response objects, allowing them to modify or inspect the request data, perform some processing, and pass control to the next function in the middleware chain.

Types of middleware in Express.js

There are two types of middleware in Express.js: application-level middleware and router-level middleware.

Application-level middleware is used to process requests for the entire application and is registered using the app.use() method. Examples of application-level middleware include logging middleware, authentication middleware, and error handling middleware.

Router-level middleware, on the other hand, is used to process requests for a specific route or set of routes and is registered using the router.use() method. Examples of router-level middleware include middleware that validates input data, middleware that restricts access to certain routes, and middleware that caches responses.

Creating custom middleware in Express.js

One of the powerful features of middleware in Express.js is the ability to create custom middleware functions. These functions can be used to add any functionality that your application needs, such as authentication, logging, or error handling.

Custom middleware functions in Express.js are created using a function that takes three arguments: the request object, the response object, and the next() function. The next() function is called to pass control to the next middleware function in the chain. Here's an example of a custom middleware function that logs the request URL and passes control to the next middleware function:

function logRequest(req, res, next) {
  console.log(`Request made to ${req.url}`);
  next();
}

Built-in middleware in Express.js

Express.js provides a number of built-in middleware functions that can be used to add common functionality to your application. These middleware functions can be added to your application using the app.use() method. In this section, we'll explore some of the most commonly used built-in middleware options in Express.js.

Express.js static middleware

The static middleware is used to serve static files such as images, CSS files, and JavaScript files. It is used to serve files from a directory using the express.static() method. Here's an example of how to use the static middleware to serve static files from a directory named public:

app.use(express.static('public'));

Express.js body-parser middleware

The body-parser middleware is used to parse the request body and make it available on the req.body property. It supports parsing of different types of data such as JSON, URL-encoded, and raw data. It is added to your application using the body-parser package. Here's an example of how to use the body-parser middleware to parse JSON data:

const bodyParser = require('body-parser');

app.use(bodyParser.json());

Express.js cookie-parser middleware

The cookie-parser middleware is used to parse cookies from the request headers and make them available on the req.cookies property. It is added to your application using the cookie-parser package. Here's an example of how to use the cookie-parser middleware:

const cookieParser = require('cookie-parser');

app.use(cookieParser());

Express.js session middleware

The session middleware is used to store session data on the server and make it available on the req.session property. It is added to your application using the express-session package. Here's an example of how to use the session middleware:

const session = require('express-session');

app.use(session({
  secret: 'mySecretKey',
  resave: false,
  saveUninitialized: true
}));

In this section, we've covered some of the most commonly used built-in middleware options in Express.js. However, there are many other built-in middleware functions available, and you can also create custom middleware functions to add any functionality that your application needs.

Third-party middleware in Express.js

In addition to built-in middleware, there are many third-party middleware functions available for Express.js. These middleware functions can be added to your application using the app.use() method, just like built-in middleware. In this section, we'll explore some popular third-party middleware options in Express.js.

Morgan

Morgan is a popular logging middleware for Express.js that logs incoming requests and outgoing responses. It provides various pre-defined logging formats and allows you to define your own custom logging format. Here's an example of how to use the Morgan middleware:

const morgan = require('morgan');

app.use(morgan('combined'));

Helmet

Helmet is a collection of security middleware functions for Express.js. It helps secure your application by setting various HTTP headers, such as Content Security Policy, X-XSS-Protection, and X-Frame-Options. Here's an example of how to use the Helmet middleware:

const helmet = require('helmet');

app.use(helmet());

Compression

The Compression middleware is used to compress the response body before sending it to the client. It helps reduce the size of the response and speeds up page load times. Here's an example of how to use the Compression middleware:

const compression = require('compression');

app.use(compression());

CORS

CORS (Cross-Origin Resource Sharing) middleware is used to enable cross-origin resource sharing for your application. It allows your application to make requests to a different domain or port. Here's an example of how to use the CORS middleware:

const cors = require('cors');

app.use(cors());

These are just a few examples of the many third-party middleware options available for Express.js. When choosing third-party middleware, make sure to check the documentation and verify that the package is up-to-date and actively maintained.

Error handling middleware in Express.js

Error handling middleware is used to handle errors that occur during the execution of middleware functions or route handlers in Express.js. When an error occurs, Express.js will look for error-handling middleware functions defined after the middleware or route handler that threw the error.

Here's an example of an error-handling middleware function that logs the error and sends a 500 Internal Server Error response to the client:

app.use(function (err, req, res, next) {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

Security middleware in Express.js

Security is an important consideration when building web applications, and Express.js provides several built-in and third-party security middleware functions that can help secure your application. In this section, we'll explore some common security middleware options in Express.js.

Express-rate-limit

The Express-rate-limit middleware is used to limit the number of requests made to your application in a given time period. This helps prevent brute force attacks and other types of attacks that involve making a large number of requests to your application.

const rateLimit = require("express-rate-limit");

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100 // limit each IP to 100 requests per windowMs
});

app.use(limiter);

In this example, we're limiting each IP address to 100 requests per 15-minute window.

Express-mongo-sanitize

The Express-mongo-sanitize middleware is used to prevent MongoDB query injection attacks by removing or sanitizing certain characters from user input.

const mongoSanitize = require('express-mongo-sanitize');

app.use(mongoSanitize());

Express-validator

The Express-validator middleware is used to validate user input and prevent security vulnerabilities caused by invalid input. It provides several validation functions, such as checking for empty input, validating email addresses, and checking for valid URLs.

const { body, validationResult } = require('express-validator');

app.post('/login', 
  body('username').notEmpty(),
  body('password').notEmpty(),
  (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    // Some code to handle login
  }
);

In this example, we're using the body() function to validate the username and password fields of a login form. If there are any validation errors, we're returning a 400 Bad Request response with the error messages.

These are just a few examples of the many security middleware functions available for Express.js. When building your application, make sure to consider the security risks and choose appropriate middleware functions to help secure your application.

Conclusion

Middleware plays a crucial role in Express.js by allowing developers to add functionality to their applications without modifying the core logic. It provides a flexible and modular way to handle requests and responses, making it easier to write maintainable and scalable code. By choosing appropriate middleware functions, developers can improve the security, performance, and functionality of their applications. Overall, understanding and effectively using middleware is essential for developing robust and reliable web applications with Express.js.

Module 6: Express.js – A Node.js Web FrameworkMiddleware in Express JS

Top Tutorials

Related Articles

AlmaBetter
Made with heartin Bengaluru, India
  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • 4th floor, 315 Work Avenue, Siddhivinayak Tower, 152, 1st Cross Rd., 1st Block, Koramangala, Bengaluru, Karnataka, 560034
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2024 AlmaBetter