Extending backbone's requests with custom headers

We have all but love for backbone around here. But although it's pretty flexible and complete, sometimes you just need that something that doesn't quite work the way you need, like adding custom headers to every single request.

You could be tempted to add a sync function on every model and collection and add your custom headers there, but besides multiplying your code many times, if your project is going on for more than a few weeks you might have some serious copy pasting to do.

There is a simpler, easier and prettier way of adding for example, a bearer token. Find a place where you can access the Backbone object and extend it like so:

Backbone.ajax = function() {  
    arguments[0].headers = {
        'Authorization': 'Bearer ' + <your token>,
        'Accept': "application/json"

    return Backbone.$.ajax.apply(Backbone.$, arguments);      

Hence tapping into backbone's ajax function, changing it, and putting it back into it's place.

comments powered by Disqus