Getting a csrf token in a form


This open source chat project uses the jade index file below. You'll notice that the form has an input value for a #{csrf} token. Where would this csrf value be coming from? Is it part of the browser environment? I don't see any javascript in the project that inserts that csrf token into that input field.

For example, when you visit the root, it just renders the index like this

  app.get('/', function (req, res) {


extend layout

block content
  form(method='post', id='add-chat-form')
    input(type='hidden', name='picture', id='picture')
      input(name='message', id='add-chat', class='input', maxlength='250', autocomplete='off', placeholder='Send a public message')
      input(type='hidden', name='_csrf', value='#{csrf}')
      input(type='hidden', name='fingerprint', id='fp')
      input(type='hidden', name='userid', id='userid')
        span Sending, please wait!
  #counter 250
Problem courtesy of: Leahcim


The tokens are created by the connect csrf middleware. You can see this in settings.js. On line 7:

  var csrf = express.csrf();

and line 13:

  var clientBypassCSRF = function (req, res, next) {
    if (req.body.apiKey && nativeClients.indexOf(req.body.apiKey) > -1) {
    } else {
      csrf(req, res, next);

This exposes a function csrfToken on the req object, which is used on line 45:

        res.locals.csrf = req.csrfToken();

The express templating engine (res.render('index'); in the code you showed in your question) extends the templates scope with the res.locals object, which is how that field gets filled in during templating.

Solution courtesy of: Aaron Dufour


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.