Middleware function Execution Problem and Solution
Tags: webdev, javascript, programming, middleware
Published: 2024-07-01 17:43:40

What is Middleware?
A middleware can be defined as a function that will have all the access for requesting an object, responding to an object, and moving to the next middleware function in the application request-response cycle. Middleware stand as a bridge between client requests and server responses. It's also responsible for handling tasks like logging, authentication, error handling and so on.


Middleware Problem
middleware problem i encountered make me understand how middleware flow works, while developing a Node.js application with Express, authentication middleware was not working because the functions were not executed in a proper way, the logging  was not capturing necessary information and the error handling was not consistent


Solution to the Problem 
firstly, you need to identify the cause of middleware execution issues and the order in which the middleware functions were declared in the application. middleware is a bridge between incoming request and the response that is why we call it request-response cycle below is a version of middleware setup in server.js;

const express = require('express');
const app = express();
const authMiddleware = require('./middlewares/auth');
const errorHandler = require('./middleware/errorHandler');
const Routes = require('./routes/contactRoutes');
const userRoutes = require('./routes/userRoutes');
const { getContacts,createContact, getContact, deleteContact, updateContact } = require('./controller/contactController');
const router = require('./routes/userRoutes');

const port = process.env.PORT || 5000;

app.use(express.json());
app.use(express.urlencoded({extended:true}));

app.use('/api/v1/contact',Routes);
app.use('/api/v1/user',userRoutes);
app.use(errorHandler)

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

note: To make all this work properly You would have installed all the necessary packages in Node.js including express, dotenv, etc.


The Authentication Middleware was used to check for a valid JWT and handle unauthorized access for example let say we have admin routes whereby only admin can perform some functions like get the list of all the contacts, delete contact or update contact. if all the 3 routes mention can only be access by admin then a user will be denied access because he/she don't have access to those routes.

const jwt = require('jsonwebtoken');

const authMiddleware = (req, res, next) => {
    const token = req.headers['authorization'];
    if (!token) {
        return res.status(401).json({ message: 'Access denied. No token provided.' });
    }

    try {
        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        req.user = decoded;
        next();
    } catch (err) {
        res.status(400).json({ message: 'Invalid token.' });
    }
};

module.exports = authMiddleware;


Error Handling Middleware
Is used to catch and response to errors efficiently
below is a code for error handling;

const errorMiddleware = (err, req, res, next) => {
    console.error(err.message);
    res.status(500).json({ message: 'Internal Server Error' });
};

module.exports = errorMiddleware;

In conclusion,
i make sure the middleware function were executed in a correct order to improve the performance of my application and improve my experience in knowledge of web applications. As i start my internship journey at HNG Tech Limited I'm eager to tackle new challenges and continue to grow as a backend developer

This article is in fulfillment of my stage 0 task for the HNG Internship. HNG Internship is a program to educate, contribute to growth and give opportunity to learning tech. Check them out for more information, https://hng.tech/internship, https://hng.tech/hire, or https://hng.tech/premium