@gcmdev/faxios 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/LICENSE +1 -0
  2. package/README.md +40 -1774
  3. package/dist/index.d.ts +9 -6
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/index.js.map +1 -1
  6. package/dist/lib/adapters/fetch-helpers.d.ts +1 -0
  7. package/dist/lib/adapters/fetch-helpers.d.ts.map +1 -0
  8. package/dist/lib/adapters/fetch.d.ts +1 -0
  9. package/dist/lib/adapters/fetch.d.ts.map +1 -0
  10. package/dist/lib/adapters/fetch.js +23 -3
  11. package/dist/lib/adapters/fetch.js.map +1 -1
  12. package/dist/lib/cancel/CanceledError.d.ts +1 -0
  13. package/dist/lib/cancel/CanceledError.d.ts.map +1 -0
  14. package/dist/lib/cancel/isCancel.d.ts +3 -1
  15. package/dist/lib/cancel/isCancel.d.ts.map +1 -0
  16. package/dist/lib/cancel/isCancel.js +3 -0
  17. package/dist/lib/cancel/isCancel.js.map +1 -1
  18. package/dist/lib/core/Faxios.d.ts +6 -17
  19. package/dist/lib/core/Faxios.d.ts.map +1 -0
  20. package/dist/lib/core/Faxios.js +144 -76
  21. package/dist/lib/core/Faxios.js.map +1 -1
  22. package/dist/lib/core/FaxiosError.d.ts +19 -6
  23. package/dist/lib/core/FaxiosError.d.ts.map +1 -0
  24. package/dist/lib/core/FaxiosError.js +16 -1
  25. package/dist/lib/core/FaxiosError.js.map +1 -1
  26. package/dist/lib/core/FaxiosHeaders.d.ts +12 -8
  27. package/dist/lib/core/FaxiosHeaders.d.ts.map +1 -0
  28. package/dist/lib/core/FaxiosHeaders.js +1 -0
  29. package/dist/lib/core/FaxiosHeaders.js.map +1 -1
  30. package/dist/lib/core/buildFullPath.d.ts +1 -0
  31. package/dist/lib/core/buildFullPath.d.ts.map +1 -0
  32. package/dist/lib/core/define.d.ts +19 -2
  33. package/dist/lib/core/define.d.ts.map +1 -0
  34. package/dist/lib/core/define.js.map +1 -1
  35. package/dist/lib/core/dispatchRequest.d.ts +1 -0
  36. package/dist/lib/core/dispatchRequest.d.ts.map +1 -0
  37. package/dist/lib/core/dispatchRequest.js +4 -0
  38. package/dist/lib/core/dispatchRequest.js.map +1 -1
  39. package/dist/lib/core/mergeConfig.d.ts +1 -0
  40. package/dist/lib/core/mergeConfig.d.ts.map +1 -0
  41. package/dist/lib/core/prepareRequest.d.ts +1 -0
  42. package/dist/lib/core/prepareRequest.d.ts.map +1 -0
  43. package/dist/lib/core/prepareRequest.js +1 -20
  44. package/dist/lib/core/prepareRequest.js.map +1 -1
  45. package/dist/lib/core/route.d.ts +11 -2
  46. package/dist/lib/core/route.d.ts.map +1 -0
  47. package/dist/lib/core/route.js.map +1 -1
  48. package/dist/lib/core/settle.d.ts +1 -0
  49. package/dist/lib/core/settle.d.ts.map +1 -0
  50. package/dist/lib/core/transformData.d.ts +1 -0
  51. package/dist/lib/core/transformData.d.ts.map +1 -0
  52. package/dist/lib/core/validateSchema.d.ts +1 -0
  53. package/dist/lib/core/validateSchema.d.ts.map +1 -0
  54. package/dist/lib/defaults/index.d.ts +1 -0
  55. package/dist/lib/defaults/index.d.ts.map +1 -0
  56. package/dist/lib/defaults/index.js +3 -3
  57. package/dist/lib/defaults/index.js.map +1 -1
  58. package/dist/lib/defaults/transitional.d.ts +1 -1
  59. package/dist/lib/defaults/transitional.d.ts.map +1 -0
  60. package/dist/lib/defaults/transitional.js +0 -1
  61. package/dist/lib/defaults/transitional.js.map +1 -1
  62. package/dist/lib/env/data.d.ts +2 -1
  63. package/dist/lib/env/data.d.ts.map +1 -0
  64. package/dist/lib/env/data.js +1 -1
  65. package/dist/lib/env/data.js.map +1 -1
  66. package/dist/lib/faxios.d.ts +115 -48
  67. package/dist/lib/faxios.d.ts.map +1 -0
  68. package/dist/lib/faxios.js +14 -2
  69. package/dist/lib/faxios.js.map +1 -1
  70. package/dist/lib/helpers/FaxiosURLSearchParams.d.ts +3 -1
  71. package/dist/lib/helpers/FaxiosURLSearchParams.d.ts.map +1 -0
  72. package/dist/lib/helpers/FaxiosURLSearchParams.js.map +1 -1
  73. package/dist/lib/helpers/HttpStatusCode.d.ts +1 -0
  74. package/dist/lib/helpers/HttpStatusCode.d.ts.map +1 -0
  75. package/dist/lib/helpers/buildURL.d.ts +1 -0
  76. package/dist/lib/helpers/buildURL.d.ts.map +1 -0
  77. package/dist/lib/helpers/buildURL.js +7 -1
  78. package/dist/lib/helpers/buildURL.js.map +1 -1
  79. package/dist/lib/helpers/cloneConfig.d.ts +4 -0
  80. package/dist/lib/helpers/cloneConfig.d.ts.map +1 -0
  81. package/dist/lib/helpers/cloneConfig.js +21 -0
  82. package/dist/lib/helpers/cloneConfig.js.map +1 -0
  83. package/dist/lib/helpers/combineURLs.d.ts +1 -0
  84. package/dist/lib/helpers/combineURLs.d.ts.map +1 -0
  85. package/dist/lib/helpers/composeSignals.d.ts +1 -0
  86. package/dist/lib/helpers/composeSignals.d.ts.map +1 -0
  87. package/dist/lib/helpers/composeSignals.js +8 -1
  88. package/dist/lib/helpers/composeSignals.js.map +1 -1
  89. package/dist/lib/helpers/cookies.d.ts +1 -0
  90. package/dist/lib/helpers/cookies.d.ts.map +1 -0
  91. package/dist/lib/helpers/estimateDataURLDecodedBytes.d.ts +1 -0
  92. package/dist/lib/helpers/estimateDataURLDecodedBytes.d.ts.map +1 -0
  93. package/dist/lib/helpers/formDataToJSON.d.ts +1 -0
  94. package/dist/lib/helpers/formDataToJSON.d.ts.map +1 -0
  95. package/dist/lib/helpers/isAbsoluteURL.d.ts +1 -0
  96. package/dist/lib/helpers/isAbsoluteURL.d.ts.map +1 -0
  97. package/dist/lib/helpers/isFaxiosError.d.ts +8 -2
  98. package/dist/lib/helpers/isFaxiosError.d.ts.map +1 -0
  99. package/dist/lib/helpers/isFaxiosError.js +5 -1
  100. package/dist/lib/helpers/isFaxiosError.js.map +1 -1
  101. package/dist/lib/helpers/isURLSameOrigin.d.ts +1 -0
  102. package/dist/lib/helpers/isURLSameOrigin.d.ts.map +1 -0
  103. package/dist/lib/helpers/parseHeaders.d.ts +1 -0
  104. package/dist/lib/helpers/parseHeaders.d.ts.map +1 -0
  105. package/dist/lib/helpers/progressEventReducer.d.ts +1 -0
  106. package/dist/lib/helpers/progressEventReducer.d.ts.map +1 -0
  107. package/dist/lib/helpers/sanitizeHeaderValue.d.ts +1 -0
  108. package/dist/lib/helpers/sanitizeHeaderValue.d.ts.map +1 -0
  109. package/dist/lib/helpers/speedometer.d.ts +1 -0
  110. package/dist/lib/helpers/speedometer.d.ts.map +1 -0
  111. package/dist/lib/helpers/substitutePathParams.d.ts +1 -0
  112. package/dist/lib/helpers/substitutePathParams.d.ts.map +1 -0
  113. package/dist/lib/helpers/throttle.d.ts +1 -0
  114. package/dist/lib/helpers/throttle.d.ts.map +1 -0
  115. package/dist/lib/helpers/toFormData.d.ts +1 -0
  116. package/dist/lib/helpers/toFormData.d.ts.map +1 -0
  117. package/dist/lib/helpers/toURLEncodedForm.d.ts +1 -0
  118. package/dist/lib/helpers/toURLEncodedForm.d.ts.map +1 -0
  119. package/dist/lib/helpers/trackStream.d.ts +1 -0
  120. package/dist/lib/helpers/trackStream.d.ts.map +1 -0
  121. package/dist/lib/helpers/validator.d.ts +1 -0
  122. package/dist/lib/helpers/validator.d.ts.map +1 -0
  123. package/dist/lib/platform.d.ts +2 -1
  124. package/dist/lib/platform.d.ts.map +1 -0
  125. package/dist/lib/plugins/attempt.d.ts +2 -0
  126. package/dist/lib/plugins/attempt.d.ts.map +1 -0
  127. package/dist/lib/plugins/attempt.js +4 -0
  128. package/dist/lib/plugins/attempt.js.map +1 -0
  129. package/dist/lib/plugins/authBearer.d.ts +31 -0
  130. package/dist/lib/plugins/authBearer.d.ts.map +1 -0
  131. package/dist/lib/plugins/authBearer.js +99 -0
  132. package/dist/lib/plugins/authBearer.js.map +1 -0
  133. package/dist/lib/plugins/definePlugin.d.ts +22 -0
  134. package/dist/lib/plugins/definePlugin.d.ts.map +1 -0
  135. package/dist/lib/plugins/definePlugin.js +14 -0
  136. package/dist/lib/plugins/definePlugin.js.map +1 -0
  137. package/dist/lib/plugins/retry.d.ts +66 -0
  138. package/dist/lib/plugins/retry.d.ts.map +1 -0
  139. package/dist/lib/plugins/retry.js +168 -0
  140. package/dist/lib/plugins/retry.js.map +1 -0
  141. package/dist/lib/plugins/timing.d.ts +32 -0
  142. package/dist/lib/plugins/timing.d.ts.map +1 -0
  143. package/dist/lib/plugins/timing.js +53 -0
  144. package/dist/lib/plugins/timing.js.map +1 -0
  145. package/dist/lib/types/standard-schema.d.ts +1 -0
  146. package/dist/lib/types/standard-schema.d.ts.map +1 -0
  147. package/dist/lib/types.d.ts +125 -34
  148. package/dist/lib/types.d.ts.map +1 -0
  149. package/dist/lib/utils.d.ts +1 -0
  150. package/dist/lib/utils.d.ts.map +1 -0
  151. package/package.json +42 -19
  152. package/skills/configure-requests/SKILL.md +380 -0
  153. package/skills/configure-requests/references/axios-differences.md +67 -0
  154. package/skills/configure-requests/references/plugins.md +127 -0
  155. package/src/index.ts +57 -0
  156. package/src/lib/adapters/fetch-helpers.ts +167 -0
  157. package/src/lib/adapters/fetch.ts +810 -0
  158. package/src/lib/cancel/CanceledError.ts +23 -0
  159. package/src/lib/cancel/isCancel.ts +10 -0
  160. package/src/lib/core/Faxios.ts +513 -0
  161. package/src/lib/core/FaxiosError.ts +283 -0
  162. package/src/lib/core/FaxiosHeaders.ts +529 -0
  163. package/src/lib/core/buildFullPath.ts +51 -0
  164. package/src/lib/core/define.ts +127 -0
  165. package/src/lib/core/dispatchRequest.ts +171 -0
  166. package/src/lib/core/mergeConfig.ts +175 -0
  167. package/src/lib/core/prepareRequest.ts +155 -0
  168. package/src/lib/core/route.ts +68 -0
  169. package/src/lib/core/settle.ts +20 -0
  170. package/src/lib/core/transformData.ts +23 -0
  171. package/src/lib/core/validateSchema.ts +53 -0
  172. package/src/lib/defaults/index.ts +221 -0
  173. package/src/lib/defaults/transitional.ts +9 -0
  174. package/src/lib/env/data.ts +1 -0
  175. package/src/lib/faxios.ts +306 -0
  176. package/src/lib/helpers/FaxiosURLSearchParams.ts +52 -0
  177. package/src/lib/helpers/HttpStatusCode.ts +77 -0
  178. package/src/lib/helpers/buildURL.ts +77 -0
  179. package/src/lib/helpers/cloneConfig.ts +23 -0
  180. package/src/lib/helpers/combineURLs.ts +11 -0
  181. package/src/lib/helpers/composeSignals.ts +74 -0
  182. package/src/lib/helpers/cookies.ts +68 -0
  183. package/src/lib/helpers/deprecatedMethod.ts +32 -0
  184. package/src/lib/helpers/estimateDataURLDecodedBytes.ts +95 -0
  185. package/src/lib/helpers/formDataToJSON.ts +122 -0
  186. package/src/lib/helpers/isAbsoluteURL.ts +13 -0
  187. package/src/lib/helpers/isFaxiosError.ts +19 -0
  188. package/src/lib/helpers/isURLSameOrigin.ts +16 -0
  189. package/src/lib/helpers/parseHeaders.ts +76 -0
  190. package/src/lib/helpers/progressEventReducer.ts +57 -0
  191. package/src/lib/helpers/sanitizeHeaderValue.ts +61 -0
  192. package/src/lib/helpers/speedometer.ts +55 -0
  193. package/src/lib/helpers/substitutePathParams.ts +13 -0
  194. package/src/lib/helpers/throttle.ts +45 -0
  195. package/src/lib/helpers/toFormData.ts +296 -0
  196. package/src/lib/helpers/toURLEncodedForm.ts +14 -0
  197. package/src/lib/helpers/trackStream.ts +123 -0
  198. package/src/lib/helpers/validator.ts +114 -0
  199. package/src/lib/platform.ts +44 -0
  200. package/src/lib/plugins/attempt.ts +3 -0
  201. package/src/lib/plugins/authBearer.ts +124 -0
  202. package/src/lib/plugins/definePlugin.ts +34 -0
  203. package/src/lib/plugins/retry.ts +245 -0
  204. package/src/lib/plugins/timing.ts +76 -0
  205. package/src/lib/types/standard-schema.ts +58 -0
  206. package/src/lib/types.ts +496 -0
  207. package/src/lib/utils.ts +932 -0
  208. package/dist/lib/core/InterceptorManager.d.ts +0 -9
  209. package/dist/lib/core/InterceptorManager.js +0 -28
  210. package/dist/lib/core/InterceptorManager.js.map +0 -1
