nc.http
An HTTP client on top of fetch: JSON by default, query objects, base URLs, timeouts, safe retries that respect Retry-After, typed errors, hooks, reusable clients and downloads with progress.
const { http } = require("@ix-xs/node-comfort");
import { request } from "@ix-xs/node-comfort/http";const { data } = await http.get("https://api.github.com/repos/nodejs/node");
const api = http.create({ baseURL: "https://api.example.com/v1/", auth: { bearer: process.env.TOKEN } });
const { data: users } = await api.get("users", { query: { page: 2 } });nc.http.Functions
nc.http.request()
request<T = any>(url: string | URL, options?: HttpOptions): Promise<HttpResponse<T>>Sends a request and resolves with the response, body already read. Throws an HttpError for error statuses, a TimeoutError when it's too slow and an AbortError when cancelled.
Parameters
| Name | Type | Description |
|---|---|---|
url | string | URL | An absolute URL, or a path when baseURL is set. |
optionsoptional | HttpOptions |
Returns Promise<HttpResponse<T>>
Throws HttpError | TimeoutError | AbortError
Example
const res = await http.request("https://api.example.com/items/42", {
method: "PUT",
json: { name: "Lamp" },
timeout: "10s",
retry: { attempts: 5, statuses: [429, 503] },
});
res.data; // parsed JSONnc.http.get()
get<T = any>(url: string | URL, options?: HttpOptions): Promise<HttpResponse<T>>Sends a GET request.
Parameters
| Name | Type |
|---|---|
url | string | URL |
optionsoptional | HttpOptions |
Returns Promise<HttpResponse<T>>
Example
const { data } = await http.get("https://api.example.com/users", { query: { page: 2, tags: ["a", "b"] } });nc.http.head()
head<T = undefined>(url: string | URL, options?: HttpOptions): Promise<HttpResponse<T>>Sends a HEAD request: headers only, no body.
Parameters
| Name | Type |
|---|---|
url | string | URL |
optionsoptional | HttpOptions |
Returns Promise<HttpResponse<T>>
Example
const { headers } = await http.head("https://example.com/big.zip");
headers["content-length"];nc.http.post()
post<T = any>(url: string | URL, data?: unknown, options?: HttpOptions): Promise<HttpResponse<T>>Sends a POST request. Objects, arrays, numbers and booleans go as JSON; strings, Buffers, FormData, Blobs and streams go as they are.
Parameters
| Name | Type |
|---|---|
url | string | URL |
dataoptional | unknown |
optionsoptional | HttpOptions |
Returns Promise<HttpResponse<T>>
Example
const { data: user } = await http.post("https://api.example.com/users", { name: "Ada" });
await http.post(uploadUrl, formData);nc.http.put()
put<T = any>(url: string | URL, data?: unknown, options?: HttpOptions): Promise<HttpResponse<T>>Sends a PUT request. The body works like in post().
Parameters
| Name | Type |
|---|---|
url | string | URL |
dataoptional | unknown |
optionsoptional | HttpOptions |
Returns Promise<HttpResponse<T>>
nc.http.patch()
patch<T = any>(url: string | URL, data?: unknown, options?: HttpOptions): Promise<HttpResponse<T>>Sends a PATCH request. The body works like in post().
Parameters
| Name | Type |
|---|---|
url | string | URL |
dataoptional | unknown |
optionsoptional | HttpOptions |
Returns Promise<HttpResponse<T>>
nc.http.delete()
delete<T = any>(url: string | URL, options?: HttpOptions): Promise<HttpResponse<T>>Sends a DELETE request.
Parameters
| Name | Type |
|---|---|
url | string | URL |
optionsoptional | HttpOptions |
Returns Promise<HttpResponse<T>>
Example
await http.delete(`https://api.example.com/users/${id}`);nc.http.download()
download(url: string | URL, destination: string, options?: HttpOptions): Promise<{ path: string; size: number; }>Downloads to a file as a stream, so memory stays flat whatever the size. Folders are created, and a partial file is removed if it fails.
Parameters
| Name | Type |
|---|---|
url | string | URL |
destination | string |
optionsoptional | HttpOptions |
Returns Promise<{ path: string, size: number }>: The absolute path and size in bytes.
Throws HttpError | TimeoutError | AbortError
Example
await http.download("https://example.com/video.mp4", "./downloads/video.mp4", {
onDownloadProgress: ({ percent }) => bar.update(percent ?? 0),
});nc.http.create()
create(defaults?: HttpOptions): HttpClientCreates a client with default options. Options passed to each call are merged on top.
Parameters
| Name | Type |
|---|---|
defaultsoptional | HttpOptions |
Returns HttpClient
Example
const github = http.create({
baseURL: "https://api.github.com",
auth: { bearer: process.env.GITHUB_TOKEN },
hooks: { afterResponse: [(res) => nc.debug(res.status, res.url)] },
});
const { data: repo } = await github.get("/repos/nodejs/node");nc.http.HttpErrorproperty
HttpError: typeof HttpErrorThrown by nc.http when the response status isn't 2xx (unless you pass throwHttpErrors: false), and for network failures (status 0).
Types
Import any of them in TypeScript with import type { HttpBody } from "@ix-xs/node-comfort", or in JavaScript with import("@ix-xs/node-comfort").HttpBody.
HttpBody
A request body.
type HttpBody = string | Buffer | Uint8Array | ArrayBuffer | URLSearchParams | FormData | Blob | ReadableStream | ReadableHttpClient
A client with its own defaults, from create().
| Property | Type | Description |
|---|---|---|
request | <T = any>(url: string | URL, options?: HttpOptions) => Promise<HttpResponse<T>> | Sends a request. |
get | <T = any>(url: string | URL, options?: HttpOptions) => Promise<HttpResponse<T>> | Sends a GET request. |
head | <T = any>(url: string | URL, options?: HttpOptions) => Promise<HttpResponse<T>> | Sends a HEAD request. |
delete | <T = any>(url: string | URL, options?: HttpOptions) => Promise<HttpResponse<T>> | Sends a DELETE request. |
post | <T = any>(url: string | URL, data?: unknown, options?: HttpOptions) => Promise<HttpResponse<T>> | Sends a POST request. Objects and arrays go as JSON. |
put | <T = any>(url: string | URL, data?: unknown, options?: HttpOptions) => Promise<HttpResponse<T>> | Sends a PUT request. Objects and arrays go as JSON. |
patch | <T = any>(url: string | URL, data?: unknown, options?: HttpOptions) => Promise<HttpResponse<T>> | Sends a PATCH request. Objects and arrays go as JSON. |
download | (url: string | URL, destination: string, options?: HttpOptions) => Promise<{ path: string; size: number; }> | Saves a response to a file. |
extend | (defaults: HttpOptions) => HttpClient | A new client with these defaults added. |
defaults | Readonly<HttpOptions> |
HttpHooks
Hooks to watch or change requests.
| Property | Type | Description |
|---|---|---|
beforeRequestoptional | ((config: HttpRequestConfig) => void | Promise<void>)[] | Runs before each attempt. It can change the URL, headers or body. |
afterResponseoptional | ((response: HttpResponse<any>, config: HttpRequestConfig) => void | HttpResponse<any> | Promise<void | HttpResponse<any>>)[] | Runs after each response, before errors are thrown. It can return another response. |
beforeRetryoptional | ((error: unknown, attempt: number, delay: number) => void | Promise<void>)[] | Runs before waiting for a retry. |
HttpMethod
An HTTP method.
type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS" | (string & {})HttpOptions
Request options.
| Property | Type | Description |
|---|---|---|
methodoptional | HttpMethod | Defaults to "GET". |
baseURLoptional | string | Prefix for relative URLs. |
headersoptional | Record<string, string | undefined> | Set a header to undefined to remove a default one. |
queryoptional | URLSearchParams | QueryParams | Added to the URL's own query string. |
jsonoptional | unknown | Sent as JSON. |
formoptional | Record<string, string | number | boolean> | Sent as a URL-encoded form. |
bodyoptional | HttpBody | Sent as is: string, Buffer, FormData, stream... |
authoptional | { bearer: string; } | { username: string; password: string; } | Sets the authorization header. |
timeoutoptional | string | number | false | Time limit per attempt, like "10s". false turns it off. Defaults to 30 seconds. |
retryoptional | number | false | HttpRetryOptions | Number of attempts, false, or retry settings. |
responseTypeoptional | "json" | "buffer" | "auto" | "text" | "stream" | How to read the body. "auto" reads JSON or text based on the content type, a Buffer otherwise. |
throwHttpErrorsoptional | boolean | Throw an HttpError when the status isn't 2xx. Defaults to true. |
signaloptional | AbortSignal | Cancels the request. |
hooksoptional | HttpHooks | |
onDownloadProgressoptional | ((progress: { loaded: number; total: number | undefined; percent: number | undefined; }) => void) | Called while the body downloads. |
redirectoptional | "error" | "follow" | "manual" | Defaults to "follow". |
HttpRequestConfig
A request as hooks see it.
| Property | Type | Description |
|---|---|---|
url | string | The final URL, base URL and query included. |
method | HttpMethod | |
headers | Record<string, string> | Lower-cased names. |
body | HttpBody | |
attempt | number | 1 for the first try. |
HttpResponse
A response.
| Property | Type | Description |
|---|---|---|
status | number | |
statusText | string | |
ok | boolean | true for 2xx statuses. |
headers | Record<string, string> | Lower-cased names. |
data | T | The body, already read (see responseType). |
url | string | The final URL, after redirects. |
duration | number | In ms, retries included. |
attempts | number | How many attempts it took. |
HttpRetryOptions
Retry settings.
| Property | Type | Description |
|---|---|---|
attemptsoptional | number | Total attempts, the first included. Defaults to 3 for methods that are safe to repeat, 1 for the others. |
delayoptional | number | Wait before the first retry, in ms. Defaults to 300. |
backoffoptional | number | Multiplies the wait after each attempt. Defaults to 2. |
maxDelayoptional | number | Longest wait, Retry-After included. Defaults to 30 seconds. |
statusesoptional | number[] | Statuses worth retrying. Defaults to 408, 413, 429, 500, 502, 503 and 504. |
methodsoptional | HttpMethod[] | Methods allowed to retry. POST and PATCH aren't, by default, so nothing gets created twice. |
QueryParams
Query string values. null and undefined are skipped, arrays repeat the key.
type QueryParams = Record<string, string | number | boolean | null | undefined | Array<string | number | boolean>>