Middlewares in ExpressJS and How to use them

Middlewares in ExpressJS and How to use them

Middlewares are just functions that have access to the request object (`req`) , the response object (`res`), and the (`next`) middleware function

ยท

4 min read

Introduction

In this article, you're going to learn about middleware in ExpressJS and how to use them, but before that, let's talk about ExpressJS.

What is ExpressJS?

ExpressJS is a flexible NodeJS framework with a set of robust features for building web and mobile applications, though there are other frameworks such as fastify, ExpressJS is still the most popular among them.

Let's take a look at an example,

To create a server without ExpressJS, we will need to write the following code,

// import http module
const http = require('http');
// import url module.
const url=require('url');

const requestListener = function (req, res) {
const reqUrl = url.parse(req.url).pathname;
    if(reqUrl == "/") {
        res.writeHead(200);
  res.end('Hi !');
    }
    else if(reqUrl == "/hello") {
        res.writeHead(200);
  res.end('Hello, World!');
    }

}

// create a server
const server = http.createServer(requestListener);
server.listen(3000);

But with ExpressJS, we would write the following code,

// Import express module;
const express=require('express');

// instantiate an app by calling the express() function
const app=express();

app.get('/', function(req, res){
res.status(200).send('Hi !');
});

app.get('/hello' , function(req, res){
res.status(200).send('Hello World!');
});

app.listen(3000);

You can see that the ExpressJS code is shorter, more readable, and easier to understand, that's one of the advantages of ExpressJS, it does a lot of heavy lifting for us behind the scene.

Now that you know what ExpressJS is, let's talk about middleware.

What are middlewares?

One of the core concepts of ExpressJS are middlewares, but what exactly is a middleware and how do we use it?

Well, Middlewares are just functions that have access to the request object (req) , the response object (res), and the (next) middleware function (often denoted with a variable named next) in the application's request-response cycle.

A middleware function can be used to attain the following tasks,

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware function in the stack.

Note: If you do not want a middleware to end a request-response cycle, you must call this next() function, otherwise the request will be left hanging.

Let's use a real-life example, assuming you're traveling and on your way you get to a police checkpoint, they stop you and ask for your ID card or car papers, once you provide it, they let you go.

That is similar to how middlewares work, although not all middlewares work this way, most custom middlewares are used this way, it waits for certain criteria to be met before calling the next function in the stack.

A middleware can be used with/without a mount path, let's take a look at the types of middlewares with some examples.

There are 5 types of middleware in ExpressJS,

  • Application-level middleware,
  • Router-level middleware
  • Error-handling middleware
  • Built-in middleware, and
  • Third-party middleware.

What's the difference between these middlewares?

Application-level middlewares are middlewares declared at the application's entry file, e.g index.js or app.js and attached to the app object.

Here's an example of an Application-level middleware.

 //  without a mount path

 app.use((req, res, next)=>{
 console.log(req.originalUrl);
 next();
})

 // with a mount path
 // any request to this path will use this middleware

 app.use('/posts/:id', (req, res, next)=>{
 if(req.params.id){
 console.log(req.params.id);
 next();
 }
})

// only a get request to this path will use this middleware

app.get('/posts/:id', (req, res, next)=>{
 if(req.params.id){
 res.send('post with id '+req.params.id);
 next();
 }
})

Router-level middlewares: are middlewares declared on a Router instance, these middlewares are not needed globally, they are only needed at some point.

Here's an example of a Router-level middleware:

const express= require('express');
const router=express.Router();

// without mount path
router.use((req, res, next)=>{
console.log(req.originalUrl)
})

// with a mount path.
// any request to this path will use this middleware

 router.use('/:id', (req, res, next)=>{
 if(req.params.id){
 console.log(req.params.id);
 next();
 }
})

// only a get request to this path will use this middleware

router.get('/:id', (req, res, next)=>{
 if(req.params.id){
 res.send('post with id '+req.params.id);
 next();
 }
})

app.use('/posts', router);

Error-Handling middleware: Error handling middlewares are middlewares used for handling Errors in the application, but unlike other middlewares that accept 3 parameters, an Error middleware must be passed 4 parameters, otherwise ExpressJS would see it as a regular middleware, and no error would be handled,

Here's an example of an Error-handling middleware

app.use((err,req, res, next)=>{
 console.log(err.stack);

})

Built-in middlewares: Built-in middlewares (as the name implies) are those middlewares that are built into ExpressJS, you don't have to create or install them yourself,

Here's an example of a Built-in middleware,

// parses JSON request
app.use(express.json());

// parses URL encoded request
app.use(express.urlencoded())

// allows the usage of static files, e.g images
app.use(express.static())

And lastly,

Third-party middlewares: Third-party middlewares are middlewares built by others, in other for you to use this middleware, you will need to install and then import it into your application.

Here's an example:

const cookieParser=require('cookie-parser');
// parses cookies into an object
app.use(cookieParser());

Conclusion

In this article, you have learned about middleware in ExpressJS, its types, and how to use them.

If you found this article helpful, do give it a thumbs up ๐Ÿ‘ and follow me, so you don't miss out on my next article.

ย