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:
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
Important: you need to register the csrf
middleware after your session
and cookieParser
middleware.
var csrf = require('csurf')app.use(csrf())
Inside your route or controller:
res.render('someform', { csrf: req.csrfToken() })
Inside your form:
input(type="hidden", name="_csrf", value="#{csrf}")
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.
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.