Skip to main content

Archive

Show more

Node.js Middleware in Express.js

Node.js Middleware in Express.js

Middleware functions are a key concept in Express.js that allow you to execute code during the request-response cycle. Middleware functions have access to the request object (req), the response object (res), and the next middleware function in the application's request-response cycle.


1. Writing Middleware Functions

You can define middleware functions in Express.js using the app.use() method. Middleware functions can perform tasks such as logging, authentication, data parsing, error handling, and more.

Example:

// Logger middleware function
const loggerMiddleware = (req, res, next) => {
    console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
    next(); // Call the next middleware function
};

// Register middleware function
app.use(loggerMiddleware);

In this example, the logger middleware function logs the incoming request method and URL to the console before calling the next middleware function in the stack.


2. Using Middleware for Authentication

You can use middleware functions for authentication by verifying user credentials or tokens before allowing access to protected routes.

Example:

// Authentication middleware function
const authMiddleware = (req, res, next) => {
    const token = req.headers.authorization;
    if (!token || token !== 'valid_token') {
        return res.status(401).send('Unauthorized');
    }
    next(); // Call the next middleware function
};

// Secure route using authentication middleware
app.get('/api/protected', authMiddleware, (req, res) => {
    res.send('Protected route accessed');
});

In this example, the auth middleware function checks for a valid token in the request header. If the token is missing or invalid, it responds with a 401 Unauthorized status.


3. Error Handling Middleware

Error handling middleware functions are used to catch and handle errors that occur during the request-response cycle.

Example:

// Error handling middleware function
const errorHandlerMiddleware = (err, req, res, next) => {
    console.error('Error:', err);
    res.status(500).send('Internal Server Error');
};

// Register error handling middleware
app.use(errorHandlerMiddleware);

In this example, the errorHandlerMiddleware function logs the error to the console and responds with a 500 Internal Server Error status.


4. Conclusion

Middleware functions in Express.js provide a powerful mechanism for extending and customizing the behavior of your web applications. Whether you're implementing logging, authentication, data validation, or error handling, middleware functions offer a flexible and modular approach to handling requests and responses.

Comments