Introduction to middleware

When a frontend client(app) requests specific data from the backend the backend will need to respond with relevant information.

This is the fundamental ideology of frontend and backend web systems.

Midllewear helps you to get the bridge between your frontend request and backend response.

Using the middleware function, we can handle the in-between data and use those values based on our requirements, and also it’s possible to chain as many as much of middleware functions.  

Middleware in Express

We can use the request object as req, the response object res and the next as next() to enable us to modify the request-response cycle.

The next() will end the request and response life cycle and call the next middleware function.

As per the implementation perspective, there are two levels of middleware in express js.  

Application-level middleware

Logger middleware and Error handling middleware are examples of application level middleware

These two middlewares always run at the application level.

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

// Logger middleware
app.use((req, res, next) => {
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
  next();
});

// Error handling middleware
app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).send('Internal Server Error');
});

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

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

 

Router-level middleware

In this example, we use router-level middleware in action.

This Router middleware will run only if this app hit this specific router only.

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

// Router-level middleware
router.use((req, res, next) => {
  console.log('Router middleware');
  next();
});

// Route handler
router.get('/', (req, res) => {
  res.send('Hello, Router!');
});

app.use('/api', router); // Mount the router on '/api'

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

Other than these we can also use plug and use third-party middleware packages as well based on our requirements.

morgan, body-parser, express.static are some of the most used third-party middlewares in express js.

Important: the middleware will execute based on the order that they are declared in the index.js main server file.  

Conclusion

By using middleware in our app we can add our own logic between the request and response life cycle, or we can change the behaviour or end the process and call the next middleware.

Happy learning/coding 😎