Search code examples
javascriptbackbone.jsrequirejsamd

Howto cleanly fetch 401 in a Backbone.js based app


In my Backbone.js based app I am talking to my API that responds with a 401 in case the underlying request was made without or with an invalid authentication token. I'd like to instrument that by navigating to a #login page, every time a 401 is received.

To fetch the 401 I successfully wrapped Backbone.sync, but at that point I get kind of stuck. I tried several strategies here:

  1. throw 'unauthorized' down in Backbone::sync and try to fetch up in my router. Failed with: 'Uncaught unauthorized'

  2. Trying to #.navigate '#login' down in Backbone::sync which not only looks odd, but comes with the problem that my app is based on AMD/require.js and I cannot simply access my Backbone.Router instance down in my wrapped sync function.

The only solution I see so far would be to create a "globally available" caching object, that gets a reference to my router instance and in turn is put into define as a dependency where it is needed. That cache object had to be a singleton and broke my whole 'please-no-globals-and-no-namespaces' - strategy.

I am kind of stuck here. Can anyone point me to a more clean solution to that common problem?


Solution

  • You can do the redirect in ajaxError:

    $.ajaxError(function (event, xhr) {
                if (xhr.status == 401)
                    window.location = '#login';
            });
    

    If everything is setup properly you do not need to access the router instance manually. Going to that url should trigger the route function associated with it.