Understanding and Utilizing Middleware in Node.js and Express.js

Middleware is a crucial concept in Express.js. It resides between the request and response, processing the request and generating the response.

In Express.js applications, middleware interrupts the processing flow for a request, allowing tasks to be executed. This enables easy implementation of tasks such as preprocessing, post-processing, logging, authentication, and error handling.

Example of a Simple Middleware

Middleware in Express.js can be written as follows.

By using app.use(myMiddleware), it gets executed every time a request arrives. It logs 'middleware get!' to the console after receiving the request and then calls the next() function.

Utilizing middleware enables effective management of various operations related to requests.

middleware

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

const myMiddleware = (req, res, next) => {
    console.log('middleware get!');
    next();
};

app.use(myMiddleware);

app.get('/', (req, res) => {
    res.send('Express.js Middleware');
});

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

Middleware Function for Authentication Verification

User authentication middleware is commonly used. It verifies whether the user is logged in before a request enters a specific route and redirects to the login page if not.

Checking the code of authMiddleware, it confirms user authentication and redirects to the '/login' path if the user is not logged in.

Examining the code in app.js, the 'requireAuth' middleware has been applied to the /profile route.

When a user attempts to access the /profile page, the 'requireAuth' middleware checks the user's login status,

and if not logged in, redirects them to the login page.

authMiddleware

const requireAuth = (req, res, next) => {
    const isAuthenticated = checkUserAuthentication(req);

    if (!isAuthenticated) {
        return res.redirect('/login');
    }
    next();
};

const checkUserAuthentication = (req) => {
    return req.session.isAuthenticated;
};

module.exports = requireAuth;

app.js

const express = require('express');
const app = express();
const requireAuth = require('./authMiddleware');

app.get('/profile', requireAuth, (req, res) => {
    res.send('profile Page');
});

app.get('/login', (req, res) => {
    res.send('login Page');
});

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