Max Schmitt

April 30 2014

Tutorial: CSRF for Express 4.x

Things have changed a bit since Express 3, so many tutorials on this subject are now out-of-date for Express 4.

To add CSRF-protection to your forms in your Express-app, here is what you can do:

1. Install the "csurf"-module

express.csrf is no longer part of the core Express framework and has been extracted into its own node module called "csurf", so we need to pull that in.

npm install csurf

2. Add the csurf middleware to your Express app

Important: you need to register the csrf middleware after your session and cookieParser middleware.

JS

var csrf = require('csurf')
app.use(csrf())

3. Pass the csrf-token to your view

Inside your route or controller:

JS

res.render('someform', { csrf: req.csrfToken() })

4. Create a hidden input inside your view

Inside your form:

PUG

input(type="hidden", name="_csrf", value="#{csrf}")

You're done!

Your Express forms are now protected from CSRF. As always, there are multiple ways to go about this task. You might want to setup some custom middleware that automatically adds the csrf-token to your res.locales or you might want to only register the csrf middleware before specific routes.