CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-got

Human-friendly and powerful HTTP request library for Node.js

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

Got

Got is a human-friendly and powerful HTTP request library for Node.js that provides advanced features including HTTP/2 support, automatic retries, RFC compliant caching, request/response hooks, progress events, and advanced timeout handling. It offers a comprehensive API for making HTTP requests with extensive TypeScript support and composable architecture.

Package Information

  • Package Name: got
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install got
  • Node.js: v20+ required
  • Module Type: ESM only

Core Imports

import got from "got";

Named imports for specific functionality:

import { got, create, Options } from "got";

For CommonJS (legacy projects):

// Note: Got is ESM-only since v12. For CommonJS, use dynamic import:
const { default: got } = await import("got");

// Or use Got v11 which still supports CommonJS:
// const got = require("got"); // Only in Got v11 and below

Error classes:

import { RequestError, HTTPError, MaxRedirectsError, CancelError, TimeoutError } from "got";

Utility functions:

import { calculateRetryDelay, parseLinkHeader } from "got";

Basic Usage

import got from "got";

// Simple GET request
const response = await got("https://api.example.com/users");
console.log(response.body);

// POST request with JSON
const result = await got.post("https://api.example.com/users", {
  json: { name: "Alice", email: "alice@example.com" }
}).json();

// GET request with JSON response
const users = await got("https://api.example.com/users").json();

// Stream response
import { pipeline } from "node:stream";
import { createWriteStream } from "node:fs";

await pipeline(
  got.stream("https://example.com/large-file.zip"),
  createWriteStream("download.zip")
);

Architecture

Got is built around several key components:

  • Core Instance: Main got function providing HTTP methods and configuration
  • Options System: Comprehensive configuration through the Options class
  • Request/Response Pipeline: Hook-based request lifecycle management
  • Stream Support: Duplex streams for handling large data transfers
  • Promise Interface: Cancelable promises with shortcut methods
  • Error Handling: Detailed error classes with request/response metadata
  • Extensibility: Instance creation and extension for custom configurations

Capabilities

HTTP Methods

Core HTTP request methods with comprehensive options and response handling. Supports all standard HTTP methods with consistent API.

function got(url: string | URL, options?: OptionsInit): CancelableRequest<Response>;
function got(options: OptionsInit): CancelableRequest<Response>;

// HTTP method shortcuts
interface Got {
  get: GotRequestFunction;
  post: GotRequestFunction;
  put: GotRequestFunction;
  patch: GotRequestFunction;
  head: GotRequestFunction;
  delete: GotRequestFunction;
}

// Cancelable request with response shortcuts
interface CancelableRequest<T> extends Promise<T> {
  /** Parse response body as JSON */
  json<ReturnType>(): CancelableRequest<ReturnType>;
  /** Get response body as Buffer */
  buffer(): CancelableRequest<Buffer>;
  /** Get response body as string */
  text(): CancelableRequest<string>;
  /** Cancel the request */
  cancel(): void;
}

HTTP Methods

Stream API

Streaming interface for handling large requests and responses with duplex stream support and progress events.

const stream: GotStream;

interface GotStream {
  (url?: string | URL, options?: StreamOptions): Request;
  get(url?: string | URL, options?: StreamOptions): Request;
  post(url?: string | URL, options?: StreamOptions): Request;
  put(url?: string | URL, options?: StreamOptions): Request;
  patch(url?: string | URL, options?: StreamOptions): Request;
  head(url?: string | URL, options?: StreamOptions): Request;
  delete(url?: string | URL, options?: StreamOptions): Request;
}

Stream API

Pagination

Built-in pagination support for APIs that return paginated results with async iterator interface.

const paginate: GotPaginate;

interface GotPaginate {
  <T>(url: string | URL, options?: OptionsWithPagination<T>): AsyncIterableIterator<T>;
  <T>(options?: OptionsWithPagination<T>): AsyncIterableIterator<T>;
  each: <T>(url: string | URL, options?: OptionsWithPagination<T>) => AsyncIterableIterator<T>;
  all: <T>(url: string | URL, options?: OptionsWithPagination<T>) => Promise<T[]>;
}

Pagination

