Author - StudySection Post Views - 4 views

Understanding Middleware in Express.js: Application, Router, Built-in & Error Handling

Middleware in Express.js is a function that sits between the request and response, allowing you to process, modify, or handle requests before sending back a response.

Types of Middleware in Express.js

When building applications with Express.js, requests don’t go straight from the client to the server’s response. Instead, they pass through special functions called middleware. These are checkpoints for a request. At each checkpoint, you can validate data, log details, add extra information, or even stop the request if needed. This makes middleware an essential part of controlling how your app behaves.

Let’s discuss the main types of middleware in Express.js.

1. Application-level Middleware

  • Attached directly to the Express app.
  • Runs for every request unless restricted to specific routes.
  • Common uses: logging, authentication, and parsing data.

Example:

app.use((req, res, next) => {
   console.log('Request Time:', Date.now());
   next(); // pass control
 });

2. Router-level Middleware

  • This works similarly to application-level middleware, but applied to a Router instance.
  • When you want to apply middleware for a specific group of routes, you can use these middleware.

Example:

const router = express.Router();
 router.use((req, res, next) => {
   console.log('Router Middleware Active');
   next();
 });
 app.use('/users', router);

3. Built-in Middleware

  • Express has some middleware already built in.
  • Common ones:
    • express.json() → Parse JSON data.
    • express.urlencoded() → Parse form data.
    • express.static() → Serve static files.

Example:

app.use(express.json());
app.use(express.static('public'));

4. Error-handling Middleware

  • Special type for catching and handling errors.
  • Must have four parameters (err, req, res, next).
  • Always placed at the end of all routes/middleware.
app.use((err, req, res, next) => {
   console.error('Error:', err.message);
   res.status(500).send('Something went wrong!');
 });

5. Third-party Middleware

  • Created by the community and installed from npm.
  • Saves time by adding extra features easily.

Popular examples:

  • morgan → Logs HTTP requests.
  • cookie-parser → Parses cookies.
  • cors → Handles cross-origin requests.

Example:

const morgan = require('morgan');
 app.use(morgan('tiny'));

Summary
Middleware is the backbone of Express.js.

  • Use application-level middleware for global tasks.
  • Use router-level middleware for specific route groups.
  • Rely on built-in middleware for common needs like JSON and static files.
  • Add error-handling middleware to catch issues gracefully.
  • Install third-party middleware to extend functionality.

By mastering these types, you can make your Express.js apps more flexible, maintainable, and powerful.

Leave a Reply

Your email address will not be published. Required fields are marked *

fiteesports.com rivierarw.com cratosroyalbet betwoon grandpashabet grandpashabet giriş deneme bonusu veren siteler casino siteleri