{"id":22645514,"url":"https://github.com/akmjenkins/flighty","last_synced_at":"2026-05-04T12:35:51.912Z","repository":{"id":34220856,"uuid":"171495924","full_name":"akmjenkins/flighty","owner":"akmjenkins","description":"Lightweight fetch wrapping library, inspired by Frisbee","archived":false,"fork":false,"pushed_at":"2023-01-03T16:35:46.000Z","size":3114,"stargazers_count":1,"open_issues_count":12,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-03-23T02:20:57.750Z","etag":null,"topics":["abort","ajax","axios","fetch","frisbee","intercept","jwt","react","react-native","request","upload","xhr"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/akmjenkins.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-02-19T15:13:31.000Z","updated_at":"2022-05-10T23:06:15.000Z","dependencies_parsed_at":"2023-01-15T05:30:38.113Z","dependency_job_id":null,"html_url":"https://github.com/akmjenkins/flighty","commit_stats":null,"previous_names":[],"tags_count":23,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akmjenkins%2Fflighty","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akmjenkins%2Fflighty/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akmjenkins%2Fflighty/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akmjenkins%2Fflighty/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/akmjenkins","download_url":"https://codeload.github.com/akmjenkins/flighty/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246145603,"owners_count":20730593,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["abort","ajax","axios","fetch","frisbee","intercept","jwt","react","react-native","request","upload","xhr"],"created_at":"2024-12-09T06:06:14.811Z","updated_at":"2026-05-04T12:35:46.880Z","avatar_url":"https://github.com/akmjenkins.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Flighty ✈️\n\n[![NPM Version](https://img.shields.io/npm/v/flighty.svg?branch=master)](https://www.npmjs.com/package/flighty)\n[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)\n[![dependencies Status](https://david-dm.org/akmjenkins/flighty/status.svg)](https://david-dm.org/akmjenkins/flighty)\n[![install size](https://packagephobia.now.sh/badge?p=flighty\u0026flightyCB=1)](https://packagephobia.now.sh/result?p=flighty)\n[![codecov](https://codecov.io/gh/akmjenkins/flighty/branch/master/graph/badge.svg)](https://codecov.io/gh/akmjenkins/flighty)\n[![Build Status](https://travis-ci.org/akmjenkins/flighty.svg?branch=master)](https://travis-ci.org/akmjenkins/flighty)\n\nSimple (and tiny) fetch wrapper with nifty features such as intercepts, ***easy*** aborts, and retries, for everywhere - that's browser, react-native, and ES5/6 front-ends.\n\n## Motivation\n\nYet another fetch wrapping library? Well, various fetch-wrapping libraries have some of the above features, but none have them all.\n\nMore importantly, almost all fetch wrapping libraries investigated include their polyfills right in the main packages (or don't include polyfills at all requiring you to find out what you're missing). Flighty has an opt-in polyfill for [fetch](https://www.npmjs.com/package/cross-fetch) (and tiny polyfills for [AbortController](https://www.npmjs.com/package/abortcontroller-polyfill) and [ES6 promise](https://github.com/taylorhakes/promise-polyfill), because you'll likely need those, too if you don't have fetch), so you don't have to bloat your code if you don't absolutely need to.\n\nEverything you'll need is included in Flighty, it's just a matter of figuring out what you need. Running in a fetch-unknown environment - use flighty/fetch. You know you'll already have a fetch but unsure of AbortController? Use flighty/abort. Supporting the latest and greatest? Just import plain ol' flighty.\n\n### Browser\n```html\n\u003c!-- no polyfills --\u003e\n\u003cscript src=\"https://unpkg.com/flighty\"\u003e\u003c/script\u003e\n\n\u003c!-- fetch, abort, and promise polyfills --\u003e\n\u003cscript src=\"https://unpkg.com/flighty/fetch\"\u003e\u003c/script\u003e\n\n\u003c!-- abort only polyfill --\u003e\n\u003cscript src=\"https://unpkg.com/flighty/abort\"\u003e\u003c/script\u003e\n\n\n\u003cscript\u003e\n // no matter which package you choose\n flighty.get('/somepath').then(...)\n\u003c/script\u003e\n```\n\n### ES5\n```js\n// no polyfill\nvar flighty = require('flighty');\n\n// fetch, abort, and promise polyfills\nvar flighty = require('flighty/fetch')\n\n// abort only polyfill\nvar flighty = require('flighty/abort')\n```\n\n\n### ES6 (and React Native*)\n```js\n// no polyfill\nimport flighty from \"flighty\";\n\n// fetch, abort, and promise polyfills\nimport flighty from \"flighty/fetch\";\n\n// abort only polyfill\nimport flighty from \"flighty/abort\";\n```\n\n**Note:** React Natives import from Flighty includes the AbortController polyfill. If React Native ever updates it's fetch, Flighty will remove this. If you do `import flighty from \"flighty/abort\"` in React Native you'll get the same package as `import flighty from \"flighty\"`, so it's recommended to do the latter.\n\n## Tiny\n\nRegardless of the package and implementation you choose, flighty is **tiny**. The biggest implementation (which is the browser build that has all polyfills) is *less than 9kb* minified and gzipped.\n\n## Features\n\n**Drop in replacement** for fetch. This works:\n\n```js\nconst res = await fetch('/somepath',{some options});\nconst res = await flighty.get('/somepath',{some options});\n```\n\nThis works because Flighty returns the standard [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) but with the addition of the **flighty object**.\n\nThe drop in replacement makes this library relatively simple to add/remove from your codebase. If you keep your use of the flighty object on the response limited to interceptors then refactoring Flighty into/out of your codebase becomes a breeze.\n\n### flighty object\n\n```js\nres.flighty = {\n  method, // the method you called flighty with - e.g. get, post, put\n  retryCount, // the number of times this request has been retried\n  json, // what you'd normally get from await res.json()\n  text, // what you'd normally get from await res.text()\n  // the values the original flighty request was called with\n  call: {\n    path,\n    options,\n    extra\n  },\n  // retry method - calls the same request you made the first time again - hello JWT 401s\n  retry: async ()\n}\n\n```\n\n### Abort\n\nFlighty comes with two abort APIs. `abortAll()` which cancels all ongoing requests and cancellation via an `abortToken` (similar to [axios cancellation token](https://github.com/axios/axios#cancellation) but easier!).\n\nAborting Fetch requests comes with a hairy, verbose [AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) API that requires you to construct, pass in a signal to the fetch, and then abort the controller like so:\n\n```js\n  const controller = new AbortController();\n  const req = fetch('/',{signal:controller.signal})\n\n  controller.abort();\n\n  try {\n    const res = await req;\n  } catch(err) {\n    // AbortError!\n  }\n\n```\n\nFlighty allows you to pass in a token (any Symbol) and then call `abort(token)` to cancel the request.\n\n```js\n  const req = flighty.get('/',{abortToken:\"my token\"});\n  flighty.abort(\"my token\");\n\n  try {\n    const res = await req;\n  } catch(err) {\n    // AbortError!\n  }\n```\n\nTokens, like AbortController signals, can be used to abort multiple requests. Let Flighty automate the creation and management of AbortController's for your requests. Just pass in a token and your request is then easy to abort.\n\n```js\n const abortToken = \"some token\";\n const reqOne = flighty('/pathone',{abortToken})\n const reqTwo = flighty('/pathtwo',{abortToken})\n const reqThree = flighty('/paththree',{abortToken})\n\n // cancel them all!\n flighty.abort(abortToken);\n\n```\n\n### Interceptors\n\nDrop in replacement for anybody using [Frisbee](https://www.npmjs.com/package/frisbee) interceptors or [fetch-intercept](https://www.npmjs.com/package/fetch-intercept), but with a couple of extra things:\n\n```js\nconst interceptor = {\n  request: (path,options,extra,retryCount) =\u003e {\n\n    // extra is an immutable object of the data passed in when\n    // creating the request - e.g. flighty('/mypath',{myFetchOptions},{someExtraData})\n    // it doesn't get changed between interceptors if you modify it.\n\n    // retryCount is the number of times this request has been\n    // retried via res.flighty.retry() or by using the retry parameters\n    // and is also immutable between interceptors\n\n\n    return [path,options];\n  }\n}\n```\n\nHere's an example interceptor object:\n```js\n{\n  request: function (path, options, extra, retryCount) {\n      // remember - extra and retryCount are immutable and will\n      // be passed to each interceptor the same\n      return [path, options];\n  },\n  requestError: function (err) {\n      // Handle an error occurred in the request method\n      return Promise.reject(err);\n  },\n  response: function (response) {\n      // do something with response (or res.flighty!)\n      return response;\n  },\n  responseError: function (err) {\n      // Handle error occurred in the last ran requestInterceptor, or the fetch itself\n      return Promise.reject(err);\n  }\n}\n```\n\n### Retries\n\nFlighty implements the same retry parameters found in [fetch-retry](https://www.npmjs.com/package/fetch-retry) but it adds two important features:\n\n1) Doesn't continue to retry if the request was aborted via an AbortController signal (or token)\n2) Adds an optional asynchronous `retryFn` that will be executed between retries\n\n#### Retry API\n\n* `retries` - the maximum number of retries to perform on a fetch (default 0 - do not retry)\n\n* `*retryDelay` - a timeout in ms to wait between retries (default 1000ms)\n\n* `retryOn` - an array of HTTP status codes that you want to retry (default you only retry if there was a network error)\n\n* `*retryFn` - a function that gets called in between the failure and the retry. This function is `await`ed so you can do some asynchronous work before the retry. Combine this with retryOn:[401] and you've got yourself a(nother) recipe to refresh JWTs (more at the end of this README):\n\n***Note:** The `retryDelay` parameter will be ignored if `retryFn` is declared. If you're using `retryFn` it's up to you to handle the delay, if any, between retries.\n\n```js\nres = await flighty.get('/path-requiring-authentication',{\n  retries:1,\n  retryOn:[401],\n  retryFn:() =\u003e flighty.get('/path_to_refresh_you_token')\n})\n```\n\nThe Flighty object also has a retry method to make it simply to retry a request:\n\n```js\n  let res;\n  res = await flighty.get('/');\n\n  if(!res.ok \u0026\u0026 res.flighty.retryCount === 0) {\n    // try it one more time...\n    res = res.flighty.retry();\n  }\n```\n\n---\n\n## API\n\n* `flighty` - default export - an instance of `Flighty`. It has a `create` method that can be used to instantiate other instances of `Flighty`. The `create` method accepts an object with can contain the following options:\n\n  * `baseURI` - the default URI use to prefix all your paths\n\n  * `headers` - an object containing default headers to send with every request\n\n  * `arrayFormat` - how to stringify array in passed body. See [qs](https://www.npmjs.com/package/qs) for available formats\n\nInstances of `Flighty` contain the following methods:\n\n* `jwt(token)` - Set your Bearer Authorization header via this method. Pass in a token and Flighty will add the header for you, pass in something false-y and Flighty won't automatically add an auth header (in case you want to do it yourself)\n\n* `auth(username,password)` - Set your Basic Authorization header via this method. Pass in a username and password and Flighty will add the header `Authorization Basic bas64encoded username and password` for you, pass in something false-y and Flighty won't automatically add an auth header (in case you want to do it yourself)\n\n* `abort` - method that accepts an abortToken to abort specific requests.\n\n* `abortAll` - aborts all in-progress requests controlled by this instance.\n\n* HTTP wrapper methods (e.g. get, post, put, delete, etc) require a `path` string, and accept two optional plain object arguments - `options` and `extra`\n\n  * Accepted method arguments:\n\n    * `path` **required** - the path for the HTTP request (e.g. `/v1/login`, will be prefixed with the value of `baseURI` if set)\n\n    * `options` _optional_ - everything you'd pass into fetch's [init](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch) plus optional `abortToken` and retry parameters: `retries`,`retryFn`,`retryDelay`,`retryFn`\n\n    * `extra` _optional_ object - sometimes you have some meta data about a request that you may want interceptors or other various listeners to know about. Whatever you pass in here will come out the other end attached the to `res.flighty.call` object and will also be passed along to all interceptors along the way\n\n  * List of available HTTP methods:\n\n    * `api.get(path, options, extra)` - GET\n    * `api.head(path, options, extra)` - HEAD\n    * `api.post(path, options, extra)` - POST\n    * `api.put(path, options, extra)` - PUT\n    * `api.del(path, options, extra)` - DELETE\n    * `api.options(path, options, extra)` - OPTIONS\n    * `api.patch(path, options, extra)` - PATCH\n\n* `registerInterceptor` - method that accepts an `interceptor` and calls it on every fetch. Returns a function that allows you to remove it:\n\n  ```js\n    const api = new Flighty({});\n    const undo = api.registerInterceptor(someInterceptor);\n    await api.get('/'); // your interceptor will run\n    undo(); // your interceptor is gone!\n  ```\n\n* `removeInterceptor` - method that accepts an reference to interceptor and removes it\n\n\n* `clearInterceptors` - removes all interceptors.\n\nFor convenience, Flighty has exposed an `interceptor` property that has the same API as frisbee to register and unregister interceptors.\n\n## Unit testing\n\nKeep it short - don't mock Flighty. It'd be over-complicated and unnecessary to mock it's features - so just mock the fetch and let Flighty do it's thing in your tests. I recommend [jest-fetch-mock](https://www.npmjs.com/package/jest-fetch-mock).\n\n---\n\n## Recipes\n\n### Throw if not 2xx recipe\n\nDon't know about you, but I found it annoying that I always had to check `res.ok` to handle my error conditions - why not just throw if the response isn't ok? Interceptor!\n\nBefore:\n```js\n\n  const res = await fetch('/');\n  if(res.ok) {\n    // do some good stuff\n  } else {\n    // do some bad stuff\n  }\n\n```\n\nAfter:\n```js\nflighty.registerInterceptor({\n  response:res =\u003e {\n    if(!res.ok) {\n      throw res;\n    }\n    return res;\n  }\n});\n\n// Now all my responses throw if I get a non-2xx response\ntry {\n  const res = await flighty.get('/');\n} catch(e) {\n  // response returned non-2xx\n}\n```\n\n### JWT Recipe with retry() and Interceptors\n\n```js\n\nconst interceptor = {\n  request: (path,options) =\u003e {\n    flighty.jwt(path === REFRESH_ENDPOINT ? myRefreshToken : myAccessToken);\n    return [path,options]\n  },\n  response: async res =\u003e {\n\n    // our only job when hitting the login path is to set the tokens locally\n    if(path === LOGIN_ENDPOINT) {\n      if(res.ok) {\n        // store your access and refresh tokens\n        setTokensLocally()\n      }\n\n      return res;\n    }\n\n    // if we get a 401 and we're not trying to refresh and this is our first retry\n    if (res.status === 401 \u0026\u0026 path !== REFRESH_TOKEN_PATH \u0026\u0026 res.flighty.retryCount === 0) {\n      try {\n        await requestToRefreshYourToken();\n        return response.flighty.retry()\n      } catch(e) {\n        // log the user out\n      }\n    }\n\n    return res;\n  }\n}\n\n```\n\n### Alternate JWT Recipe and Interceptors\n```js\n\n// same request interceptor as before\nconst interceptor = {\n  request:(path,options) =\u003e {\n    flighty.jwt(path === REFRESH_ENDPOINT ? myRefreshToken : myAccessToken);\n    return [path,options]\n  }\n}\n\nconst authenticatedApiRequest = (path,options,extra) =\u003e {\n  return flighty(\n    path,\n    {\n      ...options,\n      // retry the request 1 time\n      retries:1,\n      // if a 401 or network error is received\n      retryOn:[401],\n      // and request a new token in between\n      retryFn:() =\u003e flighty.get(REFRESH_TOKEN_ENDPOINT)\n    }\n    extra)\n};\n\nconst myRequest = authenticatedApiRequest('/some-path-requiring-authentication');\n```\n\n## Contributing\n\nPRs and ideas welcome!","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fakmjenkins%2Fflighty","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fakmjenkins%2Fflighty","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fakmjenkins%2Fflighty/lists"}