Tuesday, July 10, 2012

Adding HTTP headers to AJAX calls in Backbone.js

Just a quick note about setting custom header in the HTTP request that Backbone.js manages. This is super easy to do. In the example code below, I have a Backbone.Collection assigned to messagesCollection variable and I'm triggering a fetch on that collection: messagesCollection.fetch({ headers: { 'x-my-custom-header-1':'foobar', 'x-my-rest-api-version':'1.0' } });


  1. Thanks for this, I couldn't find anything about headers in the Backbone docs.

    Also, if anyone wants to add default headers (such as a REST token) to all their backbone sync calls, you can do this:

    // Store the native, default sync method, we'll wrap this.
    Backbone._nativeSync = Backbone.sync;

    // Create our default options object
    Backbone.defaultSyncOptions = {};

    // Ever so gingerly wrap the native sync
    // in a method that combines options
    Backbone.sync = function( method, model, options) {
    Backbone._nativeSync( method, model,
    _.extend( {}, Backbone.defaultSyncOptions, options ) );

    // then just set the options:
    Backbone.defaultSyncOptions = { headers: { "foo":"bar" } };

  2. Tyler, thanks for posting that.

  3. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or learn thru Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry. JavaScript Training in Chennai

  4. You can find anyone quite easily these days once you have a computer that is connected to the internet. That is one of the good sides of the internet technology; all unlisted telephone numbers can now be traced easily. I must confess that a lot of mobile phone and information technology experts went to work after the WTC bombings a few years ago; and of course, this brought about various means of tracing cell free business calls