🌐 Web Development

Middleware

Middleware

Software that performs processing between a request and a response. Used for authentication, logging, error handling, and more.

Detailed Explanation

Middleware is a function that runs between a request and a response. It mainly handles common tasks such as authentication, logging, error handling, and data transformation.

Middleware is chained together and runs sequentially, and you must call next() to move on to the next middleware.

Code Example

// Express.js middleware app.use((req, res, next) => { console.log(`${req.method} ${req.url}`); // logging next(); // to the next middleware }); // authentication middleware const authMiddleware = (req, res, next) => { if (!req.headers.authorization) { return res.status(401).json({ error: 'Unauthorized' }); } next(); }; app.get('/api/protected', authMiddleware, (req, res) => { res.json({ data: 'secret' }); });

Practical Conversation Example

Junior

"Do I have to put an if statement in every API to check login?"

Senior

"Create a single middleware and apply it to the router. Pulling common logic out into middleware is the standard practice."

Cautions

Order matters: Middleware runs in the order it is registered. If the authentication middleware comes after the router, it has no effect.

Calling next() is required: If you do not call next(), the request stops.

Related Terms

Learn More