CSRF token middleware
Node.js CSRF protection middleware.
Requires either a session middleware or cookie-parser to be initialized first.
falsevalue, then you must use cookie-parser before this module.
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
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.
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
req.session. Defaults to
When set to
true (or an object of options for the cookie), then the module
changes behavior and no longer uses
req.session. This means you are no
longer required to use a session middleware. Instead, you do need to use the
cookie-parser middleware in
your app before this middleware.
When set to an object, cookie storage of the secret is enabled and the
object contains options for this functionality (when set to
defaults for the options are used). The options may contain any of the
key- the name of the cookie to use to store the token secret (defaults to
path- the path of the cookie (defaults to
An array of the methods for which CSRF token checking will disabled.
['GET', 'HEAD', 'OPTIONS'].
Determines what property ("key") on
req the session object is located.
'session' (i.e. looks at
req.session). The CSRF secret
from this library is stored and read as
If the "cookie" option is not
false, then this option does
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
req.query._csrf- a built-in from Express.js to read from the URL query string.
CSRF-TokenHTTP request header.
XSRF-TokenHTTP request header.
X-CSRF-TokenHTTP request header.
X-XSRF-TokenHTTP 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 middlewaresvar csrfProtection = csrf cookie: truevar parseForm = bodyParserurlencoded extended: false// create express appvar app = express// parse cookies// we need this because "cookie" is true in csrfProtectionappusecookieParserappget'/form' csrfProtection// pass the csrfToken to the viewresrender'send' csrfToken: reqcsrfTokenapppost'/process' parseForm csrfProtectionressend'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
Note CSRF checks should only be disabled for requests that you expect to come from outside of your website. Do not disable CSRF checks for requests that you expect to only come from your website. An existing session, even if it belongs to an authenticated user, is not enough to protect against CSRF attacks.
The following is an example of how to order your routes so that certain endpoints do not check for a valid CSRF token.
var cookieParser = require'cookie-parser'var csrf = require'csurf'var bodyParser = require'body-parser'var express = require'express'// create express appvar app = express// create api routervar api = createApiRouter// mount api before csrf is appended to the app stackappuse'/api' api// now add csrf and other middlewares, after the "/api" was mountedappusebodyParserurlencoded extended: falseappusecookieParserappusecsrf cookie: trueappget'/form'// pass the csrfToken to the viewresrender'send' csrfToken: reqcsrfTokenapppost'/process'ressend'csrf was required to get here'var router =routerpost'/getProfile'ressend'no csrf to get here'return router
When the CSRF token validation fails, an error is thrown that has
err.code === 'EBADCSRFTOKEN'. This can be used to display custom
var bodyParser = require'body-parser'var cookieParser = require'cookie-parser'var csrf = require'csurf'var express = require'express'var app = expressappusebodyParserurlencoded extended: falseappusecookieParserappusecsrf cookie: true// error handlerappuseif errcode !== 'EBADCSRFTOKEN' return nexterr// handle CSRF token errors hereresstatus403ressend'form tampered with'