🍃 Middleware In Express🍃

🍃 Middleware In Express🍃

All You Need to Know About Express JS Middleware

Express app is usually a web framework that consists of middleware and a router. Therefore, an express application works through a series of middleware functions.

This series is the continuation of my series on the basics of NodeJS and ExpressJS. If you don't have basic knowledge of NodeJS read this series first: Introduction to NodeJS😁

This Express Middleware article explains all that a developer must know about middleware with respect to Express.js

Let’s dive 🤗 deeper starting with an understanding of what middleware is in general.

What is Middleware🤔

Middleware in Node.js are functions that a request goes through before reaching its designated endpoint, each middleware function has access to request and response objects and after performing the assigned task on the request it calls the next function passing the function further in the pipeline😵.

Don't be afraid 😵‍💫about what is next() I will be explaining it further in the article so keep reading😉.

If we would break🤓 this definition into points:

  1. As the name suggests it comes in the middle of something and that is the request and response cycle.
  2. Middleware has access to request and response object.
  3. Middleware has access to the next function of request-response life cycle♻️.

The middleware sits in between🤓 the request and response

user request -> midlleware -> response

MIDDLEWARE.png

Developers can write any number of middleware depending on the application, middleware functions are typically used for sanitizing inputs, logging purposes, authentication, parsing data in the request body, etc.

What is next()?👩‍🍳

Middleware can be assumed as a group of functions whenever a request has been made to the server. Well, since it is a group of functions,

how is the order in which they execute decided? 🤔

and

how will the execution flow be maintained?🤔

☝️Firstly, the order of execution is decided by the order of loading of functions. For a basic code, we will just load the functions in app.get().

Here is a simple example →

app.get('/', authenticate, log_data, update_req);

Now the ordering of middleware functions is decided authenticate(), log_data() and then update_req().

But how will the flow of execution go from one middleware function to another?🤔

Well, this is when the next() function comes into the picture🥳.

A middleware function typically receives three👌 arguments: req , res and next . next is the next function which will be executed after the current one.

Request.png

In Short🤏 The next() continues the chain of the series of functions known as middleware. next is the third👌 parameter in the middleware function and needs to be explicitly called at the end of the operation executed inside the function as express has no way to understand when the function has come to the end of execution of current operation and the next method in the series needs to be invoked, therefore, next() method needs to be called🤠.

Tasks it performs

If we want to block our site for some country or if we're going to check the authentication of a user etc., we use middleware for that

Middleware function can perform the following tasks:

  • Execute any code.
  • Update🌓 the request and the response objects.
  • End the request-response cycle For example, if there is any exception that is thrown, instead of calling the next method in the series of middleware, it can end the chain.
  • Call🤙 the next middleware in the stack.

The flow of middleware could be as follows:

Request received by server and send by client.png

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.

Why use middleware?🤫

On most websites, any time you interact with the browser, it requests information from a web server. The web server then sends a response back to the browser which it then converts and shows it to you as text, image, video, etc.

When the web server receives a request, Express ( a web-application server framework for node.js ) gives you a request object where you can see the data they are requesting along with some user details such as IP address, browser language, passed parameters, etc. Express also gives you access to a response object. These objects are usually shortened to req , res😲 .

Types of Middleware💢

There are various types of middleware functions and they all have various use cases!🧐

  • ☝️Application-level middleware:

This kind of middleware method is bound to the app Object using app.use() method.

For example:

app.use(function (req, res, next) {
  console.log('Current Time:', Date.now())
  next()
})
  • 👌Router-level middleware:

Router-level middleware works in the same way as application-level middleware, except it is bound to an instance of express.Router().

const router = express.Router()

Load router-level middleware by using the router.use() and router.METHOD() functions.

  • 🖖Error-handling middleware:

Express JS comes with default error handling params, define error-handling middleware functions in the same way as other middleware functions, except error-handling functions, have 🖖four arguments instead of three:

app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})
  • 🖐️Built-in middleware:

Starting with version 4.x, there is only one built-in middleware which is express.static.

app.use(express.static(path.join(__dirname, 'public')));

This middleware function is based on serve-static and is responsible for loading static assets such as HTML files, images, and so on.

The function signature is:

express.static(root, [options])

Here, the root is the directory name and options are several options.

  • 6️⃣ Third-party middleware:

There are a number of third-party middleware, such as body-parser.mongoose, morgan and so on. These can be installed by using the command:

npm install <module name>

And they can be loaded using requires and used later😉.

For example:

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }))

Conclusion ♟️

Middleware is a great tool to organize your code 🙂to work in the request-response cycle. It is basically a function that has access to the req and res objects of your application.

It can be thought of as a series 🏁of tasks that the developer performs before the request is handled by the application. You can code your own middleware functions or use built-in or 3rd party functions.

Middleware functions are important in writing clean, functional & reusable code!

I hope this article helps you better understand express middleware functions!😊

Happy Learning!🥰🥰

Did you find this article valuable?

Support Chhakuli Zingare by becoming a sponsor. Any amount is appreciated!