Implementing Middleware in Express.js for Short Videos

Posted by

Using middleware in express.js

Using middleware in express.js

Express.js is a popular web application framework for Node.js. One of the key features of Express.js is its use of middleware to handle requests and responses. Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. Middleware functions can perform various tasks such as logging, authentication, error handling, etc.

Here’s an example of how to use middleware in Express.js:


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

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

        // Authentication middleware
        app.use((req, res, next) => {
            if (req.headers.authorization === 'secrettoken') {
                next();
            } else {
                res.status(401).send('Unauthorized');
            }
        });

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

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

In the above example, we have defined two middleware functions before the route handler. The first middleware function logs the request method and URL, and then calls the next middleware function. The second middleware function checks for the presence of an authorization header with a specific token, and either calls the next middleware function or sends a 401 Unauthorized response.

Middleware functions can also be used to handle errors. If a middleware function calls the next() function with an argument (typically next(err)), Express.js will skip all remaining middleware and route handlers and call the error handling middleware:


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

Using middleware in Express.js allows for modular and reusable code, and makes it easy to add additional functionality to your application’s request-response cycle.

So next time you’re building a web application with Express.js, don’t forget to leverage the power of middleware!