CSRF token middleware


Node.js CSRF protection middleware.

Requires either a session middleware or cookie-parser to be initialized first.

If you have questions on how this module is implemented, please read Understanding CSRF.

$ npm install csurf
var csurf = require('csurf')

Create a middleware for CSRF token creation and validation. This middleware adds a req.csrfToken() function to make a token which should be added to requests which mutate state, within a hidden form field, query-string etc. This token is validated against the visitor's session or csrf cookie.

The csurf function takes an optional options object that may contain any of the following keys:

Determines if the token secret for the user should be stored in a cookie (when set to true or an object, requires a cookie parsing module) or in req.session (when set to false, provided by another module). Defaults to false.

When set to an object, cookie storage of the secret is enabled and the object contains options for this functionality (when set to true, the defaults for the options are used). The options may contain any of the following keys:

  • key - the name of the cookie to use to store the token secret (defaults to '_csrf').
  • path - the path of the cookie (defaults to '/').
  • any other res.cookie option can be set.

An array of the methods for which CSRF token checking will disabled. Defaults to ['GET', 'HEAD', 'OPTIONS'].

Provide a function that the middleware will invoke to read the token from the request for validation. The function is called as value(req) and is expected to return the token as a string.

The default value is a function that reads the token from the following locations, in order:

  • req.body._csrf - typically generated by the body-parser module.
  • req.query._csrf - a built-in from Express.js to read from the URL query string.
  • req.headers['csrf-token'] - the CSRF-Token HTTP request header.
  • req.headers['xsrf-token'] - the XSRF-Token HTTP request header.
  • req.headers['x-csrf-token'] - the X-CSRF-Token HTTP request header.
  • req.headers['x-xsrf-token'] - the X-XSRF-Token HTTP request header.

The following is an example of some server-side code that generates a form that requires a CSRF token to post back.

var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')
// setup route middlewares 
var csrfProtection = csrf({ cookie: true })
var parseForm = bodyparser.urlencoded({ extended: false })
// create express app 
var app = express()
// parse cookies 
app.get('/form', csrfProtection, function(reqres) {
  // pass the csrfToken to the view 
  res.render('send', { csrfToken: req.csrfToken() })
app.post('/process', parseForm, csrfProtection, function(reqres) {
  res.send('data is being processed')

Inside the view (depending on your template language; handlebars-style is demonstrated here), set the csrfToken value as the value of a hidden input field named _csrf:

<form action="/process" method="POST">
  <input type="hidden" name="_csrf" value="{{csrfToken}}">
  Favorite color: <input type="text" name="favoriteColor">
  <button type="submit">Submit</button>

When the CSRF token validation fails, an error is thrown that has err.code === 'EBADCSRFTOKEN'. This can be used to display custom error messages.

var bodyParser = require('body-parser')
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var express = require('express')
var app = express()
app.use(bodyParser.urlencoded({ extended: false }))
app.use(csrf({ cookie: true }))
// error handler 
app.use(function (errreqresnext) {
  if (err.code !== 'EBADCSRFTOKEN') return next(err)
  // handle CSRF token errors here 
  res.send('form tampered with')