How can I embed a CSRF token in a JavaScript file?

I have a Node.js application in which I have implemented CSRF. It's working fine, and when I had some JavaScript inline in a JADE file, I simply used #{token} to get the token into the JavaScript.

However, I've now moved my JavaScript into external files, and can't figure out a simple way to input the CSRF token into the code. How can I do so?

Consider to use a META-element in the document's head to hold the CSRF token. Then use this token in AJAX requests. If your server returns a new token, replace the contents of the META-element.

HTML:

<html>
<head>
  <!-- generate this server-side -->
  <meta name="csrf" content="A_VALUE">
</head>
<body>
  <form>
    <input type="text" name="something">
    <input type="submit" value="Send">
  </form> 
<body>
</html>

JAVASCRIPT

(function($) {
  var csrf = $("meta[name='csrf']").attr("content");
  $("form").submit(function (evt) {
    evt.preventDefault();
    alert("CSRF: " + csrf);
  });
})(jQuery);

(http://jsfiddle.net/ZmesY/1/)

Just write an inline script with a global token var which you can reference from any other scripts.

script
  | window.myApp.token = #{token};

And in your js:

$.ajax({ data: { _csrf: window.myApp.token }, ...});

(The exact syntax might be wrong, was a long time since i used jade, but I'm sure you get the general idea).

You can simply implant your token into one dom element, say, a hidden div. And use javascript to get that element and read the token.