Max SchmittMS
30th April 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.

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

3. Pass the csrf-token to your view

Inside your route or controller:

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

4. Create a hidden input inside your view

Inside your form:

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.

Image of my head

About the author

Hi, I’m Max! I'm a fullstack JavaScript developer living in Berlin.

When I’m not working on one of my personal projects, writing blog posts or making YouTube videos, I help my clients bring their ideas to life as a freelance web developer.

If you need help on a project, please reach out and let's work together.

To stay updated with new blog posts, follow me on Twitter or subscribe to my RSS feed.