MIddlewares in Express

 What is Middleware?

Middleware in Express is like a security guard or helper that sits between the request (client) and the response (server). It can modify, check, or handle requests before they reach the final destination (route handler).

const express = require('express');
const app = express();
const port = 3000
const fs = require("fs")

// Middleware function
const logger = (req, res, next) => {
    console.log(`we are inside middleware`);
    next(); // Move to the next middleware or route handler, if next() not written, req stop here..no further execution
};

// Use middleware
app.use(logger);

app.use((req, res, next) => {
    const timestamp = Date.now();  
    const date = new Date(timestamp);
    console.log(date.toString());
    fs.appendFileSync("logs.txt", `${date.toString()} is a ${req.method}\n`)
    console.log(`${date.toString()} is a ${req.method}`)
    next()
})

// Routes
app.get('/', (req, res) => {
    res.send('Hello, this is the Home Page!');
});

app.get('/about', (req, res) => {
    res.send('Welcome to the About Page!');
});

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




In Express.js, middleware functions are used to handle requests and responses in a structured way. Here are five types of middleware in Express:

  1. Application-Level Middleware

    • Defined using app.use() or app.METHOD().
    • Used for tasks like authentication, logging, and request modifications.
    • Example:
      app.use((req, res, next) => {
          console.log('Request received at:', Date.now());
          next();
      });
      
  2. Router-Level Middleware

    • Similar to application-level middleware but only applies to specific routers.
    • Defined using router.use().
    • Example:
      const express = require('express');
      const router = express.Router();
      
      router.use((req, res, next) => {
          console.log('Router Middleware Executed');
          next();
      });
      
      app.use('/api', router);
      
  3. Built-in Middleware

    • Express provides some built-in middleware for common tasks.

    • Examples include:

      • express.json() → Parses incoming JSON requests
      • express.urlencoded({ extended: true }) → Parses URL-encoded form data
      • express.static('public') → Serves static files
      app.use(express.json());
      app.use(express.static('public'));
      
  4. Error-Handling Middleware

    • Handles errors in the application.
    • Defined with four parameters: (err, req, res, next).
    • Example:
      app.use((err, req, res, next) => {
          console.error(err.stack);
          res.status(500).send('Something broke!');
      });
      
  5. Third-Party Middleware

    • Middleware provided by external libraries to add functionalities like authentication, logging, and security.

    • Examples:

      • morgan → Logging requests
      • helmet → Security headers
      • cors → Enable CORS
      const morgan = require('morgan');
      app.use(morgan('dev'));
      

Each middleware plays a crucial role in request processing, security, and performance optimization in an Express application. 🚀















Comments

Popular posts from this blog

Decorators in Pythons | easy way to learn about decorators

Useful Git Commands for Windows

Strings in python: Methods, Operations, and Reversing