Skip to content

Express Middleware

  • Middleware functions in Express is a functions that runs between the incoming request(req) and an outgoing response(res).
  • They can:
    • Access the request(req) and response(res) objects.
    • Modify them.
    • End the request-response cycle.
    • Or pass control to the next middleware using next().
  • Think of them as layers of functions that request passess through before reaching the final handler.
app.use((req, res, next) => {
console.log('Middleware function executed.');
next(); // Pass control to the next middleware
})
  • Application-level Middleware ->

    • Attach directly to the Express app object.
    • Eg:
      app.use((req, res, next) => {
      console.log("Application Middleware");
      next();
      });
  • Router-level Middleware ->

    • Works the same but bounds to an Express router.
    • Eg:
      const router = Router()
      router.use((req, res, next)=>{
      console.log('Router Middleware');
      next();
      })
  • Built-in Middleware ->

    • Examples:
      • express.json() β†’ parse JSON bodies.
      • express.urlencoded({ extended: true }) β†’ parse URL-encoded bodies.
      • express.static('public') β†’ serve static files.
  • Third Party Middleware ->

    • Examples:
      • morgan β†’ logging
      • cors β†’ handling cross-origin requests.
      • cookie-parser β†’ parsing cookies.
      const cors = require('cors')
      app.use(cors())
  • Error Handling Middleware ->

    • Special middleware with 4 parameters (err, req, res, next).
    • Eg:
      app.use((err, req, res, next)=>{
      console.error(err.stack)
      res.status(500).send('Something breaks!')
      })
  • πŸ‘‰ Request Flow: Client β†’ Middleware 1 β†’ Middleware 2 β†’ Route Handler β†’ Response

  • Logging requests (morgan, custom loggers).
  • Authentication/Authorization (check tokens, user roles).
  • Parsing data (JSON, forms, cookies).
  • Error handling (catch errors in routes).
  • Serving static files (images, CSS, JS).
  • Rate limiting / Security checks.