Book Image

Mastering Web Application Development with Express

By : Alexandru Vladutu
Book Image

Mastering Web Application Development with Express

By: Alexandru Vladutu

Overview of this book

Table of Contents (18 chapters)
Mastering Web Application Development with Express
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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...