Middleware in Express.js

πŸ“˜ Node.js πŸ‘ 47 views πŸ“… Nov 05, 2025
⏱ Estimated reading time: 2 min

In Express.js, middleware is a function that sits between the client request and the server response.
It can inspect, modify, allow, or stop a request before it reaches the final route handler.


1. What Middleware Does

A middleware function can:

  • Read request data

  • Modify request or response objects

  • Execute code

  • End the request–response cycle

  • Pass control to the next middleware

(req, res, next) => { // middleware logic next(); }

2. How Middleware Works (Flow)

Request β†’ Middleware β†’ Middleware β†’ Route β†’ Response

Each middleware decides whether to:

  • Call next() β†’ continue

  • Send a response β†’ stop the chain


3. Types of Middleware in Express.js


3.1 Application-Level Middleware

Applied to the entire app.

app.use((req, res, next) => { console.log(req.method, req.url); next(); });

3.2 Router-Level Middleware

Applied to specific routes.

const router = express.Router(); router.use((req, res, next) => { console.log('Router middleware'); next(); });

3.3 Built-in Middleware

Provided by Express.

app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use(express.static('public'));

3.4 Third-Party Middleware

Installed using npm.

Examples:

  • morgan – logging

  • cors – enable CORS

  • helmet – security

app.use(require('morgan')('dev'));

3.5 Error-Handling Middleware

Handles errors globally.

app.use((err, req, res, next) => { res.status(500).send('Server Error'); });

⚠ Must have four parameters.


4. Middleware Execution Order

  • Executed in the order they are defined

  • Order matters

  • Error middleware runs only on errors


5. Conditional Middleware

app.use((req, res, next) => { if (req.method === 'POST') { console.log('POST request'); } next(); });

6. Custom Authentication Middleware (Example)

function auth(req, res, next) { if (req.headers.token) { next(); } else { res.status(401).send('Unauthorized'); } } app.get('/secure', auth, (req, res) => { res.send('Protected Route'); });

7. Best Practices

  • Keep middleware small and focused

  • Always call next() when required

  • Place error middleware at the end

  • Avoid heavy logic in middleware


8. Advantages of Middleware

  • Reusable logic

  • Cleaner code

  • Better request control

  • Improved maintainability


9. Summary

  • Middleware processes requests before responses

  • Can modify, block, or pass requests

  • Express supports multiple middleware types

  • Execution order is critical



πŸ”’ Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes