{"id":13228,"library":"get-it","title":"get-it HTTP Request Library","description":"get-it is a generic HTTP request library designed for both Node.js (>=14.0.0) and modern browsers, including web workers. Currently at stable version 8.7.2, the package maintains an active development pace with frequent bug fixes and minor feature releases within its v8.x series. Its key differentiator is a highly modular, middleware-based architecture, drawing inspiration from `http-client`. This approach enables developers to compose specific functionalities such as Promise or Observable patterns, automatic request retries, cancellation, JSON serialization/deserialization, GZIP unwrapping (Node.js), base URL prepending, redirect following, and detailed upload/download progress events. The modularity aims to provide a small browser bundle footprint while offering extensive and configurable HTTP client features. It transparently handles various request body types depending on the execution environment and provides options for network timeouts.","status":"active","version":"8.7.2","language":"javascript","source_language":"en","source_url":"https://github.com/sanity-io/get-it","tags":["javascript","request","http","fetch","typescript"],"install":[{"cmd":"npm install get-it","lang":"bash","label":"npm"},{"cmd":"yarn add get-it","lang":"bash","label":"yarn"},{"cmd":"pnpm add get-it","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Used for automatic HTTP redirect handling in Node.js environments.","package":"follow-redirects","optional":false},{"reason":"TypeScript type definitions for follow-redirects, moved to dependencies for broader compatibility.","package":"@types/follow-redirects","optional":false},{"reason":"TypeScript type definitions for progress-stream, moved to dependencies for broader compatibility.","package":"@types/progress-stream","optional":false}],"imports":[{"note":"get-it primarily uses ESM imports. Direct CommonJS require() may cause issues in some setups.","wrong":"const { getIt } = require('get-it')","symbol":"getIt","correct":"import { getIt } from 'get-it'"},{"note":"Middleware functions are imported from the 'get-it/middleware' submodule. Importing directly from 'get-it' will fail.","wrong":"import { base, jsonResponse, promise } from 'get-it'","symbol":"base, jsonResponse, promise","correct":"import { base, jsonResponse, promise } from 'get-it/middleware'"},{"note":"The `observable` middleware provides an RxJS-compatible interface and should be imported from 'get-it/middleware'. It requires an Observable implementation to be passed or globally available.","wrong":"import { Observable } from 'rxjs'","symbol":"observable","correct":"import { observable } from 'get-it/middleware'"}],"quickstart":{"code":"import { getIt } from 'get-it';\nimport { base, jsonResponse, promise, timeout } from 'get-it/middleware';\n\n// Create a configured HTTP client instance\nconst httpClient = getIt([\n  // Base URL middleware prepends 'https://api.example.com/v1' to all request URLs\n  base('https://api.example.com/v1'),\n  // jsonResponse middleware automatically parses JSON responses\n  jsonResponse(),\n  // promise middleware enables the .then/.catch syntax for requests\n  promise(),\n  // timeout middleware sets connection and socket timeouts\n  timeout({ connect: 5000, socket: 10000 })\n]);\n\ninterface Project { id: string; name: string; status: string; }\n\nasync function fetchProjects() {\n  try {\n    // Make a GET request to /projects relative to the base URL\n    const response = await httpClient({ url: '/projects', method: 'GET' });\n    const projects: Project[] = response.body; // body is already parsed by jsonResponse middleware\n    console.log('Fetched projects:', projects.map(p => p.name).join(', '));\n\n    // Example of a POST request with JSON body\n    const newProject: Project = await httpClient({ \n      url: '/projects', \n      method: 'POST', \n      body: { name: 'New Awesome Project', status: 'pending' }\n    }).then(res => res.body as Project);\n    console.log('Created project:', newProject.name);\n\n  } catch (err: any) {\n    console.error('An error occurred:', err.message);\n    if (err.response) {\n      console.error('Response status:', err.response.statusCode);\n      console.error('Response body:', err.response.body);\n    }\n  }\n}\n\nfetchProjects();","lang":"typescript","description":"This quickstart demonstrates how to configure and use `get-it` with common middleware for making asynchronous HTTP requests using Promises, including setting a base URL, parsing JSON responses, and handling basic GET/POST operations and errors."},"warnings":[{"fix":"Upgrade your Node.js environment to version 14.0.0 or higher. Consider using `nvm` to manage multiple Node.js versions.","message":"`get-it` v8.x requires Node.js version >= 14.0.0. Projects running on older Node.js environments will encounter errors.","severity":"breaking","affected_versions":">=8.0.0"},{"fix":"Ensure `promise()` middleware is included in your `getIt` configuration: `getIt([/* other middleware */, promise()])` or `request.use(promise())`.","message":"By default, `getIt()` returns a low-level event emitter stream. To use a Promise-based API (e.g., `.then()`, `await`), you must explicitly apply the `promise()` middleware to your `getIt` instance.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Be mindful of the execution environment when developing universal code. Implement conditional logic or abstraction layers if these differences are critical to your application's behavior.","message":"Behavior for certain options like `maxRedirects` and the type of `rawBody` varies between Node.js and browser environments due to underlying platform differences. `maxRedirects` only applies in Node.js, while browsers handle redirects internally. `rawBody` returns `ArrayBuffer` in browsers and `Buffer` in Node.js.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always include `jsonResponse()` middleware if you expect to receive and automatically parse JSON responses. Conversely, omit it if you need the raw string body.","message":"The library's middleware architecture means that omitting crucial middleware, such as `jsonResponse()`, will prevent automatic JSON parsing, leading to raw string responses even if the server sends JSON.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Add `promise()` to your middleware chain: `const request = getIt([..., promise()]);`","cause":"The `promise()` middleware was not applied to the `get-it` instance, meaning the returned object is an event emitter, not a Promise.","error":"TypeError: request.then is not a function"},{"fix":"Verify the server is sending valid JSON and setting the `Content-Type` header correctly (e.g., `application/json`). If the response is not JSON, remove `jsonResponse()` middleware or add custom parsing logic.","cause":"The `jsonResponse()` middleware was used, but the server's response was not valid JSON or the `Content-Type` header did not indicate JSON.","error":"Error: \"Could not parse response body as JSON\""},{"fix":"Use ESM `import` statements: `import { getIt } from 'get-it';` and `import { ... } from 'get-it/middleware';`. Ensure your project is configured for ESM (e.g., `\"type\": \"module\"` in `package.json` or using `.mjs` extensions).","cause":"Attempting to import `get-it` or its middleware using CommonJS `require()` syntax in an environment that expects ESM, or when the package's `package.json` explicitly defines it as type `module`.","error":"ERR_REQUIRE_ESM"},{"fix":"Increase the `timeout` values in the `timeout` middleware (e.g., `{ connect: 10000, socket: 30000 }`). Verify network connectivity to the target server.","cause":"The HTTP request exceeded the configured `connect` or `socket` timeout, typically due to network latency, server unresponsiveness, or an unreachable host.","error":"Error: Request timed out after Xms"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":""}