# csurf [![Build Status](https://travis-ci.org/expressjs/csurf.svg?branch=master)](https://travis-ci.org/expressjs/csurf) [![NPM Version](https://badge.fury.io/js/csurf.svg)](https://badge.fury.io/js/csurf)

Node.js [CSRF](https://en.wikipedia.org/wiki/Cross-site_request_forgery) protection middleware.

Requires either a session middleware or [cookie-parser](https://github.com/expressjs/cookie-parser) to be initialized first.
- [session](https://github.com/expressjs/session)
- [cookie-session](https://github.com/expressjs/cookie-session)

### Install

```sh
$ npm install csurf
```

## API

```js
var csrf = require('csurf')
```

### csrf(options)

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.

#### Options

- `value` a function accepting the request, returning the token.
  - The default function checks four possible token locations:
    - `_csrf` parameter in `req.body` generated by the `body-parser` middleware.
    - `_csrf` parameter in `req.query` generated by `query()`.
    - `x-csrf-token` and `x-xsrf-token` header fields.
- `cookie` set to a truthy value to enable cookie-based instead of session-based csrf secret storage.
  - If `cookie` is an object, these options can be configured, otherwise defaults are used:
    - `key` the name of the cookie to use (defaults to `_csrf`) to store the csrf secret
    - any other [res.cookie](http://expressjs.com/4x/api.html#res.cookie) options can be set

### req.csrfToken()

Lazy-loads the token associated with the request.

## Example

```js
var express = require('express')
var csrf    = require('csurf')

var app = express()
app.use(csrf())
```

## License

[MIT](LICENSE)
