Create Your Own Middleware For Expressjs

post-title

Middlwares are most important in any web application. You can perform logging, authentication and various micro to large tasks based on requested route.

In express.js, its easy to use a middleware. You just have to create a function that will accept request,response,next(req,res,next) that will be passed by express.

Here’s a quick guide on how to create authentication middleware.

Create Express app

// filename: index.js
const express = require('express')
const app = express();

// Import authentication middleware
const { auth } = require('./middleware/auth')

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

// Specify the route in which authentication middleware must be used.
app.get('/login', auth, (req, res) => {
    res.send('Logged in');
});

app.get('/home', (req, res) => {
    res.send('Homepage')
})

app.listen(3001);

Here we are creating an express app are 2 routes. /login will use the auth middleware and /home will not.

Create middlware

Now create the middleware function that you imported in index.js

Create a folder middleware and create a file named as auth.js in that folder.

async function auth(req, res, next) {
    // Perform authentication
    /**
     * Check if user is logged in or not.
     * If JWT token is not present then send to login page.
     * For this article we will assume a constant username and password
     */
    const username = 'jamesbond';
    const password = 'jiochJD$8#^';
   
    if (req.headers.username == username && req.headers.password == password) {
        next();
    } else {
        res.send('Invalid username or password');
    }
}
module.exports = {
    auth
}

Here we are going to have a constant username & password which our user must specify in request headers. Username and password is declared as:

    const username = 'jamesbond';
    const password = 'jiochJD$8#^';

Next we will grab username & password from headers and if it matches with constants then we will allow user or reject.

if (req.headers.username == username && req.headers.password == password) {
        next();
    } else {
        res.send('Invalid username or password');
    }

To grab the headers from a request use req.headers.headerName. By replacing headerName you can get the headers that are passed by the users. To get list of all headers present in a request use console.log(req.headers). This will print all headers that are present in a request.

By line req.headers.username == username && req.headers.password == password we will verify that both passed username and passwords are same. If its true then process will move to app.get('/login') to perform the tasks that you have written there and this is done by next(). You user next() in a middleware to pass the execution flow to middleware caller. If you don’t user next() then execution will stay and end in the middleware.

Now if username or password is wrong then we will send a message to user in the else block.

else {
        res.send('Invalid username or password');
    }

In else block we won’t use the next()because if user has given wrong details then we don’t want to execute the part of app.get('/login').

Note: Later on you must change the middleware to verify login details from a database.

Add Headers in Postman

Now lets add headers to postman.

Open postman and enter URL http://localhost:3001/login

Goto headers tab and enter username as jamesbond & password as jiochJD$8#^. These 2 must be same as the one you entered in middlware.

cupofcode.dev postman headers

Testing

Now test the application you just built rocket

Run node app by node index.js

In postman after you have filled the URL and headers then click Send button.

If you have entered the correct username and password you will see the response in postman as Logged in otherwise it will be Invalid username or password


This was just a small demo of how middleware works and can be used in express.js To futher extend this app, update the middleware to search for username & password in database and redirect to routes according to that.