Express.js Course
Express.js
/
Beginner

Custom Middleware

Definition

Writing your own custom middleware is incredibly common. It allows you to modularize reusable logic that needs to run before your route handlers. A custom middleware is just a function that accepts `req`, `res`, and `next`.

Explain Like I'm New

Writing your own custom middleware is incredibly common.

Interactive Example

const requireRole = (role) => {
  // Middleware function returning another function (closure)
  return (req, res, next) => {
    const userRole = req.headers['x-role']; // Mocking role extraction
    
    if (userRole === role) {
      next(); // Authorized, proceed to route
    } else {
      res.status(403).json({ error: 'Forbidden. Incorrect Role.' });
    }
  };
};

// app.delete('/users/:id', requireRole('admin'), deleteHandler);

Interview Questions

basic

  • What is the primary purpose of Custom Middleware in Express.js?
  • How do you initialize Custom Middleware?

intermediate

  • How does Custom Middleware integrate with other middleware components?
  • Can you explain a common use case for Custom Middleware?

advanced

  • What are the performance implications of Custom Middleware in a high-traffic production application?
  • How would you debug issues related to Custom Middleware?

trick

  • Is it possible to achieve the same result as Custom Middleware without using Express?

Flash Cards

Question

Define Custom Middleware in your own words.

Click to reveal answer
Answer

Writing your own custom middleware is incredibly common.

Question

When should you avoid using Custom Middleware?

Click to reveal answer
Answer

It depends on the specific architectural requirements and performance bottlenecks of your application. Overusing it can sometimes lead to tightly coupled code.