The essential purpose of the csurf
middleware is to block incoming requests that include a payload (such as body parameters) without a valid token. Here's an example of how you can implement it:
app.use(require('body-parser')());
app.use(require('cookie-parser')('YOUR SECRET GOES HERE'));
app.use(require('express-session')());
app.use(require('csurf')());
app.get('/some-form', function(req, res){
res.send('<form action="/process" method="POST">' +
'<input type="hidden" name="_csrf" value="' + req.csrfToken() + '">' +
'Favorite color: <input type="text" name="favoriteColor">' +
'<button type="submit">Submit</button>' +
'</form>');
});
app.post('/process', function(req, res){
res.send('<p>Your favorite color is "' + req.body.favoriteColor + '".');
});
If you remove or alter the req.csrfToken()
, you will notice that the form stops functioning correctly.
Keep in mind that using sessions is crucial for the proper operation of csurf
. To understand why csurf
is necessary, refer to the Wikipedia page on cross-site request forgery (CSRF).