Request Options

Comprehensive configuration system for customizing HTTP requests including timeouts, retries, headers, authentication, and more.

class Options {
  constructor(input?: OptionsInit, defaults?: Options, parent?: Options);
}

interface OptionsInit {
  // Core request options
  url?: string | URL;
  method?: Method;
  headers?: Headers;
  body?: string | Buffer | Readable | FormData;
  json?: unknown;
  form?: Record<string, any>;
  searchParams?: SearchParameters;
  
  // Response handling
  responseType?: ResponseType;
  resolveBodyOnly?: boolean;
  parseJson?: ParseJsonFunction;
  stringifyJson?: StringifyJsonFunction;
  
  // Timeout and retry
  timeout?: Delays | number;
  retry?: RetryOptions;
  
  // HTTP behavior
  followRedirect?: boolean;
  maxRedirects?: number;
  decompress?: boolean;
  cache?: CacheOptions | boolean;
  
  // Advanced options
  hooks?: Hooks;
  agents?: Agents;
  https?: HttpsOptions;
  http2?: boolean;
}

Request Options

Instance Management

Create and extend Got instances with custom defaults and configurations for reusable HTTP clients.

function create(defaults: InstanceDefaults): Got;

interface Got {
  extend<T extends Array<Got | ExtendOptions>>(...instancesOrOptions: T): Got<MergeExtendsConfig<T>>;
  defaults: InstanceDefaults;
}

Instance Management

Error Handling

Comprehensive error classes with detailed metadata for different failure scenarios.

class RequestError<T = unknown> extends Error {
  readonly code: string;
  readonly options: Options;
  readonly response?: Response<T>;
  readonly request?: Request;
  readonly timings?: Timings;
}

class HTTPError<T = any> extends RequestError<T> {
  readonly response: Response<T>;
}

class MaxRedirectsError extends RequestError {
  readonly response: Response;
}

Error Handling

Response Handling

Response objects with parsed bodies, metadata, and timing information.

interface Response<T = unknown> extends PlainResponse {
  body: T;
  statusCode: number;
  statusMessage: string;
  headers: IncomingHttpHeaders;
  requestUrl: URL;
  redirectUrls: URL[];
  request: Request;
  timings: Timings;
  retryCount: number;
  ok: boolean;
}

Response Handling

Hooks System

Request lifecycle hooks for customizing behavior at different stages of the request process.

interface Hooks {
  init?: InitHook[];
  beforeRequest?: BeforeRequestHook[];
  beforeRedirect?: BeforeRedirectHook[];
  beforeError?: BeforeErrorHook[];
  beforeRetry?: BeforeRetryHook[];
  afterResponse?: AfterResponseHook[];
}

Hooks System

Utility Functions

Helper functions for retry calculation and Link header parsing.

function calculateRetryDelay(retryObject: RetryObject): number;
function parseLinkHeader(header: string): LinkHeaderResult[];

interface RetryObject {
  attemptCount: number;
  retryOptions: RetryOptions;
  error: RequestError;
  retryAfter?: number;
  computedValue: number;
}

interface LinkHeaderResult {
  reference: string;
  parameters: Record<string, string>;
}

Utility Functions

Type Definitions

// Core types
type Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'HEAD' | 'DELETE' | 'OPTIONS' | 'TRACE';
type ResponseType = 'json' | 'text' | 'buffer';
type Headers = Record<string, string | string[] | undefined>;

// Request function type
type GotRequestFunction = {
  (url: string | URL, options?: OptionsInit): CancelableRequest<Response>;
  (options: OptionsInit): CancelableRequest<Response>;
};

// Stream options type
interface StreamOptions extends OptionsInit {
  isStream?: true;
}

// Pagination types
interface OptionsWithPagination<T = unknown, R = unknown> extends OptionsInit {
  pagination?: PaginationOptions<T, R>;
}

// Extension types
interface ExtendOptions extends OptionsInit {
  handlers?: HandlerFunction[];
  mutableDefaults?: boolean;
}

// Instance defaults type
interface InstanceDefaults {
  options: Options;
  handlers: HandlerFunction[];
  mutableDefaults: boolean;
}

