Module middleware/csrf

A middleware for CSRF mitigation, using either the synchronizer token or the double submission cookie pattern (see OWASP CSRF Prevention Cheat Sheet for a detailed explanation).

This middleware extends the request object by adding two methods:

  • getCsrfToken() returns the CSRF token value for the current request, creating and storing it in the current session if necessary
  • rotateCsrfToken() creates a new CSRF token and stores it in the current session

Use getCsrfToken() of the request object to add the token value as hidden input to all forms generated by the application, and make sure the name of the form input is configured accordingly (defaults to "csrftoken").

The token value returned by getCsrfToken() is additionally stored either in the current session (default) or in a cookie. The POST parameter and the token value stored are compared, and in case of a mismatch this middleware returns a 403 "Forbidden" response.

For non-POST requests this middleware accepts the token sent as query parameter or custom header field.

Configuration options:

app.csrf() accepts an object as parameter containing the following properties (default values in brackets):

  • tokenLength: The length of the CSRF token (32)
  • checkReferrer: Enable strict referrer checking for HTTPS requests (true)
  • rotate: If true tokens are only used once and modified after each validation (false)
  • getToken: By default the middleware expects the submitted CSRF token in either a post or query parameter csrftoken or in a custom request header x-csrf-token (in this order). To customize this define a function that will receive the request object as single argument and is expected to return the CSRF token (or null).
  • getFailureResponse: An optional function receiving the request as single argument. This method is called if the CSRF validation failed, and is expected to return a valid JSGI response (default: 403 forbidden).
  • safeMethods: An array containing request method names that are considered safe, so no token validation is done (["GET", "HEAD", "OPTIONS", "TRACE"]) – isSafeRequest: A function which returns true if the request is safe, false otherwise. A request is considered safe if it fulfills isSafeRequest || safeMethods.

Cookie mode

The following options switch the middleware into "double submission cookie" mode, and allow detailed configuration of the cookie:

  • useCookie: If true the CSRF token is stored in a cookie
  • cookieName: The name of the cookie to set ("csrftoken")
  • cookieHttpOnly: If true the httpOnly flag of the cookie is set (true)
  • cookieSecure: If true the secure flag of the cookie is set (false)


    "tokenLength": 64,
    "rotate": true,
    "getToken": function(req) {
        return req.headers["x-custom-field"];


middleware (next, app)

Stick middleware factory for CSRF mitigation


Function next

the wrapped middleware chain

Object app

the Stick Application object



a JSGI middleware function