3 [![NPM Version][npm-image]][npm-url]
4 [![NPM Downloads][downloads-image]][downloads-url]
5 [![Build status][travis-image]][travis-url]
6 [![Test coverage][coveralls-image]][coveralls-url]
7 [![Gratipay][gratipay-image]][gratipay-url]
9 Node.js [CSRF](https://en.wikipedia.org/wiki/Cross-site_request_forgery) protection middleware.
11 Requires either a session middleware or [cookie-parser](https://www.npmjs.com/package/cookie-parser) to be initialized first.
13 * If you are setting the ["cookie" option](#cookie) to a non-`false` value,
14 then you must use [cookie-parser](https://www.npmjs.com/package/cookie-parser)
16 * Otherwise, you must use a session middleware before this module. For example:
17 - [express-session](https://www.npmjs.com/package/express-session)
18 - [cookie-session](https://www.npmjs.com/package/cookie-session)
20 If you have questions on how this module is implemented, please read
21 [Understanding CSRF](https://github.com/pillarjs/understanding-csrf).
32 var csurf = require('csurf')
37 Create a middleware for CSRF token creation and validation. This middleware
38 adds a `req.csrfToken()` function to make a token which should be added to
39 requests which mutate state, within a hidden form field, query-string etc.
40 This token is validated against the visitor's session or csrf cookie.
44 The `csurf` function takes an optional `options` object that may contain
45 any of the following keys:
49 Determines if the token secret for the user should be stored in a cookie
50 or in `req.session`. Defaults to `false`.
52 When set to `true` (or an object of options for the cookie), then the module
53 changes behavior and no longer uses `req.session`. This means you _are no
54 longer required to use a session middleware_. Instead, you do need to use the
55 [cookie-parser](https://www.npmjs.com/package/cookie-parser) middleware in
56 your app before this middleware.
58 When set to an object, cookie storage of the secret is enabled and the
59 object contains options for this functionality (when set to `true`, the
60 defaults for the options are used). The options may contain any of the
63 - `key` - the name of the cookie to use to store the token secret
64 (defaults to `'_csrf'`).
65 - `path` - the path of the cookie (defaults to `'/'`).
66 - any other [res.cookie](http://expressjs.com/4x/api.html#res.cookie)
71 An array of the methods for which CSRF token checking will disabled.
72 Defaults to `['GET', 'HEAD', 'OPTIONS']`.
76 Determines what property ("key") on `req` the session object is located.
77 Defaults to `'session'` (i.e. looks at `req.session`). The CSRF secret
78 from this library is stored and read as `req[sessionKey].csrfSecret`.
80 If the ["cookie" option](#cookie) is not `false`, then this option does
85 Provide a function that the middleware will invoke to read the token from
86 the request for validation. The function is called as `value(req)` and is
87 expected to return the token as a string.
89 The default value is a function that reads the token from the following
92 - `req.body._csrf` - typically generated by the `body-parser` module.
93 - `req.query._csrf` - a built-in from Express.js to read from the URL
95 - `req.headers['csrf-token']` - the `CSRF-Token` HTTP request header.
96 - `req.headers['xsrf-token']` - the `XSRF-Token` HTTP request header.
97 - `req.headers['x-csrf-token']` - the `X-CSRF-Token` HTTP request header.
98 - `req.headers['x-xsrf-token']` - the `X-XSRF-Token` HTTP request header.
102 ### Simple express example
104 The following is an example of some server-side code that generates a form
105 that requires a CSRF token to post back.
108 var cookieParser = require('cookie-parser')
109 var csrf = require('csurf')
110 var bodyParser = require('body-parser')
111 var express = require('express')
113 // setup route middlewares
114 var csrfProtection = csrf({ cookie: true })
115 var parseForm = bodyParser.urlencoded({ extended: false })
117 // create express app
121 // we need this because "cookie" is true in csrfProtection
122 app.use(cookieParser())
124 app.get('/form', csrfProtection, function(req, res) {
125 // pass the csrfToken to the view
126 res.render('send', { csrfToken: req.csrfToken() })
129 app.post('/process', parseForm, csrfProtection, function(req, res) {
130 res.send('data is being processed')
134 Inside the view (depending on your template language; handlebars-style
135 is demonstrated here), set the `csrfToken` value as the value of a hidden
136 input field named `_csrf`:
139 <form action="/process" method="POST">
140 <input type="hidden" name="_csrf" value="{{csrfToken}}">
142 Favorite color: <input type="text" name="favoriteColor">
143 <button type="submit">Submit</button>
147 ### Custom error handling
149 When the CSRF token validation fails, an error is thrown that has
150 `err.code === 'EBADCSRFTOKEN'`. This can be used to display custom
154 var bodyParser = require('body-parser')
155 var cookieParser = require('cookie-parser')
156 var csrf = require('csurf')
157 var express = require('express')
160 app.use(bodyParser.urlencoded({ extended: false }))
161 app.use(cookieParser())
162 app.use(csrf({ cookie: true }))
165 app.use(function (err, req, res, next) {
166 if (err.code !== 'EBADCSRFTOKEN') return next(err)
168 // handle CSRF token errors here
170 res.send('form tampered with')
178 [npm-image]: https://img.shields.io/npm/v/csurf.svg
179 [npm-url]: https://npmjs.org/package/csurf
180 [travis-image]: https://img.shields.io/travis/expressjs/csurf/master.svg
181 [travis-url]: https://travis-ci.org/expressjs/csurf
182 [coveralls-image]: https://img.shields.io/coveralls/expressjs/csurf/master.svg
183 [coveralls-url]: https://coveralls.io/r/expressjs/csurf?branch=master
184 [downloads-image]: https://img.shields.io/npm/dm/csurf.svg
185 [downloads-url]: https://npmjs.org/package/csurf
186 [gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg
187 [gratipay-url]: https://gratipay.com/dougwilson/