package/README.md CHANGED
@@ -1,1817 +1,83 @@
1
1
  # faxios
2
2
 
3
- > Promise based HTTP client for the browser and node.js — a TypeScript-first fork of [axios](https://github.com/axios/axios).
3
+ > Promise based HTTP client for the browser and Node.js — a TypeScript-first fork of [axios](https://github.com/axios/axios).
4
4
 
5
5
  [![npm version](https://img.shields.io/npm/v/@gcmdev/faxios.svg?style=flat-square)](https://www.npmjs.org/package/@gcmdev/faxios)
6
-
7
- ## Table of contents
8
-
9
- - [Features](#features)
10
- - [Browser support](#browser-support)
11
- - [Installing](#installing)
12
- - [Package manager](#package-manager)
13
- - [Example](#example)
14
- - [Faxios API](#faxios-api)
15
- - [Request method aliases](#request-method-aliases)
16
- - [Concurrency](#concurrency-deprecated)
17
- - [Creating an instance](#creating-an-instance)
18
- - [Instance methods](#instance-methods)
19
- - [Typed endpoint builder — `faxios.define()`](#typed-endpoint-builder--faxiosdefine)
20
- - [Shared route builder — `faxios.route()`](#shared-route-builder--faxiosroute)
21
- - [Request config](#request-config)
22
- - [Response schema](#response-schema)
23
- - [Config defaults](#config-defaults)
24
- - [Global faxios defaults](#global-faxios-defaults)
25
- - [Custom instance defaults](#custom-instance-defaults)
26
- - [Config order of precedence](#config-order-of-precedence)
27
- - [Interceptors](#interceptors)
28
- - [Multiple interceptors](#multiple-interceptors)
29
- - [Handling errors](#handling-errors)
30
- - [Handling timeouts](#handling-timeouts)
31
- - [Cancellation](#cancellation)
32
- - [AbortController](#abortcontroller)
33
- - [Using application/x-www-form-urlencoded format](#using-applicationx-www-form-urlencoded-format)
34
- - [URLSearchParams](#urlsearchparams)
35
- - [Automatic serialization](#automatic-serialization-to-urlsearchparams)
36
- - [Using multipart/form-data format](#using-multipartform-data-format)
37
- - [FormData](#formdata)
38
- - [Automatic serialization](#automatic-serialization-to-formdata)
39
- - [Posting files](#posting-files)
40
- - [HTML form posting](#html-form-posting-browser)
41
- - [Progress capturing](#progress-capturing)
42
- - [FaxiosHeaders](#Faxiosheaders)
43
- - [Fetch adapter](#fetch-adapter)
44
- - [Custom fetch](#custom-fetch)
45
- - [Using with Tauri](#using-with-tauri)
46
- - [Using with SvelteKit](#using-with-sveltekit)
47
- - [Semver](#semver)
48
- - [Promises](#promises)
49
- - [TypeScript](#typescript)
50
- - [Contributing](#contributing)
51
- - [Local setup](#local-setup)
52
- - [Resources](#resources)
53
- - [Credits](#credits)
54
- - [License](#license)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://github.com/adrianbrowning/faxios/blob/main/LICENSE)
55
7
 
56
8
  ## Features
57
9
 
58
- - Make HTTP requests with the web-standard [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) API in every runtime — browser, Node.js 18+, Deno, and Bun.
59
- - Use the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API for asynchronous request handling.
60
- - Intercept requests and responses to add custom logic or transform data.
61
- - Transform request and response data.
62
- - Cancel requests with built-in cancellation APIs.
63
- - Serialize and parse [JSON](https://www.json.org/json-en.html) data.
64
- - Serialize data objects to `multipart/form-data` or `application/x-www-form-urlencoded`.
65
- - Add client-side protection against [Cross-Site Request Forgery](https://en.wikipedia.org/wiki/Cross-site_request_forgery).
66
-
67
- ## Browser support
68
-
69
- | Chrome | Firefox | Safari | Opera | Edge |
70
- | :------------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------: |
71
- | ![Chrome browser logo](https://raw.githubusercontent.com/alrra/browser-logos/main/src/chrome/chrome_48x48.png) | ![Firefox browser logo](https://raw.githubusercontent.com/alrra/browser-logos/main/src/firefox/firefox_48x48.png) | ![Safari browser logo](https://raw.githubusercontent.com/alrra/browser-logos/main/src/safari/safari_48x48.png) | ![Opera browser logo](https://raw.githubusercontent.com/alrra/browser-logos/main/src/opera/opera_48x48.png) | ![Edge browser logo](https://raw.githubusercontent.com/alrra/browser-logos/main/src/edge/edge_48x48.png) |
72
- | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ |
73
-
74
- [![Browser Matrix](https://saucelabs.com/open_sauce/build_matrix/faxios.svg)](https://saucelabs.com/u/faxios)
10
+ - Uses the web-standard [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) API in every runtime: browser, Node.js, Deno, and Bun.
11
+ - Promise API with onion-style [`.use()` middleware](https://adrianbrowning.github.io/faxios/pages/advanced/middleware) and built-in plugins for [retries](https://adrianbrowning.github.io/faxios/pages/advanced/retry), [bearer auth](https://adrianbrowning.github.io/faxios/pages/advanced/authentication) and timing.
12
+ - Request and response data transforms, with automatic JSON handling.
13
+ - Serializes objects to `multipart/form-data` or `application/x-www-form-urlencoded`.
14
+ - Cancellation with `AbortSignal`.
15
+ - Request and response validation with any Standard Schema v1 library (Zod, Valibot, ArkType). A failed `responseSchema` keeps the rejected body on `error.response.data`.
16
+ - Strictly typed request `headers`, with suggestions for common header names and `Content-Type` values.
17
+ - Typed endpoint builders: `faxios.define()` and `faxios.route()`.
18
+ - Client-side protection against Cross-Site Request Forgery.
19
+ - ESM-only, with TypeScript definitions included.
75
20
 
76
21
  ## Installing
77
22
 
78
- ### Package manager
79
-
80
- Using npm:
81
-
82
- ```bash
83
- $ npm install @gcmdev/faxios
84
- ```
85
-
86
- Using yarn:
87
-
88
- ```bash
89
- $ yarn add @gcmdev/faxios
90
- ```
91
-
92
- Using pnpm:
93
-
94
23
  ```bash
95
- $ pnpm add @gcmdev/faxios
24
+ npm install @gcmdev/faxios
96
25
  ```
97
26
 
98
- Using bun:
99
-
100
27
  ```bash
101
- $ bun add @gcmdev/faxios
28
+ pnpm add @gcmdev/faxios
102
29
  ```
103
30
 
104
- Once the package is installed, import it with `import`:
105
-
106
- ```js
107
- import faxios, { isCancel, FaxiosError } from '@gcmdev/faxios';
108
- ```
109
-
110
- You can also use the default export, since the named export is just a re-export from the Faxios factory:
111
-
112
- ```js
113
- import faxios from '@gcmdev/faxios';
114
-
115
- console.log(faxios.isCancel('something'));
116
- ```
117
-
118
-
119
31
  ## Example
120
32
 
121
33
  ```js
122
- import faxios from '@gcmdev/faxios';
123
-
124
- try {
125
- const response = await faxios.get('/user?ID=12345');
126
- console.log(response);
127
- } catch (error) {
128
- console.error(error);
129
- }
130
-
131
- // Optionally the request above could also be done as
132
- faxios
133
- .get('/user', {
134
- params: {
135
- ID: 12345,
136
- },
137
- timeout: 5000, // 5 seconds. See "Handling Timeouts" below for matching error handling
138
- })
139
- .then(function (response) {
140
- console.log(response);
141
- })
142
- .catch(function (error) {
143
- console.log(error);
144
- })
145
- .finally(function () {
146
- // always executed
147
- });
148
-
149
- // Want to use async/await? Add the `async` keyword to your outer function/method.
150
- async function getUser() {
151
- try {
152
- // Example: GET request with query parameters
153
- const response = await faxios.get('/user', {
154
- params: {
155
- ID: 12345
156
- }
157
- });
158
-
159
- // Using the `params` option improves readability and automatically formats query strings
160
-
161
- console.log(response);
162
- } catch (error) {
163
- console.error(error);
164
- }
165
- }
166
- ```
167
-
168
- > Note: Set a `timeout` in production. Without one, a stalled request can hang
169
- > indefinitely. See [Handling Timeouts](#handling-timeouts) for the matching error handling.
170
-
171
- > Note: `async/await` is part of ECMAScript 2017 and is not supported in Internet
172
- > Explorer and older browsers, so use with caution.
173
-
174
- Performing a `POST` request
175
-
176
- ```js
177
- const response = await faxios.post('/user', {
178
- firstName: 'Fred',
179
- lastName: 'Flintstone',
180
- });
181
- console.log(response);
182
- ```
183
-
184
- Performing multiple concurrent requests
185
-
186
- ```js
187
- function getUserAccount() {
188
- return faxios.get('/user/12345');
189
- }
190
-
191
- function getUserPermissions() {
192
- return faxios.get('/user/12345/permissions');
193
- }
194
-
195
- Promise.all([getUserAccount(), getUserPermissions()]).then(function (results) {
196
- const acct = results[0];
197
- const perm = results[1];
198
- });
199
- ```
200
-
201
- ## faxios API
202
-
203
- Requests can be made by passing the relevant config to `faxios`.
204
-
205
- ##### faxios(config)
206
-
207
- ```js
208
- // Send a POST request
209
- faxios({
210
- method: 'post',
211
- url: '/user/12345',
212
- data: {
213
- firstName: 'Fred',
214
- lastName: 'Flintstone',
215
- },
216
- });
217
- ```
218
-
219
- ```js
220
- // GET request for remote image in node.js
221
- const response = await faxios({
222
- method: 'get',
223
- url: 'https://bit.ly/2mTM3nY',
224
- responseType: 'stream',
225
- });
226
- response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'));
227
- ```
228
-
229
- ##### faxios(url[, config])
230
-
231
- ```js
232
- // Send a GET request (default method)
233
- faxios('/user/12345');
234
- ```
235
-
236
- ### Request method aliases
237
-
238
- For convenience, aliases have been provided for all common request methods.
239
-
240
- ##### faxios.request(config)
241
-
242
- ##### faxios.get(url[, config])
243
-
244
- ##### faxios.delete(url[, config])
245
-
246
- ##### faxios.head(url[, config])
247
-
248
- ##### faxios.options(url[, config])
249
-
250
- ##### faxios.post(url[, data[, config]])
251
-
252
- ##### faxios.put(url[, data[, config]])
253
-
254
- ##### faxios.patch(url[, data[, config]])
255
-
256
- ###### Note
257
-
258
- When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config.
259
-
260
- ### Concurrency (deprecated)
261
-
262
- Use `Promise.all` instead of these helpers.
263
-
264
- Helper functions for dealing with concurrent requests.
265
-
266
- faxios.all(iterable)
267
- faxios.spread(callback)
268
-
269
- ### Creating an instance
270
-
271
- You can create a new instance of faxios with a custom config.
272
-
273
- ##### faxios.create([config])
274
-
275
- ```js
276
- const instance = faxios.create({
277
- baseURL: 'https://some-domain.com/api/',
278
- timeout: 1000,
279
- headers: { 'X-Custom-Header': 'foobar' },
280
- });
281
- ```
282
-
283
- ### Instance methods
284
-
285
- The following instance methods are available. Faxios merges the specified config with the instance config.
286
-
287
- ##### faxios#request(config)
288
-
289
- ##### faxios#get(url[, config])
290
-
291
- ##### faxios#delete(url[, config])
292
-
293
- ##### faxios#head(url[, config])
294
-
295
- ##### faxios#options(url[, config])
296
-
297
- ##### faxios#post(url[, data[, config]])
298
-
299
- ##### faxios#put(url[, data[, config]])
300
-
301
- ##### faxios#patch(url[, data[, config]])
302
-
303
- ##### faxios#getUri([config])
304
-
305
- ### Typed endpoint builder — `faxios.define()`
306
-
307
- Create reusable, fully-typed endpoint functions with schema enforcement locked at define-time:
308
-
309
- ```ts
310
- import faxios from '@gcmdev/faxios';
311
- import { z } from 'zod';
312
-
313
- const getUser = faxios.define('get', '/users/{id}', {
314
- pathParamsSchema: z.object({ id: z.string() }),
315
- responseSchema: z.object({ name: z.string(), age: z.number() }),
316
- });
317
-
318
- const response = await getUser({ pathParams: { id: '123' } });
319
- // response.data is typed as { name: string; age: number }
320
- ```
321
-
322
- Schemas set at define-time cannot be overridden per-call (security by design).
323
-
324
- ### Shared route builder — `faxios.route()`
325
-
326
- Create a builder with typed HTTP method helpers and shared route-level config:
327
-
328
- ```ts
329
- import faxios from '@gcmdev/faxios';
330
- import { z } from 'zod';
331
-
332
- const users = faxios.route('/users/{id}', {
333
- pathParamsSchema: z.object({ id: z.string() }),
334
- });
335
-
336
- const getUser = users.get({ responseSchema: z.object({ name: z.string() }) });
337
- const updateUser = users.put({ requestSchema: z.object({ name: z.string() }) });
338
-
339
- const res = await getUser({ pathParams: { id: '123' } });
340
- ```
341
-
342
- ## Request config
343
-
344
- ### Security notice: decompression-bomb protection is opt-in
345
-
346
- By default `maxContentLength` and `maxBodyLength` are `-1` (unlimited). A malicious or compromised server can return a tiny gzip/deflate/brotli/zstd body that expands to gigabytes and exhaust the process. The fetch adapter enforces these caps in every runtime.
347
-
348
- If you call servers you do not fully trust, **set a cap**:
349
-
350
- ```js
351
- faxios.defaults.maxContentLength = 10 * 1024 * 1024; // 10 MB
352
- faxios.defaults.maxBodyLength = 10 * 1024 * 1024;
353
- ```
354
-
355
- See the [security guide](https://faxios.rest/pages/misc/security.html) for details.
356
-
357
- These config options are available for requests. Only `url` is required. Requests default to `GET` when `method` is not set.
358
-
359
- ```js
360
- {
361
- // `url` is the server URL for the request
362
- url: '/user',
363
-
364
- // `method` is the request method to be used when making the request
365
- method: 'get', // default
366
-
367
- // Faxios prepends `baseURL` to `url` unless `url` is absolute and `allowAbsoluteUrls` is set to true.
368
- // It can be convenient to set `baseURL` for an instance of faxios to pass relative URLs
369
- // to the methods of that instance.
370
- baseURL: 'https://some-domain.com/api/',
371
-
372
- // `allowAbsoluteUrls` determines whether absolute URLs override `baseURL`.
373
- // Defaults to `false` when `baseURL` is set, `true` otherwise.
374
- // When `false`, absolute values for `url` are prepended by `baseURL`.
375
- allowAbsoluteUrls: true,
376
-
377
- // `transformRequest` allows changes to the request data before it is sent to the server
378
- // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
379
- // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
380
- // FormData or Stream
381
- // You may modify the headers object.
382
- transformRequest: [function (data, headers) {
383
- // Do whatever you want to transform the data
384
-
385
- return data;
386
- }],
387
-
388
- // `transformResponse` allows changes to the response data to be made before
389
- // it is passed to then/catch
390
- transformResponse: [function (data) {
391
- // Do whatever you want to transform the data
392
-
393
- return data;
394
- }],
395
-
396
- // `parseReviver` is an optional function passed as the
397
- // second argument (reviver) to JSON.parse()
398
- parseReviver: function (key, value, context) {
399
- // In modern environments, context.source provides the raw JSON string
400
- // allowing for precision-safe parsing of BigInt
401
- if (typeof value === 'number' && context?.source) {
402
- const isInteger = Number.isInteger(value);
403
- const isUnsafe = !Number.isSafeInteger(value);
404
- const isValidIntegerString = /^-?\d+$/.test(context.source);
405
-
406
- if (isInteger && isUnsafe && isValidIntegerString) {
407
- try {
408
- return BigInt(context.source);
409
- } catch {
410
- // Fallback: return original value if parsing fails
411
- }
412
- }
413
- }
414
- return value;
415
- },
416
-
417
- // `headers` are custom headers to be sent
418
- headers: {'X-Requested-With': 'XMLHttpRequest'},
419
-
420
- // `params` are the URL parameters to be sent with the request
421
- // Must be a plain object or a URLSearchParams object
422
- params: {
423
- ID: 12345
424
- },
425
-
426
- // `paramsSerializer` is an optional config that allows you to customize serializing `params`.
427
- paramsSerializer: {
428
-
429
- // Custom encoder function which sends key/value pairs in an iterative fashion.
430
- encode?: (param: string): string => { /* Do custom operations here and return transformed string */ },
431
-
432
- // Custom serializer function for the entire parameter. Allows the user to mimic pre 1.x behaviour.
433
- serialize?: (params: Record<string, any>, options?: ParamsSerializerOptions ),
434
-
435
- // Configuration for formatting array indexes in the params.
436
- indexes: false, // Three available options: (1) indexes: null (leads to no brackets), (2) (default) indexes: false (leads to empty brackets), (3) indexes: true (leads to brackets with indexes).
437
-
438
- // Maximum object nesting depth when serializing params. Payloads deeper than this throw an
439
- // FaxiosError with code ERR_FORM_DATA_DEPTH_EXCEEDED. Default: 100. Set to Infinity to disable.
440
- maxDepth: 100
441
-
442
- },
443
-
444
- // `data` is the data to be sent as the request body
445
- // Only applicable for request methods 'PUT', 'POST', 'DELETE', and 'PATCH'
446
- // When no `transformRequest` is set, it must be of one of the following types:
447
- // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
448
- // - Browser only: FormData, File, Blob
449
- // - React Native: FormData
450
- // - Node only: Stream, Buffer, FormData (form-data package)
451
- data: {
452
- firstName: 'Fred'
453
- },
454
-
455
- // `formDataHeaderPolicy` controls how node.js FormData#getHeaders() is copied.
456
- // 'legacy' (default) copies all returned headers for v1 compatibility.
457
- // 'content-only' copies only Content-Type and Content-Length.
458
- formDataHeaderPolicy: 'legacy',
459
-
460
- // syntax alternative to send data into the body
461
- // method post
462
- // only the value is sent, not the key
463
- data: 'Country=Brasil&City=Belo Horizonte',
464
-
465
- // `timeout` specifies the number of milliseconds before the request times out.
466
- // If the request takes longer than `timeout`, Faxios aborts it.
467
- timeout: 1000, // default is `0` (no timeout)
468
-
469
- // `withCredentials` indicates whether or not cross-site Access-Control requests
470
- // should be made using credentials
471
- // This only controls whether the browser sends credentials.
472
- // It does not control whether the XSRF header is added.
473
- withCredentials: false, // default
474
-
475
- // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
476
- // This will set an `Authorization` header, overwriting any existing
477
- // `Authorization` custom headers you have set using `headers`.
478
- // If `auth` is omitted, the fetch adapter can read
479
- // HTTP Basic auth credentials from the request URL, for example
480
- // `https://user:pass@example.com`. Faxios decodes percent-encoded URL
481
- // credentials, and `auth` takes precedence over URL-embedded credentials.
482
- // Please note that only HTTP Basic auth is configurable through this parameter.
483
- // For Bearer tokens and such, use `Authorization` custom headers instead.
484
- auth: {
485
- username: 'janedoe',
486
- password: 's00pers3cret'
487
- },
488
-
489
- // `responseType` indicates the type of data that the server will respond with
490
- // options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
491
- // browser only: 'blob'
492
- responseType: 'json', // default
493
-
494
- // `responseEncoding` indicates encoding to use for decoding responses (Node.js only)
495
- // Note: Ignored for `responseType` of 'stream' or client-side requests
496
- // options are: 'ascii', 'ASCII', 'ansi', 'ANSI', 'binary', 'BINARY', 'base64', 'BASE64', 'base64url',
497
- // 'BASE64URL', 'hex', 'HEX', 'latin1', 'LATIN1', 'ucs-2', 'UCS-2', 'ucs2', 'UCS2', 'utf-8', 'UTF-8',
498
- // 'utf8', 'UTF8', 'utf16le', 'UTF16LE'
499
- responseEncoding: 'utf8', // default
500
-
501
- // `xsrfCookieName` is the name of the cookie to use as a value for the xsrf token
502
- xsrfCookieName: 'XSRF-TOKEN', // default
503
-
504
- // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
505
- xsrfHeaderName: 'X-XSRF-TOKEN', // default
506
-
507
- // `withXSRFToken` defines whether to send the XSRF header in browser requests.
508
- // `undefined` (default) - set XSRF header only for the same origin requests
509
- // `true` - always set XSRF header, including for cross-origin requests
510
- // `false` - never set XSRF header
511
- // function - resolve with custom logic; receives the internal config object
512
- withXSRFToken: boolean | undefined | ((config: InternalFaxiosRequestConfig) => boolean | undefined),
513
-
514
- // `withXSRFToken` controls whether Faxios reads the XSRF cookie and sets the XSRF header.
515
- // - `undefined` (default): the XSRF header is set only for same-origin requests.
516
- // - `true`: attempt to set the XSRF header for all requests (including cross-origin).
517
- // - `false`: never set the XSRF header.
518
- // - function: a callback that receives the request `config` and returns `true`,
519
- // `false`, or `undefined` to decide per-request behavior.
520
- //
521
- // Note about `withCredentials`: `withCredentials` controls whether cross-site
522
- // requests include credentials (cookies and HTTP auth). In older Faxios versions,
523
- // setting `withCredentials: true` implicitly caused Faxios to set the XSRF header
524
- // for cross-origin requests. Newer Faxios separates these concerns: to allow the
525
- // XSRF header to be sent for cross-origin requests you should set both
526
- // `withCredentials: true` and `withXSRFToken: true`.
527
- //
528
- // Example:
529
- // faxios.get('/user', { withCredentials: true, withXSRFToken: true });
530
-
531
- // `onDownloadProgress` allows handling of progress events for downloads.
532
- // Upload progress (`onUploadProgress`) is not supported because the
533
- // web-standard fetch API cannot emit upload progress events.
534
- onDownloadProgress: function ({loaded, total, progress, bytes, estimated, rate, download = true}) {
535
- // Do whatever you want with the Faxios progress event
536
- },
537
-
538
- // `maxContentLength` defines the max size of the response content in bytes.
539
- // It is enforced by the fetch adapter.
540
- maxContentLength: 2000,
541
-
542
- // `maxBodyLength` defines the max size of the request content in bytes.
543
- // It is enforced by the fetch adapter when the body length can be determined.
544
- maxBodyLength: 2000,
545
-
546
- // `redact` masks matching config keys when FaxiosError#toJSON() is called.
547
- // Matching is case-insensitive and recursive. It does not change the request.
548
- redact: ['authorization', 'password'],
549
-
550
- // `validateStatus` defines whether to resolve or reject the promise for a given
551
- // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
552
- // or `undefined`), Faxios resolves the promise; otherwise, Faxios rejects it.
553
- validateStatus: function (status) {
554
- return status >= 200 && status < 300; // default
555
- },
556
-
557
- // cancel Faxios requests using AbortController
558
- signal: new AbortController().signal,
559
-
560
- // transitional options for backward compatibility that may be removed in the newer versions
561
- transitional: {
562
- // silent JSON parsing mode
563
- // `true` - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour)
564
- // `false` - throw SyntaxError if JSON parsing failed
565
- // Important: this option only takes effect when `responseType` is explicitly set to 'json'.
566
- // When `responseType` is omitted (defaults to no value), faxios uses `forcedJSONParsing`
567
- // to attempt JSON parsing, but will silently return the raw string on failure regardless
568
- // of this setting. To have invalid JSON throw errors, use:
569
- // { responseType: 'json', transitional: { silentJSONParsing: false } }
570
- silentJSONParsing: true, // default value for the current Faxios version
571
-
572
- // try to parse the response string as JSON even if `responseType` is not 'json'
573
- forcedJSONParsing: true,
574
-
575
- // throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts
576
- clarifyTimeoutError: false,
577
-
578
- // advertise `zstd` in the default Accept-Encoding header when the current
579
- // runtime's fetch implementation can decompress zstd responses.
580
- advertiseZstdAcceptEncoding: false,
581
-
582
- // when true (default), `validateStatus: undefined` resolves every response status
583
- // (legacy behavior). Set to false to make explicit undefined behave like omitted,
584
- // using the configured/default validator (reject non-2xx).
585
- validateStatusUndefinedResolves: true,
586
-
587
- // use the legacy interceptor request/response ordering
588
- legacyInterceptorReqResOrdering: true, // default
589
- },
590
-
591
- // `responseSchema` accepts any Standard Schema v1 compliant schema (Zod, Valibot, ArkType).
592
- // Validates response.data after transformResponse; throws ERR_BAD_RESPONSE_SCHEMA on failure.
593
- // TypeScript infers response.data type from the schema's output type.
594
- responseSchema: UserSchema,
595
-
596
- // `requestSchema` validates config.data before sending; throws ERR_BAD_REQUEST_SCHEMA on failure.
597
- requestSchema: CreateUserSchema,
598
-
599
- // `paramsSchema` validates config.params before URL construction; throws ERR_BAD_PARAMS_SCHEMA.
600
- paramsSchema: QuerySchema,
601
-
602
- // `pathParams` substitutes {key} placeholders in the URL.
603
- pathParams: { id: '123' },
604
-
605
- // `pathParamsSchema` validates pathParams before substitution; throws ERR_BAD_PATH_PARAMS_SCHEMA.
606
- // When set, pathParams is required.
607
- pathParamsSchema: PathSchema,
608
-
609
- env: {
610
- // The FormData class to be used to automatically serialize the payload into a FormData object
611
- FormData: window?.FormData || global?.FormData
612
- },
613
-
614
- formSerializer: {
615
- visitor: (value, key, path, helpers) => {}; // custom visitor function to serialize form values
616
- dots: boolean; // use dots instead of brackets format
617
- metaTokens: boolean; // keep special endings like {} in parameter key
618
- indexes: boolean; // array indexes format null - no brackets, false - empty brackets, true - brackets with indexes
619
- maxDepth: 100; // maximum object nesting depth; throws FaxiosError (ERR_FORM_DATA_DEPTH_EXCEEDED) if exceeded. Set to Infinity to disable.
620
- }
621
- }
622
- ```
623
-
624
- ### Strict RFC 3986 percent-encoding for query params
625
-
626
- By default, faxios decodes `%3A`, `%24`, `%2C` and `%20` back to `:`, `$`, `,` and `+` for readability (the `+` follows the `application/x-www-form-urlencoded` convention for spaces in query strings). These characters are valid in a query component under [RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986#section-3.4), so the default output is correct, but some backends require strict percent-encoding and reject the readable form.
627
-
628
- Override the default encoder via `paramsSerializer.encode`:
629
-
630
- ```js
631
- // Per-request: emit strict RFC 3986 percent-encoding for query values
632
- faxios.get('/foo', {
633
- params: { filter: JSON.stringify({ startedAt: '2026-01-23' }) },
634
- paramsSerializer: { encode: encodeURIComponent }
635
- });
636
-
637
- // Or set it on the instance defaults
638
- const client = faxios.create({
639
- paramsSerializer: { encode: encodeURIComponent }
640
- });
641
- ```
642
-
643
- ## Response schema
644
-
645
- The response to a request contains the following information.
646
-
647
- ```js
648
- {
649
- // `data` is the response that was provided by the server
650
- data: {},
651
-
652
- // `status` is the HTTP status code from the server response
653
- status: 200,
654
-
655
- // `statusText` is the HTTP status message from the server response
656
- statusText: 'OK',
657
-
658
- // `headers` the HTTP headers that the server responded with
659
- // All header names are lowercase and can be accessed using the bracket notation.
660
- // Example: `response.headers['content-type']`
661
- headers: {},
662
-
663
- // `config` is the config that was provided to `faxios` for the request
664
- config: {},
665
-
666
- // `request` is the request that generated this response
667
- // It is the fetch `Request` instance used for the request
668
- request: {}
669
- }
670
- ```
671
-
672
- When using `then`, you receive the response like this:
673
-
674
- ```js
675
- const response = await faxios.get('/user/12345');
676
- console.log(response.data);
677
- console.log(response.status);
678
- console.log(response.statusText);
679
- console.log(response.headers);
680
- console.log(response.config);
681
- ```
682
-
683
- When using `catch`, or passing a [rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) as the second parameter of `then`, read the response from the `error` object. See [Handling errors](#handling-errors).
684
-
685
- ## Config defaults
686
-
687
- Config defaults apply to every request.
688
-
689
- ### Global faxios defaults
690
-
691
- ```js
692
- faxios.defaults.baseURL = 'https://api.example.com';
693
-
694
- // Important: If you use faxios with multiple domains, Faxios sends AUTH_TOKEN to all of them.
695
- // See below for an example using Custom instance defaults instead.
696
- faxios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
697
-
698
- faxios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
699
- ```
700
-
701
- ### Custom instance defaults
702
-
703
- ```js
704
- // Set config defaults when creating the instance
705
- const instance = faxios.create({
706
- baseURL: 'https://api.example.com',
707
- });
708
-
709
- // Alter defaults after instance has been created
710
- instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
711
- ```
712
-
713
- ### Config order of precedence
714
-
715
- Faxios merges config in this order: library defaults from [lib/defaults/index.js](https://github.com/faxios/faxios/blob/main/lib/defaults/index.js#L49), the instance `defaults` property, and the request `config` argument. Later values take precedence over earlier ones.
716
-
717
- ```js
718
- // Create an instance using the config defaults provided by the library
719
- // At this point the timeout config value is `0` as is the default for the library
720
- const instance = faxios.create();
34
+ import faxios from "@gcmdev/faxios";
721
35
 
722
- // Override timeout default for the library
723
- // Now all requests using this instance will wait 2.5 seconds before timing out
724
- instance.defaults.timeout = 2500;
725
-
726
- // Override timeout for this request as it's known to take a long time
727
- instance.get('/longRequest', {
36
+ const { data: user } = await faxios.get("/user", {
37
+ params: { ID: 12345 },
728
38
  timeout: 5000,
729
39
  });
730
- ```
731
-
732
- ## Interceptors
733
-
734
- You can intercept requests or responses before methods like `.get()` or `.post()`
735
- resolve their promises (before code inside `then` or `catch`, or after `await`)
736
-
737
- ```js
738
- const instance = faxios.create();
739
-
740
- // Add a request interceptor
741
- instance.interceptors.request.use(
742
- function (config) {
743
- // Do something before the request is sent
744
- return config;
745
- },
746
- function (error) {
747
- // Do something with the request error
748
- return Promise.reject(error);
749
- }
750
- );
751
-
752
- // Add a response interceptor
753
- instance.interceptors.response.use(
754
- function (response) {
755
- // Any status code that lies within the range of 2xx causes this function to trigger
756
- // Do something with response data
757
- return response;
758
- },
759
- function (error) {
760
- // Any status codes that fall outside the range of 2xx cause this function to trigger
761
- // Do something with response error
762
- return Promise.reject(error);
763
- }
764
- );
765
- ```
766
-
767
- If you need to remove an interceptor later you can.
768
-
769
- ```js
770
- const instance = faxios.create();
771
- const myInterceptor = instance.interceptors.request.use(function () {
772
- /*...*/
773
- });
774
- instance.interceptors.request.eject(myInterceptor);
775
- ```
776
-
777
- You can also clear all interceptors for requests or responses.
778
-
779
- ```js
780
- const instance = faxios.create();
781
- instance.interceptors.request.use(function () {
782
- /*...*/
783
- });
784
- instance.interceptors.request.clear(); // Removes interceptors from requests
785
- instance.interceptors.response.use(function () {
786
- /*...*/
787
- });
788
- instance.interceptors.response.clear(); // Removes interceptors from responses
789
- ```
790
40
 
791
- You can add interceptors to a custom instance of faxios.
792
-
793
- ```js
794
- const instance = faxios.create();
795
- instance.interceptors.request.use(function () {
796
- /*...*/
41
+ const response = await faxios.post("/user", {
42
+ firstName: "Fred",
43
+ lastName: "Flintstone",
797
44
  });
798
45
  ```
799
46
 
800
- When you add request interceptors, they are presumed to be asynchronous by default. This can cause a delay
801
- in the execution of your faxios request when the main thread is blocked (a promise is created under the hood for
802
- the interceptor and your request gets put at the bottom of the call stack). If your request interceptors are synchronous you can add a flag
803
- to the options object that will tell faxios to run the code synchronously and avoid any delays in request execution.
804
-
805
- ```js
806
- faxios.interceptors.request.use(
807
- function (config) {
808
- config.headers.test = 'I am only a header!';
809
- return config;
810
- },
811
- null,
812
- { synchronous: true }
813
- );
814
- ```
815
-
816
- If you want to execute a particular interceptor based on a runtime check,
817
- you can add a `runWhen` function to the options object. The request interceptor will not run **if and only if** the return
818
- of `runWhen` is `false`. Faxios calls the function with the config
819
- object (don't forget that you can bind your own arguments to it as well.) This can be handy when you have an
820
- asynchronous request interceptor that only needs to run at certain times.
47
+ Add behaviour to every request with `.use()`. Keep the instance it returns: only that value is typed with the plugin's options.
821
48
 
822
49
  ```js
823
- function onGetCall(config) {
824
- return config.method === 'get';
825
- }
826
- faxios.interceptors.request.use(
827
- function (config) {
828
- config.headers.test = 'special get headers';
829
- return config;
830
- },
831
- null,
832
- { runWhen: onGetCall }
833
- );
834
- ```
835
-
836
- > Note: The options parameter (with `synchronous` and `runWhen` properties) is only supported for request interceptors at the moment.
837
-
838
- ### Interceptor execution order
839
-
840
- Request and response interceptors use different execution orders.
841
-
842
- Request interceptors run in reverse order (LIFO: last in, first out). The last interceptor added runs first.
843
-
844
- Response interceptors run in the order they were added (FIFO: first in, first out). The first interceptor added runs first.
845
-
846
- Example:
847
-
848
- ```js
849
- const instance = faxios.create();
850
-
851
- const interceptor = (id) => (base) => {
852
- console.log(id);
853
- return base;
854
- };
50
+ import faxios from "@gcmdev/faxios";
51
+ import { retry } from "@gcmdev/faxios/plugins/retry";
855
52
 
856
- instance.interceptors.request.use(interceptor('Request Interceptor 1'));
857
- instance.interceptors.request.use(interceptor('Request Interceptor 2'));
858
- instance.interceptors.request.use(interceptor('Request Interceptor 3'));
859
- instance.interceptors.response.use(interceptor('Response Interceptor 1'));
860
- instance.interceptors.response.use(interceptor('Response Interceptor 2'));
861
- instance.interceptors.response.use(interceptor('Response Interceptor 3'));
53
+ const api = faxios.create().use(retry());
862
54
 
863
- // Console output:
864
- // Request Interceptor 3
865
- // Request Interceptor 2
866
- // Request Interceptor 1
867
- // [HTTP request is made]
868
- // Response Interceptor 1
869
- // Response Interceptor 2
870
- // Response Interceptor 3
55
+ const { data } = await api.get("/user", { headers: { Accept: "application/json" } });
871
56
  ```
872
57
 
873
- ### Multiple interceptors
874
-
875
- When a response is fulfilled and multiple response interceptors are registered:
876
-
877
- - Each interceptor runs in registration order.
878
- - Each interceptor receives the result from the previous interceptor.
879
- - The chain returns the result from the last interceptor.
880
- - If a fulfillment interceptor throws, Faxios skips the next fulfillment interceptor and calls the next rejection interceptor.
881
- - After the error is caught, later fulfillment interceptors run again, just like in a promise chain.
882
-
883
- Read [the interceptor tests](./test/specs/interceptors.spec.js) to see all this in code.
884
-
885
- ## Error types
886
-
887
- Faxios error messages include details that can help you debug the request.
888
-
889
- Faxios errors use this structure:
890
- | Property | Definition |
891
- | -------- | ---------- |
892
- | message | A quick summary of the error message and the status it failed with. |
893
- | name | This defines where the error originated from. For faxios, it will always be an 'FaxiosError'. |
894
- | stack | Stack trace for the error. |
895
- | config | An faxios config object with specific instance configurations defined by the user from when the request was made |
896
- | code | Faxios error code. The table below lists internal Faxios error codes. |
897
- | status | HTTP response status code. See [here](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) for common HTTP response status code meanings.
58
+ ## Documentation
898
59
 
899
- These are the internal Faxios error codes:
60
+ The full documentation is at https://adrianbrowning.github.io/faxios/.
900
61
 
901
- | Code | Definition |
902
- | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
903
- | ERR_BAD_OPTION_VALUE | Invalid value provided in faxios configuration. |
904
- | ERR_BAD_OPTION | Invalid option provided in faxios configuration. |
905
- | ERR_NOT_SUPPORT | Feature or method not supported in the current faxios environment. |
906
- | ERR_DEPRECATED | Deprecated feature or method used in faxios. |
907
- | ERR_INVALID_URL | Invalid URL provided for faxios request. |
908
- | ECONNABORTED | Typically indicates that the request has been timed out (unless `transitional.clarifyTimeoutError` is set) or aborted by the browser or its plugin. |
909
- | ERR_CANCELED | The user explicitly canceled the request with an AbortSignal or CancelToken. |
910
- | ETIMEDOUT | Request timed out after exceeding the configured Faxios timeout. Set `transitional.clarifyTimeoutError` to `true`; otherwise Faxios throws a generic `ECONNABORTED` error. |
911
- | ERR_NETWORK | Network-related issue. In the browser, this error can also be caused by a [CORS](https://developer.mozilla.org/ru/docs/Web/HTTP/Guides/CORS) or [Mixed Content](https://developer.mozilla.org/en-US/docs/Web/Security/Mixed_content) policy violation. The browser does not allow the JS code to clarify the real reason for the error caused by security issues, so please check the console. |
912
- | ERR_FR_TOO_MANY_REDIRECTS | Request exceeded the configured maximum number of redirects. |
913
- | ERR_BAD_RESPONSE | Response cannot be parsed properly or is in an unexpected format. Usually related to a response with `5xx` status code. |
914
- | ERR_BAD_REQUEST | The request has an unexpected format or is missing required parameters. Usually related to a response with `4xx` status code. |
915
-
916
- ## Handling errors
917
-
918
- By default, Faxios rejects responses with status codes outside the 2xx range.
919
-
920
- ```js
921
- faxios.get('/user/12345').catch(function (error) {
922
- if (error.response) {
923
- // The request was made and the server responded with a status code
924
- // that falls out of the range of 2xx
925
- console.log(error.response.data);
926
- console.log(error.response.status);
927
- console.log(error.response.headers);
928
- } else if (error.request) {
929
- // The request was made but no response was received
930
- // `error.request` is the fetch `Request` instance used for the request
931
- console.log(error.request);
932
- } else {
933
- // Something happened in setting up the request that triggered an Error
934
- console.log('Error', error.message);
935
- }
936
- console.log(error.config);
937
- });
938
- ```
939
-
940
- Use `validateStatus` to override the default condition (`status >= 200 && status < 300`) and choose which HTTP status codes should reject.
941
-
942
- ```js
943
- faxios.get('/user/12345', {
944
- validateStatus: function (status) {
945
- return status < 500; // Resolve only if the status code is less than 500
946
- },
947
- });
948
- ```
949
-
950
- Use `toJSON` to get more information about the HTTP error.
951
-
952
- ```js
953
- faxios.get('/user/12345').catch(function (error) {
954
- console.log(error.toJSON());
955
- });
956
- ```
957
-
958
- To avoid logging secrets from `error.config`, pass a `redact` array in the request config. Matching config keys are masked case-insensitively at any depth when `FaxiosError#toJSON()` is called.
959
-
960
- ```js
961
- faxios.get('/user/12345', {
962
- headers: { Authorization: 'Bearer token' },
963
- redact: ['authorization']
964
- }).catch(function (error) {
965
- console.log(error.toJSON().config.headers.Authorization); // [REDACTED ****]
966
- });
967
- ```
968
-
969
- ## Handling timeouts
970
-
971
- ```js
972
- async function fetchWithTimeout() {
973
- try {
974
- const response = await faxios.get('https://example.com/data', {
975
- timeout: 5000, // 5 seconds
976
- transitional: {
977
- // set to true if you prefer ETIMEDOUT over ECONNABORTED
978
- clarifyTimeoutError: false,
979
- },
980
- });
981
-
982
- console.log('Response:', response.data);
983
- } catch (error) {
984
- if (faxios.isFaxiosError(error)) {
985
- if (error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT') {
986
- console.error('Request timed out. Please try again.');
987
- return;
988
- }
989
-
990
- console.error('Faxios error:', error.message);
991
- return;
992
- }
993
-
994
- console.error('Unexpected error:', error);
995
- }
996
- }
997
- ```
998
-
999
- ## Cancellation
1000
-
1001
- ### AbortController
1002
-
1003
- Since `v0.22.0`, Faxios supports AbortController:
1004
-
1005
- ```js
1006
- const controller = new AbortController();
1007
-
1008
- faxios
1009
- .get('/foo/bar', {
1010
- signal: controller.signal,
1011
- })
1012
- .then(function (response) {
1013
- //...
1014
- });
1015
- // cancel the request
1016
- controller.abort();
1017
- ```
1018
-
1019
-
1020
- > Note: You can cancel several requests with the same cancel token or abort controller.
1021
- > If a cancellation token is already cancelled when an Faxios request starts, Faxios cancels the request immediately without making a real request.
1022
-
1023
- > During the transition period, you can use both cancellation APIs, even for the same request:
1024
-
1025
- ## Using `application/x-www-form-urlencoded` format
1026
-
1027
- ### URLSearchParams
1028
-
1029
- By default, faxios serializes JavaScript objects to `JSON`. To send data as [`application/x-www-form-urlencoded`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST), use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API. It works in most browsers and in [Node](https://nodejs.org/api/url.html#url_class_urlsearchparams) v10 and later.
1030
-
1031
- ```js
1032
- const params = new URLSearchParams({ foo: 'bar' });
1033
- params.append('extraparam', 'value');
1034
- faxios.post('/foo', params);
1035
- ```
1036
-
1037
-
1038
-
1039
- ### Automatic serialization to URLSearchParams
1040
-
1041
- Faxios automatically serializes the data object to urlencoded format if the content-type header is set to "application/x-www-form-urlencoded".
1042
-
1043
- ```js
1044
- const data = {
1045
- x: 1,
1046
- arr: [1, 2, 3],
1047
- arr2: [1, [2], 3],
1048
- users: [
1049
- { name: 'Peter', surname: 'Griffin' },
1050
- { name: 'Thomas', surname: 'Anderson' },
1051
- ],
1052
- };
1053
-
1054
- await faxios.postForm('https://postman-echo.com/post', data, {
1055
- headers: { 'content-type': 'application/x-www-form-urlencoded' },
1056
- });
1057
- ```
1058
-
1059
- The server receives these fields:
1060
-
1061
- ```js
1062
- {
1063
- x: '1',
1064
- 'arr[]': [ '1', '2', '3' ],
1065
- 'arr2[0]': '1',
1066
- 'arr2[1][0]': '2',
1067
- 'arr2[2]': '3',
1068
- 'arr3[]': [ '1', '2', '3' ],
1069
- 'users[0][name]': 'Peter',
1070
- 'users[0][surname]': 'griffin',
1071
- 'users[1][name]': 'Thomas',
1072
- 'users[1][surname]': 'Anderson'
1073
- }
1074
- ```
1075
-
1076
- If your backend body parser, such as `body-parser` for `express.js`, supports nested object decoding, the server receives the same object structure:
1077
-
1078
- ```js
1079
- const app = express();
1080
-
1081
- app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
1082
-
1083
- app.post('/', function (req, res, next) {
1084
- // echo body as JSON
1085
- res.send(JSON.stringify(req.body));
1086
- });
1087
-
1088
- server = app.listen(3000);
1089
- ```
1090
-
1091
- ## Using `multipart/form-data` format
1092
-
1093
- ### FormData
1094
-
1095
- To send data as `multipart/form-data`, pass a FormData instance as the payload.
1096
- You do not need to set the `Content-Type` header. Faxios detects it from the payload type.
1097
- For browser, web worker, and React Native `FormData`, leave `Content-Type` unset so the runtime can add the multipart boundary.
1098
-
1099
- ```js
1100
- const formData = new FormData();
1101
- formData.append('foo', 'bar');
1102
-
1103
- faxios.post('https://httpbin.org/post', formData);
1104
- ```
1105
-
1106
- In node.js, use the [`form-data`](https://github.com/form-data/form-data) library:
1107
-
1108
- ```js
1109
- const FormData = require('form-data');
1110
-
1111
- const form = new FormData();
1112
- form.append('my_field', 'my value');
1113
- form.append('my_buffer', Buffer.alloc(10));
1114
- form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
1115
-
1116
- faxios.post('https://example.com', form);
1117
- ```
1118
-
1119
- In node.js, when a `FormData` object provides `getHeaders()`, faxios copies all returned headers by default for v1 compatibility. If the `FormData` object is custom or not fully trusted, set `formDataHeaderPolicy: 'content-only'` to copy only `Content-Type` and `Content-Length`, and set any other request headers explicitly with the request `headers` config.
1120
-
1121
- ### Automatic serialization to FormData
1122
-
1123
- Since `v0.27.0`, Faxios can serialize an object to FormData if the request `Content-Type`
1124
- header is set to `multipart/form-data`.
1125
-
1126
- This request submits data as FormData in browsers and Node.js:
1127
-
1128
- ```js
1129
- import faxios from '@gcmdev/faxios';
1130
-
1131
- faxios
1132
- .post(
1133
- 'https://httpbin.org/post',
1134
- { x: 1 },
1135
- {
1136
- headers: {
1137
- 'Content-Type': 'multipart/form-data',
1138
- },
1139
- }
1140
- )
1141
- .then(({ data }) => console.log(data));
1142
- ```
1143
-
1144
- The Node.js build uses the [`form-data`](https://github.com/form-data/form-data) polyfill by default.
1145
-
1146
- You can override the FormData class with the `env.FormData` config option, but most applications do not need this:
1147
-
1148
- ```js
1149
- import faxios from '@gcmdev/faxios';
1150
-
1151
- const { data } = await faxios.post(
1152
- 'https://httpbin.org/post',
1153
- { x: 1, buf: Buffer.alloc(10) },
1154
- { headers: { 'Content-Type': 'multipart/form-data' } }
1155
- );
1156
- console.log(data);
1157
- ```
1158
-
1159
- The Faxios FormData serializer supports these special endings:
1160
-
1161
- - `{}` - serialize the value with JSON.stringify
1162
- - `[]` - unwrap the array-like object as separate fields with the same key
1163
-
1164
- > Note: Arrays and FileList objects are unwrapped by default.
1165
-
1166
- FormData serializer supports additional options via `config.formSerializer: object` property to handle rare cases:
1167
-
1168
- - `visitor: Function` - user-defined visitor function that Faxios calls recursively to serialize the data object
1169
- to a `FormData` object by following custom rules.
1170
-
1171
- - `dots: boolean = false` - use dot notation instead of brackets to serialize arrays and objects;
1172
-
1173
- - `metaTokens: boolean = true` - add the special ending (e.g `user{}: '{"name": "John"}'`) in the FormData key.
1174
- A backend body parser can use this meta-information to parse the value as JSON.
1175
-
1176
- - `indexes: null|false|true = false` - controls how Faxios adds indexes to unwrapped keys of `flat` array-like objects.
1177
- - `null` - don't add brackets (`arr: 1`, `arr: 2`, `arr: 3`)
1178
- - `false`(default) - add empty brackets (`arr[]: 1`, `arr[]: 2`, `arr[]: 3`)
1179
- - `true` - add brackets with indexes (`arr[0]: 1`, `arr[1]: 2`, `arr[2]: 3`)
1180
- - `maxDepth: number = 100` - maximum object nesting depth the serializer will recurse into. If the
1181
- input object exceeds this depth, an `FaxiosError` with `code: 'ERR_FORM_DATA_DEPTH_EXCEEDED'` is
1182
- thrown instead of overflowing the call stack. This protects server applications from DoS
1183
- attacks via deeply nested payloads. Set to `Infinity` to disable the limit and restore pre-fix behaviour.
1184
-
1185
- ```js
1186
- // Raise the limit for a schema that genuinely nests deeper than 100 levels:
1187
- faxios.postForm('/api', data, { formSerializer: { maxDepth: 200 } });
1188
-
1189
- // Same protection applies to params serialization:
1190
- faxios.get('/api', { params: data, paramsSerializer: { maxDepth: 200 } });
1191
- ```
1192
-
1193
- Given this object:
1194
-
1195
- ```js
1196
- const obj = {
1197
- x: 1,
1198
- arr: [1, 2, 3],
1199
- arr2: [1, [2], 3],
1200
- users: [
1201
- { name: 'Peter', surname: 'Griffin' },
1202
- { name: 'Thomas', surname: 'Anderson' },
1203
- ],
1204
- 'obj2{}': [{ x: 1 }],
1205
- };
1206
- ```
1207
-
1208
- The Faxios serializer appends these fields:
1209
-
1210
- ```js
1211
- const formData = new FormData();
1212
- formData.append('x', '1');
1213
- formData.append('arr[]', '1');
1214
- formData.append('arr[]', '2');
1215
- formData.append('arr[]', '3');
1216
- formData.append('arr2[0]', '1');
1217
- formData.append('arr2[1][0]', '2');
1218
- formData.append('arr2[2]', '3');
1219
- formData.append('users[0][name]', 'Peter');
1220
- formData.append('users[0][surname]', 'Griffin');
1221
- formData.append('users[1][name]', 'Thomas');
1222
- formData.append('users[1][surname]', 'Anderson');
1223
- formData.append('obj2{}', '[{"x":1}]');
1224
- ```
1225
-
1226
- Faxios supports `postForm`, `putForm`, and `patchForm` as shortcuts for the matching HTTP methods with the `Content-Type` header preset to `multipart/form-data`.
1227
-
1228
- ## Posting files
1229
-
1230
- Submit a single file:
1231
-
1232
- ```js
1233
- await faxios.postForm('https://httpbin.org/post', {
1234
- myVar: 'foo',
1235
- file: document.querySelector('#fileInput').files[0],
1236
- });
1237
- ```
1238
-
1239
- or multiple files as `multipart/form-data`:
1240
-
1241
- ```js
1242
- await faxios.postForm('https://httpbin.org/post', {
1243
- 'files[]': document.querySelector('#fileInput').files,
1244
- });
1245
- ```
1246
-
1247
- `FileList` object can be passed directly:
1248
-
1249
- ```js
1250
- await faxios.postForm('https://httpbin.org/post', document.querySelector('#fileInput').files);
1251
- ```
1252
-
1253
- Faxios sends all files with the same field name: `files[]`.
1254
-
1255
- ## HTML form posting (browser)
1256
-
1257
- Pass an HTML Form element as a payload to submit it as `multipart/form-data` content.
1258
-
1259
- ```js
1260
- await faxios.postForm('https://httpbin.org/post', document.querySelector('#htmlForm'));
1261
- ```
1262
-
1263
- `FormData` and `HTMLForm` objects can also be posted as `JSON` by explicitly setting the `Content-Type` header to `application/json`:
1264
-
1265
- ```js
1266
- await faxios.post('https://httpbin.org/post', document.querySelector('#htmlForm'), {
1267
- headers: {
1268
- 'Content-Type': 'application/json',
1269
- },
1270
- });
1271
- ```
1272
-
1273
- For example, the Form
1274
-
1275
- ```html
1276
- <form id="form">
1277
- <input type="text" name="foo" value="1" />
1278
- <input type="text" name="deep.prop" value="2" />
1279
- <input type="text" name="deep prop spaced" value="3" />
1280
- <input type="text" name="baz" value="4" />
1281
- <input type="text" name="baz" value="5" />
1282
-
1283
- <select name="user.age">
1284
- <option value="value1">Value 1</option>
1285
- <option value="value2" selected>Value 2</option>
1286
- <option value="value3">Value 3</option>
1287
- </select>
1288
-
1289
- <input type="submit" value="Save" />
1290
- </form>
1291
- ```
1292
-
1293
- submits this JSON object:
1294
-
1295
- ```js
1296
- {
1297
- "foo": "1",
1298
- "deep": {
1299
- "prop": {
1300
- "spaced": "3"
1301
- }
1302
- },
1303
- "baz": [
1304
- "4",
1305
- "5"
1306
- ],
1307
- "user": {
1308
- "age": "value2"
1309
- }
1310
- }
1311
- ```
1312
-
1313
- Sending `Blobs`/`Files` as JSON (`base64`) is not currently supported.
1314
-
1315
- ## Progress capturing
1316
-
1317
- Faxios can capture response download progress in every runtime.
1318
- Progress events are limited to `3` times per second.
1319
-
1320
- Upload progress (`onUploadProgress`) is not supported because the web-standard
1321
- fetch API cannot emit upload progress events.
1322
-
1323
- ```js
1324
- await faxios.post(url, data, {
1325
- onDownloadProgress: function (faxiosProgressEvent) {
1326
- /*{
1327
- loaded: number;
1328
- total?: number;
1329
- progress?: number;
1330
- bytes: number;
1331
- estimated?: number;
1332
- rate?: number; // download speed in bytes
1333
- download: true; // download sign
1334
- }*/
1335
- },
1336
- });
1337
- ```
1338
-
1339
- ## FaxiosHeaders
1340
-
1341
- Faxios includes an `FaxiosHeaders` class for working with headers through a Map-like API.
1342
- HTTP header names are case-insensitive, but Faxios keeps the original header case for style and for servers that incorrectly depend on case.
1343
- Directly manipulating the headers object still works, but it is deprecated.
1344
-
1345
- ### Working with headers
1346
-
1347
- An `FaxiosHeaders` instance can contain several internal value types that control setting and merging.
1348
- Faxios gets the final headers object with string values by calling `toJSON`.
1349
-
1350
- > Note: By JSON here we mean an object consisting only of string values intended to be sent over the network.
1351
-
1352
- The header value can be one of the following types:
1353
-
1354
- - `string` - normal string value sent to the server
1355
- - `null` - skip header when rendering to JSON
1356
- - `false` - skip header when rendering to JSON. Also indicates that the `set` method must be called with `rewrite` set to `true`
1357
- to overwrite this value (Faxios uses this internally to allow users to opt out of installing certain headers like `User-Agent` or `Content-Type`)
1358
- - `undefined` - value is not set
1359
-
1360
- > Note: The header value is considered set if it is not equal to undefined.
1361
-
1362
- The headers object is always initialized inside interceptors and transformers:
1363
-
1364
- ```ts
1365
- faxios.interceptors.request.use((request: InternalFaxiosRequestConfig) => {
1366
- request.headers.set('My-header', 'value');
1367
-
1368
- request.headers.set({
1369
- 'My-set-header1': 'my-set-value1',
1370
- 'My-set-header2': 'my-set-value2',
1371
- });
1372
-
1373
- request.headers.set('User-Agent', false); // prevent Faxios from setting this header later
1374
-
1375
- request.headers.setContentType('text/plain');
1376
-
1377
- request.headers['My-set-header2'] = 'newValue'; // direct access is deprecated
1378
-
1379
- return request;
1380
- });
1381
- ```
1382
-
1383
- You can iterate over an `FaxiosHeaders` instance using a `for...of` statement:
1384
-
1385
- ```js
1386
- const headers = new FaxiosHeaders({
1387
- foo: '1',
1388
- bar: '2',
1389
- baz: '3',
1390
- });
1391
-
1392
- for (const [header, value] of headers) {
1393
- console.log(header, value);
1394
- }
1395
-
1396
- // foo 1
1397
- // bar 2
1398
- // baz 3
1399
- ```
1400
-
1401
- ### Preserving a specific header case
1402
-
1403
- Header names are case-insensitive, but `FaxiosHeaders` keeps the case of the first matching key it sees.
1404
- If you need a specific case for non-standard case-sensitive servers, define a case preset with `undefined` and then set the value later:
1405
-
1406
- ```js
1407
- const api = faxios.create();
1408
-
1409
- api.defaults.headers.common = {
1410
- 'content-type': undefined,
1411
- accept: undefined,
1412
- };
1413
-
1414
- await api.put(url, data, {
1415
- headers: {
1416
- 'Content-Type': 'application/octet-stream',
1417
- Accept: 'application/json',
1418
- },
1419
- });
1420
- ```
1421
-
1422
- You can also compose the same behavior with `FaxiosHeaders.concat`:
1423
-
1424
- ```js
1425
- const headers = faxios.FaxiosHeaders.concat(
1426
- { 'content-type': undefined },
1427
- { 'Content-Type': 'application/octet-stream' }
1428
- );
1429
-
1430
- await faxios.put(url, data, { headers });
1431
- ```
1432
-
1433
- ### new FaxiosHeaders(headers?)
1434
-
1435
- Constructs a new `FaxiosHeaders` instance.
1436
-
1437
- ```
1438
- constructor(headers?: RawFaxiosHeaders | FaxiosHeaders | string);
1439
- ```
1440
-
1441
- If the headers object is a string, Faxios parses it as raw HTTP headers.
1442
-
1443
- ```js
1444
- const headers = new FaxiosHeaders(`
1445
- Host: www.bing.com
1446
- User-Agent: curl/7.54.0
1447
- Accept: */*`);
1448
-
1449
- console.log(headers);
1450
-
1451
- // Object [FaxiosHeaders] {
1452
- // host: 'www.bing.com',
1453
- // 'user-agent': 'curl/7.54.0',
1454
- // accept: '*/*'
1455
- // }
1456
- ```
1457
-
1458
- ### FaxiosHeaders#set
1459
-
1460
- ```ts
1461
- set(headerName, value: Faxios, rewrite?: boolean);
1462
- set(headerName, value, rewrite?: (this: FaxiosHeaders, value: string, name: string, headers: RawFaxiosHeaders) => boolean);
1463
- set(headers?: RawFaxiosHeaders | FaxiosHeaders | string, rewrite?: boolean);
1464
- ```
1465
-
1466
- The `rewrite` argument controls the overwriting behavior:
1467
-
1468
- - `false` - do not overwrite if the header's value is set (is not `undefined`)
1469
- - `undefined` (default) - overwrite the header unless its value is set to `false`
1470
- - `true` - rewrite anyway
1471
-
1472
- The option can also accept a user-defined function that determines whether to overwrite the value.
1473
-
1474
- Empty or whitespace-only header names are ignored.
1475
-
1476
- Returns `this`.
1477
-
1478
- ### FaxiosHeaders#get(header)
1479
-
1480
- ```
1481
- get(headerName: string, matcher?: true | FaxiosHeaderMatcher): FaxiosHeaderValue;
1482
- get(headerName: string, parser: RegExp): RegExpExecArray | null;
1483
- ```
1484
-
1485
- Returns the internal value of the header. It can take an extra argument to parse the header's value with `RegExp.exec`,
1486
- matcher function or internal key-value parser.
1487
-
1488
- ```ts
1489
- const headers = new FaxiosHeaders({
1490
- 'Content-Type': 'multipart/form-data; boundary=Asrf456BGe4h',
1491
- });
1492
-
1493
- console.log(headers.get('Content-Type'));
1494
- // multipart/form-data; boundary=Asrf456BGe4h
1495
-
1496
- console.log(headers.get('Content-Type', true)); // parse key-value pairs from a string separated with \s,;= delimiters:
1497
- // [Object: null prototype] {
1498
- // 'multipart/form-data': undefined,
1499
- // boundary: 'Asrf456BGe4h'
1500
- // }
1501
-
1502
- console.log(
1503
- headers.get('Content-Type', (value, name, headers) => {
1504
- return String(value).replace(/a/g, 'ZZZ');
1505
- })
1506
- );
1507
- // multipZZZrt/form-dZZZtZZZ; boundZZZry=Asrf456BGe4h
1508
-
1509
- console.log(headers.get('Content-Type', /boundary=(\w+)/)?.[0]);
1510
- // boundary=Asrf456BGe4h
1511
- ```
1512
-
1513
- Returns the value of the header.
1514
-
1515
- ### FaxiosHeaders#has(header, matcher?)
1516
-
1517
- ```
1518
- has(header: string, matcher?: FaxiosHeaderMatcher): boolean;
1519
- ```
1520
-
1521
- Returns `true` if the header is set (has no `undefined` value).
1522
-
1523
- ### FaxiosHeaders#delete(header, matcher?)
1524
-
1525
- ```
1526
- delete(header: string | string[], matcher?: FaxiosHeaderMatcher): boolean;
1527
- ```
1528
-
1529
- Returns `true` if at least one header has been removed.
1530
-
1531
- ### FaxiosHeaders#clear(matcher?)
1532
-
1533
- ```
1534
- clear(matcher?: FaxiosHeaderMatcher): boolean;
1535
- ```
1536
-
1537
- Removes all headers.
1538
- Unlike the `delete` method matcher, this optional matcher matches the header name rather than the value.
1539
-
1540
- ```ts
1541
- const headers = new FaxiosHeaders({
1542
- foo: '1',
1543
- 'x-foo': '2',
1544
- 'x-bar': '3',
1545
- });
1546
-
1547
- console.log(headers.clear(/^x-/)); // true
1548
-
1549
- console.log(headers.toJSON()); // [Object: null prototype] { foo: '1' }
1550
- ```
1551
-
1552
- Returns `true` if at least one header has been cleared.
1553
-
1554
- ### FaxiosHeaders#normalize(format);
1555
-
1556
- If the headers object was changed directly, it can have duplicates with the same name but in different cases.
1557
- This method normalizes the headers object by combining duplicate keys into one.
1558
- Faxios uses this method internally after calling each interceptor.
1559
- Set `format` to true for converting header names to lowercase and capitalizing the initial letters (`cOntEnt-type` => `Content-Type`)
1560
-
1561
- ```js
1562
- const headers = new FaxiosHeaders({
1563
- foo: '1',
1564
- });
1565
-
1566
- headers.Foo = '2';
1567
- headers.FOO = '3';
1568
-
1569
- console.log(headers.toJSON()); // [Object: null prototype] { foo: '1', Foo: '2', FOO: '3' }
1570
- console.log(headers.normalize().toJSON()); // [Object: null prototype] { foo: '3' }
1571
- console.log(headers.normalize(true).toJSON()); // [Object: null prototype] { Foo: '3' }
1572
- ```
1573
-
1574
- Returns `this`.
1575
-
1576
- ### FaxiosHeaders#concat(...targets)
1577
-
1578
- ```
1579
- concat(...targets: Array<FaxiosHeaders | RawFaxiosHeaders | string | undefined | null>): FaxiosHeaders;
1580
- ```
1581
-
1582
- Merges the instance with targets into a new `FaxiosHeaders` instance. If the target is a string, Faxios parses it as raw HTTP headers.
1583
-
1584
- Returns a new `FaxiosHeaders` instance.
1585
-
1586
- ### FaxiosHeaders#toJSON(asStrings?)
1587
-
1588
- ```
1589
- toJSON(asStrings: true): Record<string, string>;
1590
- toJSON(asStrings?: false): Record<string, string | string[]>;
1591
- ```
1592
-
1593
- Resolves all internal header values into a new null prototype object.
1594
- Set `asStrings` to true to resolve arrays as a string containing all elements, separated by commas.
1595
-
1596
- ### FaxiosHeaders.from(thing?)
1597
-
1598
- ```
1599
- from(thing?: FaxiosHeaders | RawFaxiosHeaders | string): FaxiosHeaders;
1600
- ```
1601
-
1602
- Returns a new `FaxiosHeaders` instance created from the raw headers passed in,
1603
- or returns the given headers object if it's already an `FaxiosHeaders` instance.
1604
-
1605
- ### FaxiosHeaders.concat(...targets)
1606
-
1607
- ```
1608
- concat(...targets: Array<FaxiosHeaders | RawFaxiosHeaders | string | undefined | null>): FaxiosHeaders;
1609
- ```
1610
-
1611
- Returns a new `FaxiosHeaders` instance created by merging the target objects.
1612
-
1613
- ### Shortcuts
1614
-
1615
- The following shortcuts are available:
1616
-
1617
- - `setContentType`, `getContentType`, `hasContentType`
1618
-
1619
- - `setContentLength`, `getContentLength`, `hasContentLength`
1620
-
1621
- - `setAccept`, `getAccept`, `hasAccept`
1622
-
1623
- - `setUserAgent`, `getUserAgent`, `hasUserAgent`
1624
-
1625
- - `setContentEncoding`, `getContentEncoding`, `hasContentEncoding`
1626
-
1627
- ## Fetch adapter
1628
-
1629
- The fetch adapter is the only adapter. It uses the web-standard [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) API and is used in every runtime — browser, Node.js 18+, Deno, and Bun. It is the default; you do not need to select it.
1630
-
1631
- ```js
1632
- const { data } = await faxios.get(url); // uses fetch in all runtimes
1633
- ```
1634
-
1635
- The default `adapter` is `['fetch']`. You can pass a custom adapter function, but `'fetch'` is the only built-in name.
1636
-
1637
- It supports download progress capturing and response types such as `stream` and `formdata` when the environment supports them. Upload progress is not supported because fetch cannot emit upload progress events.
1638
-
1639
- Proxies and connection agents are not configured through faxios options. Configure them at the runtime level instead — for example, by passing a custom dispatcher/agent via `fetchOptions`, or by setting the runtime's global proxy/dispatcher (Node's `undici` `ProxyAgent`, Deno/Bun proxy env vars, etc.).
1640
-
1641
- When `auth` is omitted, the fetch adapter can read HTTP Basic auth credentials from the request URL, for example `https://user:pass@example.com`. Percent-encoded URL credentials are decoded before the `Authorization` header is generated, and `auth` takes precedence over URL-embedded credentials.
1642
-
1643
- ### Custom fetch
1644
-
1645
- Since `v1.12.0`, you can configure the fetch adapter to use a custom fetch API instead of environment globals.
1646
- Pass a custom `fetch` function, `Request`, and `Response` constructors through `env` config.
1647
- This helps in custom environments and app frameworks.
1648
-
1649
- When using a custom fetch, you may also need to set custom `Request` and `Response` constructors. If you do not set them, Faxios uses the global objects.
1650
- If your custom fetch API does not provide these objects and the globals are incompatible with it, pass `null` to disable them inside the fetch adapter.
1651
-
1652
- > Note: Setting `Request` and `Response` to `null` prevents the fetch adapter from capturing download progress.
1653
-
1654
- Basic example:
1655
-
1656
- ```js
1657
- import customFetchFunction from 'customFetchModule';
1658
-
1659
- const instance = faxios.create({
1660
- adapter: 'fetch',
1661
- onDownloadProgress(e) {
1662
- console.log('downloadProgress', e);
1663
- },
1664
- env: {
1665
- fetch: customFetchFunction,
1666
- Request: null, // undefined -> use the global constructor
1667
- Response: null,
1668
- },
1669
- });
1670
- ```
1671
-
1672
- #### Using with Tauri
1673
-
1674
- A minimal example of setting up Faxios for use in a [Tauri](https://tauri.app/plugin/http-client/) app with a platform fetch function that ignores CORS policy for requests.
1675
-
1676
- ```js
1677
- import { fetch } from '@tauri-apps/plugin-http';
1678
- import faxios from '@gcmdev/faxios';
1679
-
1680
- const instance = faxios.create({
1681
- adapter: 'fetch',
1682
- onDownloadProgress(e) {
1683
- console.log('downloadProgress', e);
1684
- },
1685
- env: {
1686
- fetch,
1687
- },
1688
- });
1689
-
1690
- const { data } = await instance.get('https://google.com');
1691
- ```
1692
-
1693
- #### Using with SvelteKit
1694
-
1695
- [SvelteKit](https://svelte.dev/docs/kit/web-standards#Fetch-APIs) uses a custom fetch function for server rendering in `load` functions. It also uses relative paths, which are incompatible with the standard URL API. Configure Faxios to use SvelteKit's custom fetch API:
1696
-
1697
- ```js
1698
- export async function load({ fetch }) {
1699
- const { data: post } = await faxios.get('https://jsonplaceholder.typicode.com/posts/1', {
1700
- adapter: 'fetch',
1701
- env: {
1702
- fetch,
1703
- Request: null,
1704
- Response: null,
1705
- },
1706
- });
1707
-
1708
- return { post };
1709
- }
1710
- ```
1711
-
1712
- ## Semver
1713
-
1714
- Faxios follows [semver](https://semver.org/) since `v1.0.0`.
1715
-
1716
- ## Promises
1717
-
1718
- faxios depends on a native ES6 Promise implementation to be [supported](https://caniuse.com/promises).
1719
- If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise).
1720
-
1721
- ## TypeScript
1722
-
1723
- faxios includes [TypeScript](https://typescriptlang.org) definitions and a type guard for faxios errors.
1724
-
1725
- ```typescript
1726
- let user: User = null;
1727
- try {
1728
- const { data } = await faxios.get('/user?ID=12345');
1729
- user = data.userDetails;
1730
- } catch (error) {
1731
- if (faxios.isFaxiosError(error)) {
1732
- handleFaxiosError(error);
1733
- } else {
1734
- handleUnexpectedError(error);
1735
- }
1736
- }
1737
- ```
1738
-
1739
- Use `faxios.isCancel<T>()` to narrow cancellation errors to `CanceledError<T>`:
1740
-
1741
- ```typescript
1742
- const controller = new AbortController();
1743
-
1744
- try {
1745
- await faxios.get<User>('/user?ID=12345', { signal: controller.signal });
1746
- } catch (error) {
1747
- if (faxios.isCancel<User>(error)) {
1748
- handleCancellation(error);
1749
- }
1750
- }
1751
- ```
1752
-
1753
- faxios is ESM-only. Use `"moduleResolution": "node16"` or `"bundler"` in your `tsconfig.json`.
1754
-
1755
- When using `responseSchema`, TypeScript infers `response.data` from the schema's output type automatically — no manual generic needed:
1756
-
1757
- ```typescript
1758
- import { z } from 'zod';
1759
-
1760
- const UserSchema = z.object({ name: z.string(), age: z.number() });
1761
- const { data } = await faxios.get('/user/1', { responseSchema: UserSchema });
1762
- // data is typed as { name: string; age: number }
1763
- ```
1764
-
1765
- You can also create a custom instance with typed interceptors:
1766
-
1767
- ```typescript
1768
- import faxios, { FaxiosInstance, InternalFaxiosRequestConfig } from '@gcmdev/faxios';
1769
-
1770
- const apiClient: FaxiosInstance = faxios.create({
1771
- baseURL: 'https://api.example.com',
1772
- timeout: 10000,
1773
- });
1774
-
1775
- apiClient.interceptors.request.use((config: InternalFaxiosRequestConfig) => {
1776
- // Add auth token
1777
- return config;
1778
- });
1779
- ```
1780
-
1781
- ## Online one-click setup
1782
-
1783
- You can use Gitpod, a free online IDE for open source projects, to contribute or run the examples online.
1784
-
1785
- [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/faxios/faxios/blob/main/examples/server.js)
62
+ - [First steps](https://adrianbrowning.github.io/faxios/pages/getting-started/first-steps)
63
+ - [Request config](https://adrianbrowning.github.io/faxios/pages/advanced/request-config)
64
+ - [Error handling](https://adrianbrowning.github.io/faxios/pages/advanced/error-handling)
65
+ - [Middleware and plugins](https://adrianbrowning.github.io/faxios/pages/advanced/middleware)
66
+ - [Migrating from interceptors](https://adrianbrowning.github.io/faxios/pages/advanced/migrating-from-interceptors)
67
+ - [Schema validation](https://adrianbrowning.github.io/faxios/pages/advanced/schema-validation)
68
+ - [Typed endpoints: `define()`](https://adrianbrowning.github.io/faxios/pages/advanced/define)
69
+ - [Route builder: `route()`](https://adrianbrowning.github.io/faxios/pages/advanced/route)
70
+ - [Headers](https://adrianbrowning.github.io/faxios/pages/advanced/headers)
71
+ - [TypeScript](https://adrianbrowning.github.io/faxios/pages/advanced/type-script)
1786
72
 
1787
73
  ## Contributing
1788
74
 
1789
- ### Local setup
1790
-
1791
- As a supply-chain hardening measure, this repository ships a project-level `.npmrc` that sets `ignore-scripts=true`. This blocks npm lifecycle scripts (`preinstall`, `install`, `postinstall`, `prepare`) from any direct or transitive dependency when you run `npm install` or `npm ci` inside the repo. See [THREATMODEL.md](./THREATMODEL.md) (threat T-S2) for the rationale.
1792
-
1793
- One consequence: the repository's own `prepare` hook (which installs Husky's git hooks) will **not** run automatically. After your first install, enable the git hooks manually:
1794
-
1795
- ```bash
1796
- npm ci
1797
- npm rebuild husky && npx husky
1798
- ```
1799
-
1800
- Run those two commands once per fresh checkout. You do **not** need to re-run them after every subsequent `npm install`.
1801
-
1802
- Do not remove `ignore-scripts=true` from `.npmrc` to "fix" this. That reopens the lifecycle-script attack surface for every other package in the tree. All CI workflows already invoke npm with `--ignore-scripts`, so local behaviour matches CI.
1803
-
1804
- ## Resources
1805
-
1806
- - [Changelog](https://github.com/faxios/faxios/blob/v1.x/CHANGELOG.md)
1807
- - [Ecosystem](https://github.com/faxios/faxios/blob/v1.x/ECOSYSTEM.md)
1808
- - [Contributing Guide](https://github.com/faxios/faxios/blob/v1.x/CONTRIBUTING.md)
1809
- - [Code of Conduct](https://github.com/faxios/faxios/blob/v1.x/CODE_OF_CONDUCT.md)
75
+ See [CONTRIBUTING.md](https://github.com/adrianbrowning/faxios/blob/main/CONTRIBUTING.md).
1810
76
 
1811
77
  ## Credits
1812
78
 
1813
- faxios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) in [AngularJS](https://angularjs.org/). It provides a standalone `$http`-like service for use outside AngularJS.
79
+ faxios is a fork of [axios](https://github.com/axios/axios). axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) in [AngularJS](https://angularjs.org/), and provides a standalone `$http`-like service for use outside AngularJS.
1814
80
 
1815
81
  ## License
1816
82
 
1817
- [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
83
+ [MIT](https://github.com/adrianbrowning/faxios/blob/main/LICENSE)