Skip to main content

Explain middleware in the context of Express.js.

 In Express.js, middleware refers to functions that are executed during the lifecycle of a request-response cycle. Middleware functions have access to the request (req) and response (res) objects, as well as the next function that allows you to pass control to the next middleware function in the stack.

Explain middleware in the context of Express.js.

Middleware can be used for various purposes such as:

  • Processing incoming requests (parsing body data, handling authentication)

  • Logging requests

  • Handling errors

  • Serving static files

  • Modifying request/response objects

How Middleware Works in Express

Express processes middleware in a stack, meaning that each middleware function is executed sequentially, one after the other, in the order they were defined. Each middleware function has three arguments:

  1. req: The request object, which contains the HTTP request data (headers, body, query parameters, etc.).

  2. res: The response object, which allows you to send a response back to the client.

  3. next: A function that, when called, passes control to the next middleware function. If not called, the request will hang.

Basic Syntax for Middleware in Express

app.use((req, res, next) => { console.log('Middleware function executed'); next(); // Call next() to pass control to the next middleware });

Types of Middleware in Express

  1. Application-Level Middleware
    This type of middleware is bound to the Express app and can handle requests for all routes or specific routes.

    const express = require('express'); const app = express(); // Global middleware for all routes app.use((req, res, next) => { console.log('Request received!'); next(); }); app.get('/', (req, res) => { res.send('Hello, world!'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); });

    Specific Route Middleware:


    // Middleware for a specific route app.use('/about', (req, res, next) => { console.log('About page accessed!'); next(); }); app.get('/about', (req, res) => { res.send('About Us'); });
  1. Router-Level Middleware
    This middleware is bound to a specific instance of express.Router() and only runs for routes handled by that router.

    const express = require('express'); const app = express(); const router = express.Router(); router.use((req, res, next) => { console.log('Router-level middleware executed'); next(); }); router.get('/home', (req, res) => { res.send('Home page'); }); app.use('/page', router); app.listen(3000, () => { console.log('Server is running on port 3000'); });
  2. Built-in Middleware
    Express comes with some built-in middleware functions. For example:

    • express.json(): Parses incoming requests with JSON payloads.

    • express.urlencoded(): Parses incoming requests with URL-encoded data.

    • express.static(): Serves static files (images, CSS, JavaScript).

    Example:

    app.use(express.json()); // To parse incoming JSON data app.use(express.static('public')); // To serve static files from 'public' folder
  1. Error-Handling Middleware
    This is a special type of middleware used to handle errors. It takes four arguments: err, req, res, and next.

    Example:

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

    This middleware is added after all other middleware functions and routes, and it's triggered if an error occurs anywhere during the request handling process.

Example of Using Middleware in an Express App

Here's a more complete example that uses multiple middleware functions:

const express = require('express'); const app = express(); // Middleware to log the request method and URL app.use((req, res, next) => { console.log(`${req.method} ${req.url}`); next(); // Call the next middleware or route handler }); // Built-in middleware to parse JSON bodies app.use(express.json()); // Custom middleware for authentication app.use((req, res, next) => { if (!req.headers.authorization) { return res.status(403).send('Forbidden'); } next(); // If authorized, pass to the next middleware or route }); // Route for getting user information (protected by the authentication middleware) app.get('/user', (req, res) => { res.send('User data'); }); // Error-handling middleware app.use((err, req, res, next) => { console.error(err); res.status(500).send('Something went wrong!'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); });

When to Use Middleware

Middleware is useful in various scenarios, including but not limited to:

  • Request logging (e.g., logging each request for debugging or analytics)

  • Authentication and authorization (e.g., checking if a user is logged in or has permission)

  • Data parsing (e.g., parsing JSON or form data)

  • Static file serving (e.g., serving images, CSS, and JS files)

  • Error handling (e.g., catching and handling errors in your app)

Order of Middleware Execution

Middleware functions in Express are executed in the order they are defined, so the order in which you declare them matters. For example, if you declare an authentication middleware after a route handler, it will never be executed because the request is already responded to by the route.

Popular posts from this blog

How does BGP prevent routing loops? Explain AS_PATH and loop prevention mechanisms.

 In Border Gateway Protocol (BGP), preventing routing loops is critical — especially because BGP is the inter-domain routing protocol used to connect Autonomous Systems (ASes) on the internet. ๐Ÿ”„ How BGP Prevents Routing Loops The main mechanism BGP uses is the AS_PATH attribute . ๐Ÿ” What is AS_PATH? AS_PATH is a BGP path attribute that lists the sequence of Autonomous Systems (AS numbers) a route has traversed. Each time a route is advertised across an AS boundary, the local AS number is prepended to the AS_PATH. Example: If AS 65001 → AS 65002 → AS 65003 is the route a prefix has taken, the AS_PATH will look like: makefile AS_PATH: 65003 65002 65001 It’s prepended in reverse order — so the last AS is first . ๐Ÿšซ Loop Prevention Using AS_PATH ✅ Core Mechanism: BGP routers reject any route advertisement that contains their own AS number in the AS_PATH. ๐Ÿ” Why It Works: If a route makes its way back to an AS that’s already in the AS_PATH , that AS kno...

What’s the impact of BGP full routes on router memory and performance?

Receiving full BGP routes (i.e., the full global BGP routing table) has a significant impact on a router's memory and performance. Here's a breakdown of the key impacts: ๐Ÿ”ง 1. Memory Usage (RAM) A full BGP table typically contains ~1 million IPv4 routes and growing (~200k+ IPv6 routes). Each BGP route consumes tens to hundreds of bytes of memory, depending on attributes (AS path, communities, etc.). This translates to hundreds of megabytes to several gigabytes of RAM just for storing the BGP RIB (Routing Information Base). The FIB (Forwarding Information Base) , which is installed into the router's hardware or kernel for actual packet forwarding, also consumes memory (especially in TCAM for hardware routers). ❗ Example A router might require 4–8 GB of RAM (or more) to comfortably handle full BGP routes with headroom for growth and stability. ๐Ÿง  2. CPU Utilization High CPU load during: Initial BGP session establishment (parsing all rout...

Explain the OSPF LSDB (Link State Database) and how SPF (Shortest Path First) algorithm works.

OSPF (Open Shortest Path First) is a link-state routing protocol , and the LSDB (Link-State Database) and SPF (Shortest Path First) algorithm are core to how OSPF calculates the best paths . Let’s break them down. ๐Ÿง  What is the OSPF LSDB (Link-State Database)? The LSDB is a map of the entire OSPF network area — each router stores a complete topology of its area. ๐Ÿ” Details: Built from LSAs (Link-State Advertisements) exchanged between routers. Contains info about: Routers and their interfaces Network segments Neighbor relationships Each OSPF router maintains an identical LSDB within the same area. ✅ Key Characteristics: Feature Description Scope One LSDB per OSPF area Source Built from received LSAs Consistency All routers in an area have identical LSDBs Purpose Used as input for SPF algorithm to calculate best paths ⚙️ How the SPF Algorithm Works in OSPF OSPF uses Dijkstra’s Shortest Path First (SPF) algorithm to compute the shortest (lowest-cost)...