javascriptpolymerpolymer-1.0service-worker

How can I, and does it make sense to, use a Service Worker to add an Authorization header to all my API requests?


Every request I make to an internal API requires an Authorization header. I am building a Polymer-based app using many web components, both private and third-party. I do nearly all of my AJAX calls through <iron-ajax> elements. I know that I could create a custom component to achieve the centralization I'm looking for, but I was wondering if using a service worker to intercept requests to my api and add the required headers and any other manipulation or validation I might want would be viable, performant, or even possible. Especially because Polymer 1.0 doesn't support extending other components yet.


Solution

  • Think of the service worker script as a (java-)scriptable proxy — you could most certainly do any manipulation (including adding, removing and manipulating HTTP Headers) to your calls as long as the service worker controls the origin. And as long as your API calls are same-origin. Cross-Origin and other opaque request-y stuff gets trickier, but I don't think this applies to your use-case judging from how you described it so far.

    The only problem with that approach is that you are basically limiting your app's scope to a single browser: Google Chrome (version 40+). If that's fine by you, feel free to go ahead with this, but since Firefox won't be supporting request capture (the fetch event) just yet, (even though service workers at this point seem to be finally landing in Firefox 43), and you can't polyfill service workers — you will have to provide some fallback-mechanism in your page's JS code if you want to support any browser, other than Chrome 40+ at least for several months to come.