// Handler function type
type HandlerFunction = <T extends GotReturn>(
  options: Options, 
  next: (options: Options) => T
) => T | Promise<T>;

// Return type union
type GotReturn = Request | CancelableRequest;

// Hook types
type InitHook = (init: OptionsInit, self: Options) => void;
type BeforeRequestHook = (options: Options) => Promise<void | Response>;
type BeforeRedirectHook = (updatedOptions: Options, plainResponse: PlainResponse) => Promise<void>;
type BeforeErrorHook = (error: RequestError) => Promise<RequestError>;
type BeforeRetryHook = (error: RequestError, retryCount: number) => Promise<void>;
type AfterResponseHook<T = unknown> = (
  response: Response<T>, 
  retryWithMergedOptions: (options: OptionsInit) => never
) => Promise<Response | CancelableRequest<Response>>;

// Timing information
interface Timings {
  start: number;
  socket: number;
  lookup: number;
  connect: number;
  secureConnect: number;
  upload: number;
  response: number;
  end: number;
  error?: number;
  abort?: number;
  phases: {
    wait: number;
    dns: number;
    tcp: number;
    tls?: number;
    request: number;
    firstByte: number;
    download: number;
    total: number;
  };
}

// Plain response interface
interface PlainResponse {
  requestUrl: URL;
  redirectUrls: URL[];
  request: Request;
  ip?: string;
  isFromCache: boolean;
  statusCode: number;
  url: string;
  timings: Timings;
}

// Retry configuration
interface RetryOptions {
  limit?: number;
  methods?: Method[];
  statusCodes?: number[];
  errorCodes?: string[];
  calculateDelay?: (retryObject: RetryObject) => number;
  backoffLimit?: number;
  noise?: number;
}

// Cache configuration
interface CacheOptions {
  shared?: boolean;
  cacheHeuristic?: number;
  immutableMinTimeToLive?: number;
  ignoreCargoCult?: boolean;
}

// Agent types
interface Agents {
  http?: any;
  https?: any;
  http2?: any;
}

// HTTPS options
interface HttpsOptions {
  rejectUnauthorized?: boolean;
  checkServerIdentity?: Function;
  certificateAuthority?: string | Buffer | Array<string | Buffer>;
  key?: string | Buffer | Array<string | Buffer>;
  certificate?: string | Buffer | Array<string | Buffer>;
  passphrase?: string;
  pfx?: string | Buffer | Array<string | Buffer>;
}

// Delay configuration
interface Delays {
  lookup?: number;
  connect?: number;
  secureConnect?: number;
  socket?: number;
  send?: number;
  response?: number;
  read?: number;
  request?: number;
}

// JSON parsing functions
type ParseJsonFunction = (text: string) => unknown;
type StringifyJsonFunction = (object: unknown) => string;

// Search parameters type
type SearchParameters = string | Record<string, string | number | boolean | null | undefined> | URLSearchParams | Array<[string, string | number | boolean]>;

// Progress information for upload/download events
interface Progress {
  /** Completion percentage (0 to 1) */
  percent: number;
  /** Number of bytes transferred */
  transferred: number;
  /** Total bytes to transfer (undefined if content-length header missing) */
  total?: number;
}

// Event function type for request events
type GotEventFunction<T> = {
  /** Request event to get request object */
  (name: 'request', listener: (request: ClientRequest) => void): T;
  /** Response event to get response object */
  (name: 'response', listener: (response: Response) => void): T;
  /** Redirect event with response and next options */
  (name: 'redirect', listener: (response: Response, nextOptions: Options) => void): T;
  /** Upload progress event */
  (name: 'uploadProgress', listener: (progress: Progress) => void): T;
  /** Download progress event */
  (name: 'downloadProgress', listener: (progress: Progress) => void): T;
  /** Retry event with count and error */
  (name: 'retry', listener: (retryCount: number, error: RequestError) => void): T;
};

// Request events interface
interface RequestEvents<T> {
  on: GotEventFunction<T>;
  once: GotEventFunction<T>;
  off: GotEventFunction<T>;
}
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/got@14.4.x
Publish Source
CLI
Badge
tessl/npm-got badge