Setting defaults for all your SuperAgent requests

Don't miss a single post, sign up for immediate updates!

SuperAgent is an HTTP request library for both Node.js and client-side JavaScript. It’s lightweight and easy to use but out of the box doesn’t support setting defaults on all of your requests.

The simplest approach would be to use the npm package superagent-defaults which implements basic default setting capabilities:

With superagent-defaults in Node.js it would look something like this:

const defaults = require('superagent-defaults');

const superagent = defaults();

superagent
  .set('X-Custom-Header', 'foobar');

export default superagent;

Now you can require this file wherever you’re using SuperAgent instead of the superagent package itself.

This worked out great for us until we started to implement an authentication check in our client-side code to logout / route users to the login page when their authentication token has expired or is missing.

In that situation, we couldn’t simply set the defaults as they needed to be interrogated periodically for changes. This became very apparent when I created a redirect loop that would immediately log you out as soon as you log in because we I was only setting the authentication header in the SuperAgent defaults on initial page load, not after you properly authenticated.

To get around this, I wrote a script that would utilize superagent-defaults for the static settings, and create a series of wrapper methods that mirrored SuperAgent’s existing interfacing:

const defaults = require('superagent-defaults');

const superagent = defaults();

superagent
  .set('X-Custom-Header', 'foobar');

const request = {
  init: () => (
    superagent.set(
      'Authorization',
      `Bearer ${window.localStorage.getItem('token')}`,
    )
  ),
  delete: url => request.init().delete(url),
  get: url => request.init().get(url),
  post: url => request.init().post(url),
  put: url => request.init().put(url),
};

Not my best work as it has some duplicated code in there, but it gets the job done. Feel free to improve and comment below ;)

To interface with it, you would require that script and then access the new request object as you would access a SuperAgent object:

const request = require('superagent-wrapper');

request
  .get('https://api.crowdsync.com/endpoint')
  .then(
    res => console.log(res),
    err => console.log(err),
  );

Now you have defaults (static and dynamic) set on all of your SuperAgent requests… NEXT ISSUE!