Adding middleware in Express in Node.js


Each request in app goes through multiple middleware’s in express. If one of the middleware returns the response it ends there. If any middleware wants to pass the request to next middleware, it uses next() function call at the end of its function call.

Http Request -> Middleware (req, resp, next)-> Middleware(req, res, next)-> Http Response ( res.send() ).

const http = require('http');
const express = require('express');
const app = express();
app.use((req, res,next)=>{
   console.log('first middleware');
});
const server = http.createServer(app);
server.listen(3000);

Middleware’s are added using use function as shown above. Use() function receives three arguments basically request, response and next() function.

The use() function are added before the server create function. Now for adding second middleware −

Running app −

Open browser and navigate to localhost:3000

On terminal console, we will see log messages −

In the first middleware, we used next() function call to pass the http request to next middleware in call stack. Middleware’s generally works as they are defined the file.

Sending response from middleware

Express provides a send() function to return any type of response e.g. html, text etc. we can still use the old write function as well. Here we don’t requires to set header, express will automatically does that.

app.use((req, res,next)=>{
   console.log('second middleware');
   res.send('<h1> Hello Tutorials Point </h1>');
});

Nodemon will auto restart app on code change −

By default the content type is text/html in express.js . We can override the default header value by using response.setHeader() function.

If we remove next() function call in first middleware −

const http = require('http');
const express = require('express');
const app = express();
app.use((req, res,next)=>{
   console.log('first middleware');
   //next();
   res.send('<h1> first midleware: Hello Tutorials Point </h1>');
});
app.use((req, res,next)=>{
   console.log('second middleware');
   res.send('<h1> second middleware: Hello Tutorials Point </h1>');
});
const server = http.createServer(app);
server.listen(3000);

Note we commented next() function call in first middleware

So our http request will not reach second middleware and we see response from first middleware only.

Updated on: 13-May-2020

265 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements