How to write middleware for Express.js
Last Updated: August 18, 2017
Before telling you about anything, I will show you the middleware
function logger(req,res,next){ console.log(new Date(), req.method, req.url); next(); }
This will tell you about middleware
- Middleware is a function.
- It has access to response and request object.
- It has access to the next middleware function in request-response life cycle.
- Execute any code.
- Make changes to the request and the response objects.
- End the request-response cycle.
- Call the next middleware function in the stack.
Simple to understand the middleware, right?
Now lets look at how to implement the following middleware chain. I am going to define two middleware and route handler
const express = require('express') const app = express() const port = 3000 function hello(req,res,next){ console.log("Hello there !") next(); } function logger(req,res,next){ console.log("I am inside logger") next(); } app.use(hello) app.use(logger) app.get('/', (request, response) => { console.log("I am in Handler") response.send('Hello from Express!') }) app.listen(port, function () { console.log('Example app listening on port 3000!') })
Now run your server
$ node server.js
Open the http://localhost:3000
from your browser
You will see this output in your server terminal
$ node server.js Example app listening on port 3000! Hello there ! I am insise logger I am in Handler
app.use
: This is how you define your middleware. A function with a signature of(req, res, next)
is passed to thisapp.use
function. First paramater isrequest
, second parameter is response and the third one isnext
.next()
is used to call the next middleware in the chain or route handler- First middleware
hello
just print the “Hello there !” and call the next middleware logger - Second middleware
logger
just print the “I am inside logger” and call the route handler