Express.js middleware: Understanding and building your own

Murat Erkin Çiçek
4 min readJan 27, 2023

--

Express.js Middlewares

Express.js is a popular web framework for Node.js that allows developers to easily create web applications and APIs. One of the key features of Express is its middleware system, which allows developers to add functionality to the request-response cycle in a modular way. In this article, we will explore the basics of Express middleware and how to build your own middleware using Javascript.

First, let’s define what middleware is in the context of Express. Middleware is simply a function that has access to the request, response, and next objects of the application. This function can perform various tasks, such as modifying the request or response, validating data, or even calling the next middleware function in the stack.

There are two types of middleware in Express: application-level middleware and route-level middleware. Application-level middleware is executed on every request, while route-level middleware is only executed when a specific route is matched.

To use middleware in an Express application, you can simply use the app.use() or router.use() method, passing in the middleware function as an argument. For example, the following code adds a middleware function that logs the request method and URL to the console:

app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});

In this example, the middleware function is using the next() function to call the next middleware function in the stack. If you don't call next(), the request-response cycle will not continue and the response will not be sent to the client.

Now, let’s look at how to build your own middleware using Javascript. To start, you will need to create a new file with .js extension. Here's an example of a simple middleware function that checks if the request has a valid token:

function checkToken(req, res, next) {
const token = req.headers['x-access-token'];

if (!token) {
return res.status(401).json({ message: 'No token provided' });
}

// Verify token
// ...

next();
}

This middleware function is using the req.headers object to check if the x-access-token header is present in the request. If it's not, the middleware function returns a 401 status code and a JSON object with an error message. If the token is present, the middleware function can perform additional tasks, such as verifying the token.

To use this middleware function in your application, you can simply import it and use it with the app.use() or router.use() method:

import { checkToken } from './checkToken';

app.use(checkToken);

In this example, the checkToken middleware function will be executed on every request, before the route-level middleware and handlers.

In addition to using middleware globally for all routes using app.use() or router.use(), you can also use middleware for specific routes. This is known as route-level middleware.

To use middleware for a specific route, you can pass the middleware function as an argument to the route-handling method (app.get(), app.post(), etc.). For example, the following code demonstrates how to use the checkToken middleware function only for the /secure route:

app.get('/secure', checkToken, (req, res) => {
res.json({ message: 'Access granted' });
});

In this example, the checkToken middleware function will be executed before the route handler for the /secure route. If the token is not valid, the middleware function will return an error and the route handler will not be executed.

You can also chain multiple middleware functions for a specific route. For example, the following code demonstrates how to use both checkToken and log middleware functions for the /secure route:

app.get('/secure', checkToken, log, (req, res) => {
res.json({ message: 'Access granted' });
});

In this example, the checkToken middleware function will be executed first, followed by the log middleware function, and finally the route handler.

It’s important to note that the order in which you specify the middleware functions matters. The middleware functions will be executed in the order in which they are specified.

It is also possible to use middleware for multiple routes using router.use() method, which allows you to specify a path or route pattern. For example, the following code demonstrates how to use the checkToken middleware function for all routes that start with /api:

const router = express.Router();
router.use('/api', checkToken);
app.use('/', router);

In this example, the checkToken middleware function will be executed for all routes that start with /api, such as /api/users and /api/items.

In conclusion, Express middleware is a powerful feature that allows developers to add functionality to the request-response cycle in a modular way. By understanding the basics of middleware and how to build your own middleware using Javascript, you can create more robust and maintainable Express applications.

Don’t forget to follow for more. Thank you for reading!

--

--

Murat Erkin Çiçek
Murat Erkin Çiçek

Written by Murat Erkin Çiçek

Full Stack Developer and Javascript lover. GitHub: @murerkinn

No responses yet