I'm working with Nodejs and using expressjs and now I'm looking into middleware functionality and I'm wondering what's the "next" job in middleware concepts? "Next into next middleware", but what is "next middleware"? I tried using the following code and whenever I hit "http://localhost:3000/" then it shows "Middleware 1 and Middleware 2" in console and browser "hello world" is always displayed, so "next middleware" always means "router handler" (get method)?
const express = require('express'); const app = express(); // Middleware function 1 app.use((req, res, next) => { console.log('Middleware 1'); next(); // Move to the next middleware }); // Middleware function 2 app.use((req, res, next) => { console.log('Middleware 2'); next(); // Move to the next middleware }); // Route handler app.get('/', (req, res) => { res.send('Hello, world!'); }); app.listen(3000, () => { console.log('Server started on port 3000'); });
This is wrong. Next middleware doesn't always mean "router handler". Next() function redirects to another function.
For example, the following example,
Console output:
The response in the browser is
Hello, world!
. Therefore, the next() function is not always meant as a router handler.