Express js Middleware

Middlewares are different types of functions that have access to the req objectres object and the next middleware function in the application’s request-response cycle.

Basically, middlewares are used to handle and modify the req and res object or pass control to the next middleware function according to the conditions.


In the below example, we are checking through middleware that if the password is equal to 123 then a user can access the home page otherwise not.


const express = require('express');
const app = express();
// app.use() is used to apply a middleware
(req, res, next) => {
    let password = req.query.password;
    // if password is equal to 123 then call next();
    if(password == 123) next();
    res.send('Invalid Password. You can't access the home page.');

app.get('/', (req, res) => {
    res.send('Welcome to the Home Page.');

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

Now run the index.js file by running node index command.



Browser Output
Invalid Password. You can’t access the home page.


Browser Output
Welcome to the Home Page.

In the Express JS, there are some types of middleware –

Next is – Express JS Cookie

Previous is – Template Engines

Leave a Reply

Your email address will not be published. Required fields are marked *