Ready to Fly?✈️ Middleware in Express.js is Your Boarding Pass!🎫

Ready to Fly?✈️ Middleware in Express.js is Your Boarding Pass!🎫

Imagine your web app as a passenger at an airport. Just like a flight passenger has to pass through several checkpoints before boarding the plane, an HTTP request has to pass through several "middlewares" before getting a response.

Let’s walk through what happens at an airport (Express app), with various middlewares at play!

Flying from "Express Airlines" 🛬🤩

When you arrive at the airport (the request comes in), there are multiple steps before you board the plane (response). Let's break it down:

  1. Check-in Counter (First Middleware): ✈️
    The check-in desk checks your ticket and ID (checking if the request has the correct data, maybe validating inputs).

  2. Security Checkpoint (Second Middleware): 🔍
    Before you board, you pass through security. They ensure you're not carrying anything illegal (authentication middleware, checking if the user is authorized).

  3. Baggage Scan (Third Middleware): 🧳
    Your bags are scanned. This ensures you aren’t carrying anything harmful (another layer of validation or maybe even logging the request for security reasons).

  4. Gate Check (Final Middleware): 🛫
    Finally, before you get on the plane, the staff checks your boarding pass one more time (final check to send a response or let the request proceed).

Now, let’s see this in code!

Middleware as Airport Checkpoints

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

// First Middleware: Check-in Counter ✈️
app.use((req, res, next) => {
  console.log('Checking in passenger...');
  req.checkedIn = true;
  next(); // Proceed to the next step
});

// Second Middleware: Security Check 🔍
app.use((req, res, next) => {
  console.log('Security check...');
  if (!req.checkedIn) {
    return res.status(400).send('Please check in first.');
  }
  req.clearedSecurity = true;
  next();
});

// Third Middleware: Baggage Scan 🧳
app.use((req, res, next) => {
  console.log('Scanning baggage...');
  if (!req.clearedSecurity) {
    return res.status(403).send('Security clearance required.');
  }
  req.baggageScanned = true;
  next();
});

// Final Middleware: Gate Check 🛫
app.get('/', (req, res) => {
  if (req.checkedIn && req.clearedSecurity && req.baggageScanned) {
    res.send('Boarding completed, enjoy your flight!');
  } else {
    res.status(400).send('You missed a step in the process.');
  }
});

app.listen(3000, () => {
  console.log('Airport server running on port 3000...');
});
  • Check-in Counter (First Middleware):
    When the passenger arrives, they check in and the checkedIn flag is set to true. This middleware is like input validation (are you a valid passenger?).

  • Security Checkpoint (Second Middleware):
    The passenger must clear security. Here, we check if they’ve been checked in. If not, they are denied access (similar to checking authentication, like "Is this user logged in?").

  • Baggage Scan (Third Middleware):
    Their baggage is scanned. If they pass security, we scan the bags and add a baggageScanned flag. This could represent an extra layer of data validation or even logging in to a real app.

  • Gate Check (Final Middleware):
    Finally, the passenger must pass the gate check. If they’re checked in, cleared security, and have their bags scanned, they can board the plane (send the response). If any step fails, they don’t get on the plane (response with an error).

What We Learned

  • Middleware Flow: Just like at an airport, every request in Express passes through multiple checkpoints (middleware).

  • Middleware Responsibility: Each checkpoint (middleware) checks something specific and either sends you on to the next step or stops you.

  • Next Function: Middleware calls next() to move the request along, just like how airport staff lets you pass to the next step.

Next time you fly ✈️, think of all those middleware functions that help you safely get to your destination. Happy coding, and safe travels! 🌍✈️

Did you find this article valuable?

Support Dev Station by becoming a sponsor. Any amount is appreciated!