- Mastering Web Application Development with Express
- Alexandru Vl?du?u
- 299字
- 2021-08-05 17:54:20
Ordering of middleware
Express doesn't know what middleware components do internally, so it doesn't reorder them. The framework doesn't try to be overly smart and do complicated things such as checking whether a function depends on another. This means it's our responsibility to make sure we load them in the proper order.
The most popular example to reflect this is the session and cookie middleware. The session handler uses a cookie as an ID to retrieve the session data, so the cookie parsing must take place in advance. The same dependency relation is between the cross-site request forgery (CSRF) and session middleware, since the first stores its token on the user's session. An example with the correct inclusion of these three middleware components is as follows:
var cookieParser = require('cookie-parser'); var session = require('express-session'); var csrf = require('csurf'); app.use(cookieParser()); app.use(session({ secret: 'random chars here' })); app.use(csrf());
There are other reasons for paying attention to the ordering of middleware besides taking care of dependencies, such as the need for authentication. For example, if only certain white-listed IP addresses are allowed to view a certain page, and the component that's doing the authentication is placed after the one that renders that page, then everyone will be able to bypass the authentication. Actually, a better way to say this is that nobody (no request) would ever reach the authentication layer in the first place.
You might be wondering what is the difference between app.VERB()
and regular middleware loaded with app.use()
. The fact of the matter is that both methods delegate to the router introduced in Express 4 and behave similarly, with a few exceptions, such as the following:
- The path parameter is stripped and not visible to the middleware function for
app.use()
- The
app.VERB()
function accepts multiple callbacks instead of just one