Express Middleware
πΉ What is Middleware in Express?
Section titled βπΉ What is Middleware in Express?β- 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().
- Access the request(
- Think of them as layers of functions that request passess through before reaching the final handler.
πΉ Syntax
Section titled βπΉ Syntaxβ app.use((req, res, next) => { console.log('Middleware function executed.'); next(); // Pass control to the next middleware })πΉ Types of Middleware
Section titled βπΉ Types of Middlewareβ-
Application-level Middleware ->
- Attach directly to the Express
appobject. - Eg:
app.use((req, res, next) => {console.log("Application Middleware");next();});
- Attach directly to the Express
-
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.
- Examples:
-
Third Party Middleware ->
- Examples:
morganβ loggingcorsβ handling cross-origin requests.cookie-parserβ parsing cookies.
const cors = require('cors')app.use(cors())
- Examples:
-
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!')})
- Special middleware with 4 parameters
-
π Request Flow: Client β Middleware 1 β Middleware 2 β Route Handler β Response
πΉ When to use Middleware?
Section titled βπΉ When to use Middleware?β- 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.