### Basic Request Example Source: https://github.com/sindresorhus/got/blob/main/documentation/migration-guides/request.md Compares a basic GET request using the 'request' library with its equivalent in 'got'. Note the use of async/await and try/catch in 'got'. ```javascript import request from 'request'; request('https://google.com', (error, response, body) => { console.log('error:', error); console.log('statusCode:', response && response.statusCode); console.log('body:', body); }); ``` ```javascript import got from 'got'; try { const response = await got('https://google.com'); console.log('statusCode:', response.statusCode); console.log('body:', response.body); } catch (error) { console.log('error:', error); } ``` -------------------------------- ### Subscribe to 'got:request:start' Channel Source: https://github.com/sindresorhus/got/blob/main/documentation/diagnostics-channel.md Example of subscribing to the 'got:request:start' diagnostic channel to log request details. Ensure the 'node:diagnostics_channel' module is imported. ```javascript import diagnosticsChannel from 'node:diagnostics_channel'; const channel = diagnosticsChannel.channel('got:request:start'); channel.subscribe(message => { console.log(`${message.method} ${message.url}`); }); ``` -------------------------------- ### Handle Redirects with beforeRedirect Example Source: https://github.com/sindresorhus/got/blob/main/documentation/9-hooks.md Example demonstrating how to use the `beforeRedirect` hook to change the hostname if it points to a 'deadSite'. ```javascript import got from 'got'; const response = await got('https://example.com', { hooks: { beforeRedirect: [ (options, response) => { if (options.hostname === 'deadSite') { options.hostname = 'fallbackSite'; } } ] } }); ``` -------------------------------- ### Install and Use Keyv Redis Adapter Source: https://github.com/sindresorhus/got/blob/main/documentation/cache.md Shows how to install the `@keyv/redis` package and use a Redis instance as a cache adapter for Got. Ensure you have a Redis server running and accessible. ```sh npm install @keyv/redis ``` ```javascript import got from 'got'; import KeyvRedis from '@keyv/redis'; const redis = new KeyvRedis('redis://user:pass@localhost:6379'); await got('https://sindresorhus.com', {cache: redis}); ``` -------------------------------- ### Install Got using npm Source: https://github.com/sindresorhus/got/blob/main/readme.md Install the Got package using npm. This package is native ESM and does not provide a CommonJS export. ```sh npm install got ``` -------------------------------- ### Log Retry Information with beforeRetry Example Source: https://github.com/sindresorhus/got/blob/main/documentation/9-hooks.md This example shows how to use the `beforeRetry` hook to log the retry count and error code when a request fails and is retried. ```javascript import got from 'got'; await got('https://httpbin.org/status/500', { hooks: { beforeRetry: [ (error, retryCount) => { console.log(`Retrying [${retryCount}]: ${error.code}`); // Retrying [1]: ERR_NON_2XX_3XX_RESPONSE } ] } }); ``` -------------------------------- ### Basic Usage of gh-got Source: https://github.com/sindresorhus/got/blob/main/documentation/lets-make-a-plugin.md Demonstrates how to use the 'gh-got' library to fetch a user's profile information and log its creation date. This is a simple example of making an authenticated API request. ```javascript import ghGot from 'gh-got'; const response = await ghGot('users/sindresorhus'); const creationDate = new Date(response.created_at); console.log(`Sindre's GitHub profile was created on ${creationDate.toGMTString()}`); // => Sindre's GitHub profile was created on Sun, 20 Dec 2009 22:57:02 GMT ``` -------------------------------- ### Make a GET Request Source: https://github.com/sindresorhus/got/blob/main/documentation/quick-start.md Perform a simple GET request to a URL. The response object is a Promise. ```javascript import got from 'got'; const url = 'https://httpbin.org/anything'; const response = await got(url); ``` -------------------------------- ### Handle Unknown Options with Init Hook Source: https://github.com/sindresorhus/got/blob/main/documentation/tips.md This example shows how to prevent Got from throwing errors on unknown options by reading them in an `init` hook. Custom options are stored in `options.context`. ```javascript import got from 'got'; const convertFoo = got.extend({ hooks: { init: [ (rawOptions, options) => { if ('foo' in rawOptions) { options.context.foo = rawOptions.foo; delete rawOptions.foo; } } ] } }); const instance = got.extend(convertFoo, { hooks: { beforeRequest: [ options => { options.headers.foo = options.context.foo; } ] } }); const {headers} = await instance('https://httpbin.org/anything', {foo: 'bar'}).json(); console.log(headers.Foo); //=> 'bar' ``` -------------------------------- ### Incomplete Stack Trace Example Source: https://github.com/sindresorhus/got/blob/main/documentation/async-stack-traces.md Illustrates the typical output of an error stack trace from a basic async operation, showing the lack of information about where the async task was initiated. ```text file:///home/szm/Desktop/got/demo.js:3 reject(new Error('here')); ^ Error: here at Timeout._onTimeout (file:///home/szm/Desktop/got/demo.js:3:10) at listOnTimeout (node:internal/timers:557:17) at processTimers (node:internal/timers:500:7) ``` -------------------------------- ### Simple GET Request with JSON Parsing Source: https://context7.com/sindresorhus/got/llms.txt Make a simple GET request and parse the JSON response body. Requires the 'got' package to be imported. ```js import got from 'got'; // Simple GET, parse JSON body const data = await got('https://httpbin.org/anything').json(); console.log(data.method); ``` -------------------------------- ### Handling HTTP Response Streams Source: https://github.com/sindresorhus/got/blob/main/documentation/3-streams.md This example demonstrates how to handle an HTTP response as a stream, check response headers, and pipe the stream to a file. It also shows how to manage errors and destroy the stream if necessary. ```APIDOC ## stream.on('response', …) ### Description This event is emitted when an HTTP response is received. ### Parameters #### Response Object - **response** (PlainResponse) - The HTTP response object. ### Request Example ```js import {pipeline as streamPipeline} from 'node:stream/promises'; import {createWriteStream} from 'node:fs'; import got from 'got'; const readStream = got.stream('http://example.com/image.png', {throwHttpErrors: false}); const onError = error => { // Do something with it. }; readStream.on('response', async response => { if (response.headers.age > 3600) { console.log('Failure - response too old'); readStream.destroy(); // Destroy the stream to prevent hanging resources. return; } // Prevent `onError` being called twice. readStream.off('error', onError); try { await streamPipeline( readStream, createWriteStream('image.png') ); console.log('Success'); } catch (error) { onError(error); } }); readStream.once('error', onError); ``` ``` -------------------------------- ### Modify Cache Headers with beforeCache Example Source: https://github.com/sindresorhus/got/blob/main/documentation/9-hooks.md This example shows how to use `beforeCache` to explicitly set the `cache-control` header, influencing how the response is cached. ```javascript import got from 'got'; // Advanced: Modify headers for fine control const instance2 = got.extend({ cache: new Map(), hooks: { beforeCache: [ (response) => { // Force caching with explicit duration // Mutations work directly - no need to return response.headers['cache-control'] = 'public, max-age=3600'; } ] } }); ``` -------------------------------- ### Example Async Stack Trace Source: https://github.com/sindresorhus/got/blob/main/documentation/async-stack-traces.md This is an example of a long, detailed asynchronous stack trace generated by Node.js. Such traces can be very verbose, especially in complex applications involving multiple asynchronous operations. ```text Error: Timeout awaiting 'request' for 1ms at ClientRequest. (file:///home/szm/Desktop/got/dist/source/core/index.js:780:61) at Object.onceWrapper (node:events:514:26) at ClientRequest.emit (node:events:406:35) at TLSSocket.socketErrorListener (node:_http_client:447:9) at TLSSocket.emit (node:events:394:28) at emitErrorNT (node:internal/streams/destroy:157:8) at emitErrorCloseNT (node:internal/streams/destroy:122:3) at processTicksAndRejections (node:internal/process/task_queues:83:21) at emitInitScript (node:internal/async_hooks:493:3) at process.nextTick (node:internal/process/task_queues:133:5) at onDestroy (node:internal/streams/destroy:96:15) at TLSSocket.Socket._destroy (node:net:677:5) at _destroy (node:internal/streams/destroy:102:25) at TLSSocket.destroy (node:internal/streams/destroy:64:5) at ClientRequest.destroy (node:_http_client:371:16) at emitInitScript (node:internal/async_hooks:493:3) at initAsyncResource (node:internal/timers:162:5) at new Timeout (node:internal/timers:196:3) at setTimeout (node:timers:164:19) at addTimeout (file:///home/szm/Desktop/got/dist/source/core/timed-out.js:32:25) at timedOut (file:///home/szm/Desktop/got/dist/source/core/timed-out.js:59:31) at Request._onRequest (file:///home/szm/Desktop/got/dist/source/core/index.js:771:32) at emitInitScript (node:internal/async_hooks:493:3) at promiseInitHook (node:internal/async_hooks:323:3) at promiseInitHookWithDestroyTracking (node:internal/async_hooks:327:3) at Request.flush (file:///home/szm/Desktop/got/dist/source/core/index.js:274:24) at makeRequest (file:///home/szm/Desktop/got/dist/source/as-promise/index.js:125:30) at Request. (file:///home/szm/Desktop/got/dist/source/as-promise/index.js:121:17) at Object.onceWrapper (node:events:514:26) at emitInitScript (node:internal/async_hooks:493:3) at promiseInitHook (node:internal/async_hooks:323:3) at promiseInitHookWithDestroyTracking (node:internal/async_hooks:327:3) at file:///home/szm/Desktop/got/dist/source/core/index.js:357:27 at processTicksAndRejections (node:internal/process/task_queues:96:5) at emitInitScript (node:internal/async_hooks:493:3) at promiseInitHook (node:internal/async_hooks:323:3) at promiseInitHookWithDestroyTracking (node:internal/async_hooks:327:3) at file:///home/szm/Desktop/got/dist/source/core/index.js:338:50 at Request._beforeError (file:///home/szm/Desktop/got/dist/source/core/index.js:388:11) at ClientRequest. (file:///home/szm/Desktop/got/dist/source/core/index.js:781:18) at Object.onceWrapper (node:events:514:26) at emitInitScript (node:internal/async_hooks:493:3) at process.nextTick (node:internal/process/task_queues:133:5) at onDestroy (node:internal/streams/destroy:96:15) at TLSSocket.Socket._destroy (node:net:677:5) at _destroy (node:internal/streams/destroy:102:25) at TLSSocket.destroy (node:internal/streams/destroy:64:5) at ClientRequest.destroy (node:_http_client:371:16) at emitInitScript (node:internal/async_hooks:493:3) at initAsyncResource (node:internal/timers:162:5) at new Timeout (node:internal/timers:196:3) at setTimeout (node:timers:164:19) at addTimeout (file:///home/szm/Desktop/got/dist/source/core/timed-out.js:32:25) at timedOut (file:///home/szm/Desktop/got/dist/source/core/timed-out.js:59:31) at Request._onRequest (file:///home/szm/Desktop/got/dist/source/core/index.js:771:32) at emitInitScript (node:internal/async_hooks:493:3) at promiseInitHook (node:internal/async_hooks:323:3) at promiseInitHookWithDestroyTracking (node:internal/async_hooks:327:3) at Request.flush (file:///home/szm/Desktop/got/dist/source/core/index.js:274:24) at lastHandler (file:///home/szm/Desktop/got/dist/source/create.js:37:26) at iterateHandlers (file:///home/szm/Desktop/got/dist/source/create.js:49:28) at got (file:///home/szm/Desktop/got/dist/source/create.js:69:16) at Timeout.timeoutHandler [as _onTimeout] (file:///home/szm/Desktop/got/dist/source/core/timed-out.js:42:25) at listOnTimeout (node:internal/timers:559:11) at processTimers (node:internal/timers:500:7) ``` -------------------------------- ### GET Request with Options Source: https://github.com/sindresorhus/got/blob/main/documentation/quick-start.md Make a GET request with custom headers and a send timeout. The response body is parsed as JSON. ```javascript import got from 'got'; const url = 'https://httpbin.org/anything'; const options = { headers: { 'Custom-Header': 'Quick start', }, timeout: { send: 3500 }, }; const data = await got(url, options).json(); ``` -------------------------------- ### Upload Progress for Stream Body with Got Source: https://github.com/sindresorhus/got/blob/main/documentation/3-streams.md Demonstrates how to get granular upload progress for stream bodies using the `chunk-data` package. The `content-length` header must be set manually. ```javascript import fs from 'node:fs'; import got from 'got'; import {chunkFromAsync} from 'chunk-data'; const filePath = 'large-file.bin'; const stream = fs.createReadStream(filePath); const size = fs.statSync(filePath).size; await got.post('https://httpbin.org/anything', { body: chunkFromAsync(stream, 65_536), headers: { 'content-length': size } }) .on('uploadProgress', progress => { console.log(progress); }); ``` -------------------------------- ### Proxying Headers with Streams (request) Source: https://github.com/sindresorhus/got/blob/main/documentation/migration-guides/request.md Example of how 'request' library handles header proxying with streams. ```javascript http.createServer((serverRequest, serverResponse) => { if (serverRequest.url === '/doodle.png') { serverRequest.pipe(request('https://example.com/doodle.png')).pipe(serverResponse); } }); ``` -------------------------------- ### Configure Proxy with hpagent Source: https://github.com/sindresorhus/got/blob/main/documentation/tips.md Use the hpagent package to configure an HTTPS proxy for Got requests. This example demonstrates setting up an HTTPS proxy with keep-alive options. ```javascript import got from 'got'; import {HttpsProxyAgent} from 'hpagent'; await got('https://sindresorhus.com', { agent: { https: new HttpsProxyAgent({ keepAlive: true, keepAliveMsecs: 1000, maxSockets: 256, maxFreeSockets: 256, scheduling: 'lifo', proxy: 'https://localhost:8080' }) } }); ``` -------------------------------- ### Example Error with Captured Stack Trace Source: https://github.com/sindresorhus/got/blob/main/documentation/async-stack-traces.md This is an example of an error object produced by the Got instance configured with the stack trace capturing handler. The `source` property contains the captured stack trace, making it easier to debug. ```text RequestError: Timeout awaiting 'request' for 100ms at ClientRequest. (file:///home/szm/Desktop/got/dist/source/core/index.js:780:61) at Object.onceWrapper (node:events:514:26) at ClientRequest.emit (node:events:406:35) at TLSSocket.socketErrorListener (node:_http_client:447:9) at TLSSocket.emit (node:events:394:28) at emitErrorNT (node:internal/streams/destroy:157:8) at emitErrorCloseNT (node:internal/streams/destroy:122:3) at processTicksAndRejections (node:internal/process/task_queues:83:21) at Timeout.timeoutHandler [as _onTimeout] (file:///home/szm/Desktop/got/dist/source/core/timed-out.js:42:25) at listOnTimeout (node:internal/timers:559:11) at processTimers (node:internal/timers:500:7) { input: undefined, code: 'ETIMEDOUT', timings: { }, name: 'TimeoutError', options: { }, event: 'request', source: [ 'Error', ' at got.extend.handlers (file:///home/szm/Desktop/got/demo.js:6:10)', ' at iterateHandlers (file:///home/szm/Desktop/got/dist/source/create.js:49:28)', ' at got (file:///home/szm/Desktop/got/dist/source/create.js:69:16)', ' at file:///home/szm/Desktop/got/demo.js:23:8', ' at ModuleJob.run (node:internal/modules/esm/module_job:183:25)', ' at async Loader.import (node:internal/modules/esm/loader:178:24)', ' at async Object.loadESM (node:internal/process/esm_loader:68:5)', ' at async handleMainPromise (node:internal/modules/run_main:63:12)' ] } ``` -------------------------------- ### Basic HTTP Request with Got Source: https://github.com/sindresorhus/got/blob/main/documentation/migration-guides/nodejs.md Simplifies making a GET request using the Got library, handling responses and errors concisely. ```javascript import got from 'got'; try { const {body} = await got('https://httpbin.org/anything'); console.log(body); } catch (error) { console.error(error); } ``` -------------------------------- ### Make HTTP Request with Got Promise API Source: https://github.com/sindresorhus/got/blob/main/documentation/1-promise.md Demonstrates making a GET request and accessing response headers after parsing the JSON body. Ensure 'got' is imported. ```javascript import got from 'got'; const {headers} = await got( 'https://httpbin.org/anything', { headers: { foo: 'bar' } } ).json(); ``` -------------------------------- ### Storing Custom Data with init and beforeRequest Hooks Source: https://github.com/sindresorhus/got/blob/main/documentation/9-hooks.md Demonstrates using `init` to store custom data in `options.context` and `beforeRequest` to access and use it. This example stores a 'secret' from the initial options and adds it to the request headers. ```javascript import got from 'got'; const instance = got.extend({ hooks: { init: [ (plain, options) => { if ('secret' in plain) { options.context.secret = plain.secret; delete plain.secret; } } ], beforeRequest: [ options => { options.headers.secret = options.context.secret; } ] } }); const {headers} = await instance( 'https://httpbin.org/anything', { secret: 'passphrase' } ).json(); console.log(headers.Secret); //=> 'passphrase' ``` -------------------------------- ### Implement Cache with Custom Request Function Source: https://github.com/sindresorhus/got/blob/main/documentation/cache.md Shows how to create a custom `request` function within `got.extend` to intercept requests and return a cached response. This example simulates a cached response using a `Readable` stream. ```javascript import https from 'node:https'; import {Readable} from 'node:stream'; import got from 'got'; const getCachedResponse = (url, options) => { const response = new Readable({ read() { this.push("Hello, world!"); this.push(null); } }); response.statusCode = 200; response.headers = {}; response.trailers = {}; response.socket = null; response.aborted = false; response.complete = true; response.httpVersion = '1.1'; response.httpVersionMinor = 1; response.httpVersionMajor = 1; return response; }; const instance = got.extend({ request: (url, options, callback) => { return getCachedResponse(url, options); } }); const body = await instance('https://example.com').text(); console.log(body); //=> "Hello, world!" ``` -------------------------------- ### Basic HTTP Request with Node.js http Source: https://github.com/sindresorhus/got/blob/main/documentation/migration-guides/nodejs.md Illustrates a basic GET request using the native Node.js http module, including response handling and error management. ```javascript import http from 'node:http'; const request = http.request('https://httpbin.org/anything', response => { if (response.statusCode >= 400) { request.destroy(new Error()); return; } const chunks = []; let totalLength = 0; response.on('data', chunk => { chunks.push(chunk); totalLength += chunk.length; }); response.once('end', () => { const bytes = new Uint8Array(totalLength); let offset = 0; for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.length; } if (response.statusCode >= 400) { const error = new Error(`Unsuccessful response: ${response.statusCode}`); error.body = new TextDecoder().decode(bytes); return; } const text = new TextDecoder().decode(bytes); console.log(text); }); response.once('error', console.error); }); request.once('error', console.error); request.end(); ``` -------------------------------- ### Use QuickLRU Storage Adapter Source: https://github.com/sindresorhus/got/blob/main/documentation/cache.md Shows how to use `QuickLRU` as a cache storage adapter for Got, configuring it with a maximum size. ```javascript import QuickLRU from 'quick-lru'; const storageAdapter = new QuickLRU({maxSize: 1000}); await got('https://sindresorhus.com', {cache: storageAdapter}); ``` -------------------------------- ### Custom JSON Stringification: Ignore Underscore Properties Source: https://github.com/sindresorhus/got/blob/main/documentation/2-options.md Customize how JSON request bodies are stringified using `stringifyJson`. This example ignores properties starting with an underscore. ```javascript import got from 'got'; await got.post('https://example.com', { stringifyJson: object => JSON.stringify(object, (key, value) => { if (key.startsWith('_')) { return; } return value; }), json: { some: 'payload', _ignoreMe: 1234 } }); ``` -------------------------------- ### Extend Got Client with Options Source: https://github.com/sindresorhus/got/blob/main/documentation/quick-start.md Create a reusable client instance with default options like prefix URL and authorization headers. ```javascript import got from 'got'; const options = { prefixUrl: 'https://httpbin.org', headers: { Authorization: getTokenFromVault(), }, }; const client = got.extend(options); export default client; ``` -------------------------------- ### Use Got with Options Class Source: https://github.com/sindresorhus/got/blob/main/documentation/2-options.md Demonstrates creating a Got instance with an Options class for centralized configuration and early validation. Modifying options on the class instance updates the configuration. ```javascript import got, {Options} from 'got'; const options = new Options({ prefixUrl: 'https://httpbin.org', headers: { foo: 'foo' } }); options.headers.foo = 'bar'; // Use got.extend() to create an instance with the Options const instance = got.extend(options); const {headers} = await instance('anything').json(); console.log(headers.foo); //=> 'bar' ``` -------------------------------- ### Test Got Requests with Nock Source: https://github.com/sindresorhus/got/blob/main/documentation/tips.md Mock HTTP requests using Nock for testing. This example sets up a persistent mock for a GET request that replies with a 500 error, demonstrating retry behavior. ```javascript import got from 'got'; import nock from 'nock'; const scope = nock('https://sindresorhus.com') .get('/') .reply(500, 'Internal server error') .persist(); try { await got('https://sindresorhus.com') } catch (error) { console.log(error.response.body); //=> 'Internal server error' console.log(error.response.retryCount); //=> 2 } scope.persist(false); ``` -------------------------------- ### Set Content-Length for File Streams Source: https://github.com/sindresorhus/got/blob/main/documentation/2-options.md When sending a file stream as the request body, the 'content-length' header must be manually set. This example shows how to get the file size using `fsPromises.stat` and provide it in the headers. ```javascript import fs from 'node:fs'; import fsPromises from 'node:fs/promises'; import got from 'got'; const filePath = 'path/to/file'; const fileStats = await fsPromises.stat(filePath); const fileStream = fs.createReadStream(filePath); await got.post('https://httpbin.org/anything', { body: fileStream, headers: { 'content-length': fileStats.size.toString() } }); ``` -------------------------------- ### Use Third-Party Storage Adapter Source: https://github.com/sindresorhus/got/blob/main/documentation/cache.md Demonstrates integrating a third-party storage adapter, imported from a local file, with Got's caching mechanism. ```javascript import storageAdapter from './my-storage-adapter'; await got('https://sindresorhus.com', {cache: storageAdapter}); ``` -------------------------------- ### Get JSON Response Source: https://github.com/sindresorhus/got/blob/main/documentation/quick-start.md Retrieve and parse a JSON response directly from a GET request. ```javascript import got from 'got'; const url = 'https://httpbin.org/anything'; const data = await got(url).json(); ``` -------------------------------- ### Enable Unix Sockets with Got Source: https://github.com/sindresorhus/got/blob/main/documentation/2-options.md Demonstrates how to use Unix domain sockets for requests. You can enable this option per-request or for an entire Got instance using `got.extend`. Ensure proper URL sanitization if accepting untrusted user input. ```javascript import got from 'got'; await got('http://unix:/var/run/docker.sock:/containers/json', {enableUnixSockets: true}); // Or without protocol (HTTP by default) await got('unix:/var/run/docker.sock:/containers/json', {enableUnixSockets: true}); // Enable Unix sockets for the whole instance. const gotWithUnixSockets = got.extend({enableUnixSockets: true}); await gotWithUnixSockets('http://unix:/var/run/docker.sock:/containers/json'); ``` -------------------------------- ### Provide Multiple Client Keys and Certificates Source: https://github.com/sindresorhus/got/blob/main/documentation/5-https.md Use this when multiple client keys and certificates are available and need to be provided, potentially out of order. The library will handle matching them. ```javascript import got from 'got'; // Multiple keys with certificates (out of order) await got('https://example.com', { https: { key: [ fs.readFileSync('./client_key1.pem'), fs.readFileSync('./client_key2.pem') ], certificate: [ fs.readFileSync('./client_cert2.pem'), fs.readFileSync('./client_cert1.pem') ] } }); ``` -------------------------------- ### Enable GET Request Body Source: https://github.com/sindresorhus/got/blob/main/documentation/2-options.md Set `allowGetBody` to `true` to send a body with GET requests. Note that this is non-compliant with HTTP/2 and generally considered an anti-pattern. -------------------------------- ### Proxying Headers with Streams (got) Source: https://github.com/sindresorhus/got/blob/main/documentation/migration-guides/request.md Demonstrates 'got' stream usage with opt-in header proxying using `copyPipedHeaders: true`. ```javascript import {pipeline as streamPipeline} from 'node:stream/promises'; import got from 'got'; const server = http.createServer(async (serverRequest, serverResponse) => { if (serverRequest.url === '/doodle.png') { await streamPipeline( serverRequest, got.stream('https://example.com/doodle.png', {copyPipedHeaders: true}), serverResponse ); } }); server.listen(8080); ``` -------------------------------- ### Stream GET Response to File with Got Source: https://github.com/sindresorhus/got/blob/main/documentation/3-streams.md Streams the GET response of a URL directly to a file using `streamPipeline` for efficient data transfer and error handling. ```javascript import stream from 'node:stream'; import {pipeline as streamPipeline} from 'node:stream/promises'; import fs from 'node:fs'; import got from 'got'; // This example streams the GET response of a URL to a file. await streamPipeline( got.stream('https://sindresorhus.com'), fs.createWriteStream('index.html') ); ``` -------------------------------- ### Prevent Caching of Errors with beforeCache Example Source: https://github.com/sindresorhus/got/blob/main/documentation/9-hooks.md This example demonstrates using `beforeCache` to prevent caching responses with a status code of 400 or higher by returning `false`. ```javascript import got from 'got'; // Simple: Don't cache errors const instance = got.extend({ cache: new Map(), hooks: { beforeCache: [ (response) => response.statusCode >= 400 ? false : undefined ] } }); await instance('https://example.com'); ``` -------------------------------- ### Extend Got Instance with Options Source: https://github.com/sindresorhus/got/blob/main/documentation/10-instances.md Create a new Got instance with merged default options, including prefix URL and custom headers. Subsequent requests from this instance will include these configurations. ```javascript import got from 'got'; const client = got.extend({ prefixUrl: 'https://httpbin.org', headers: { 'x-foo': 'bar' } }); const {headers} = await client.get('headers').json(); console.log(headers['x-foo']); //=> 'bar' const jsonClient = client.extend({ responseType: 'json', resolveBodyOnly: true, headers: { 'x-lorem': 'impsum' } }); const {headers: headers2} = await jsonClient.get('headers'); console.log(headers2['x-foo']); //=> 'bar' console.log(headers2['x-lorem']); //=> 'impsum' ``` -------------------------------- ### Extend Got with Token Initialization Source: https://github.com/sindresorhus/got/blob/main/documentation/lets-make-a-plugin.md Configure a Got instance to handle authorization tokens. It uses an environment variable by default but can be overridden via options. The token is stored in `options.context`. ```javascript import got from 'got'; const instance = got.extend({ prefixUrl: 'https://api.github.com', headers: { accept: 'application/vnd.github.v3+json' }, responseType: 'json', context: { token: process.env.GITHUB_TOKEN, }, hooks: { init: [ (raw, options) => { if ('token' in raw) { options.context.token = raw.token; delete raw.token; } } ] } }); export default instance; ``` -------------------------------- ### Set HTTP Method Source: https://github.com/sindresorhus/got/blob/main/documentation/2-options.md Specify the HTTP method for the request using the `method` option. Defaults to `GET`. Common methods include `GET`, `POST`, `PUT`, and `DELETE`. ```javascript import got from 'got'; const {method} = await got('https://httpbin.org/anything', { method: 'POST' }).json(); console.log(method); // => 'POST' ``` -------------------------------- ### Catch-All Custom Options Instance Source: https://github.com/sindresorhus/got/blob/main/documentation/tips.md Creates a reusable Got instance that handles any unknown options by storing them in `options.context`. This is useful for creating flexible, catch-all configurations. ```javascript import got from 'got'; const catchAllOptions = got.extend({ hooks: { init: [ (raw, options) => { for (const key in raw) { if (!(key in options)) { options.context[key] = raw[key]; delete raw[key]; } } } ] } }); const instance = got.extend(catchAllOptions, { hooks: { beforeRequest: [ options => { // All custom options will be visible under `options.context` options.headers.foo = options.context.foo; } ] } }); const {headers} = await instance('https://httpbin.org/anything', {foo: 'bar'}).json(); console.log(headers.Foo); //=> 'bar' ``` -------------------------------- ### got(url, options, defaults) Source: https://github.com/sindresorhus/got/blob/main/documentation/1-promise.md The main Got function returns a Promise. Request aborting is supported via the `signal` option and `AbortController`. The most common way is to pass the URL as the first argument, then the options as the second. ```APIDOC ## got(url, options, defaults) ### Description Makes an HTTP request and returns a Promise that resolves with the response. ### Method `got(url: string | URL, options?: OptionsInit, defaults?: Options)` ### Returns `Promise` ### Example ```js import got from 'got'; const {headers} = await got( 'https://httpbin.org/anything', { headers: { foo: 'bar' } } ).json(); ``` ``` -------------------------------- ### method Source: https://github.com/sindresorhus/got/blob/main/documentation/2-options.md Specifies the HTTP method for the request. Defaults to GET. ```APIDOC ## `method` ### Description Sets the HTTP method used for the request. ### Type `string` ### Default `GET` ### Example ```js import got from 'got'; const {method} = await got('https://httpbin.org/anything', { method: 'POST' }).json(); console.log(method); // => 'POST' ``` ``` -------------------------------- ### Base URL for API Client Instance Source: https://context7.com/sindresorhus/got/llms.txt Create a reusable API client instance with a base URL using `got.extend()`. Subsequent requests will prepend this base URL. Requires the 'got' package to be imported. ```js import got from 'got'; const api = got.extend({prefixUrl: 'https://httpbin.org'}); // Equivalent to got('https://httpbin.org/anything') const data = await api('anything').json(); console.log(data.url); ``` -------------------------------- ### Filtering Headers When Proxying Source: https://github.com/sindresorhus/got/blob/main/documentation/3-streams.md This example demonstrates how to filter response headers when proxying a stream, allowing only specific headers to be passed through. ```APIDOC ## Example: Filter headers when proxying to ServerResponse ```js import {pipeline as streamPipeline} from 'node:stream/promises'; import got from 'got'; import express from 'express'; const app = express(); // Allowlist specific headers when proxying app.get('/proxy', async (request, response) => { await streamPipeline( got.stream(request.query.url).on('response', upstreamResponse => { // Only allow specific headers for (const header of Object.keys(upstreamResponse.headers)) { if (!['content-type', 'content-length'].includes(header.toLowerCase())) { delete upstreamResponse.headers[header]; } } }), response ); }); ``` ``` -------------------------------- ### Got URL Constructor Usage Source: https://github.com/sindresorhus/got/blob/main/documentation/2-options.md Shows that the URL can be passed as a string or a WHATWG URL object to the got function. Both methods are semantically equivalent. ```javascript import got from 'got'; // This: await got('https://httpbin.org/anything'); // is semantically the same as this: await got(new URL('https://httpbin.org/anything')); ``` -------------------------------- ### Handle Errors in Promise API Source: https://github.com/sindresorhus/got/blob/main/documentation/quick-start.md Catch errors from a GET request that results in a 404 status code and log the status code. ```javascript import got from 'got'; try { const data = await got.get('https://httpbin.org/status/404'); } catch (error) { console.error(error.response.statusCode); } ``` -------------------------------- ### Provide Single Client Key and Certificate Source: https://github.com/sindresorhus/got/blob/main/documentation/5-https.md Use this when a single client key and certificate are required for authentication. Ensure the files are correctly read using `fs.readFileSync`. ```javascript import got from 'got'; // Single key with certificate await got('https://example.com', { https: { key: fs.readFileSync('./client_key.pem'), certificate: fs.readFileSync('./client_cert.pem') } }); ``` -------------------------------- ### Custom JSON Stringification: Numbers as Strings Source: https://github.com/sindresorhus/got/blob/main/documentation/2-options.md Customize how JSON request bodies are stringified using `stringifyJson`. This example converts all numbers to strings. ```javascript import got from 'got'; await got.post('https://example.com', { stringifyJson: object => JSON.stringify(object, (key, value) => { if (typeof value === 'number') { return value.toString(); } return value; }), json: { some: 'payload', number: 1 } }); ``` -------------------------------- ### got.extend Source: https://context7.com/sindresorhus/got/llms.txt Compose reusable clients by creating new Got instances that inherit and merge parent defaults. Instances can be layered for complex configurations. ```APIDOC ## Instances API ### `got.extend(options | instances)` — Compose reusable clients Creates a new Got instance inheriting and merging parent defaults. Instances can be layered. ### Description Compose reusable clients by creating new Got instances that inherit and merge parent defaults. Instances can be layered for complex configurations. ### Usage ```js import got from 'got'; const base = got.extend({ prefixUrl: 'https://api.example.com/v1', headers: {'x-api-key': process.env.API_KEY}, retry: {limit: 3}, timeout: {request: 10_000} }); const jsonClient = base.extend({ responseType: 'json', resolveBodyOnly: true }); const users = await jsonClient('users'); const user = await jsonClient('users/42'); const deduped = got.extend({ handlers: [ (options, next) => { if (options.isStream) return next(options); const cache = new Map(); const key = options.url.href; const pending = cache.get(key); if (pending) return pending; const promise = next(options); cache.set(key, promise); promise.finally(() => cache.delete(key)); return promise; } ] }); ``` ``` -------------------------------- ### Configure HTTP/HTTPS Proxy with Custom Agents Source: https://context7.com/sindresorhus/got/llms.txt Shows how to configure Got to use an HTTP/HTTPS proxy by providing a custom agent. This is useful when your application needs to route requests through a proxy server. ```javascript import got from 'got'; import {HttpsProxyAgent} from 'hpagent'; await got('https://example.com', { agent: { https: new HttpsProxyAgent({ keepAlive: true, maxSockets: 256, proxy: 'https://proxy.example.com:8080' }) } }); ``` -------------------------------- ### Fixing Typos with init Hook Source: https://github.com/sindresorhus/got/blob/main/documentation/9-hooks.md Use the `init` hook to correct option typos before they are normalized. This example fixes a `followRedirects` typo to `followRedirect`. ```javascript import got from 'got'; const instance = got.extend({ hooks: { init: [ plain => { if ('followRedirects' in plain) { plain.followRedirect = plain.followRedirects; delete plain.followRedirects; } } ] } }); // Normally, the following would throw: const response = await instance( 'https://example.com', { followRedirects: true } ); // There is no option named `followRedirects`, but we correct it in an `init` hook. ``` -------------------------------- ### Send Iterable/AsyncIterable as Request Body Source: https://github.com/sindresorhus/got/blob/main/documentation/2-options.md Iterable and AsyncIterable objects, including Web ReadableStreams, can be used as the request body. This example uses an async generator. ```javascript import got from 'got'; // Using an async generator async function* generateData() { yield 'Hello, '; yield 'world!'; } await got.post('https://httpbin.org/anything', { body: generateData() }); ``` -------------------------------- ### Configure User-Agent Header Source: https://github.com/sindresorhus/got/blob/main/documentation/lets-make-a-plugin.md Extends the 'got' instance to include a 'user-agent' header, formatted with the package name and version. This is crucial for API identification and tracking. ```javascript const packageJson = { name: 'gh-got', version: '12.0.0' }; const instance = got.extend({ ... headers: { accept: 'application/vnd.github.v3+json', 'user-agent': `${packageJson.name}/${packageJson.version}` }, ... }); ``` -------------------------------- ### Inspect or retry based on response with `hooks.afterResponse` Source: https://context7.com/sindresorhus/got/llms.txt The `afterResponse` hook allows inspection of responses and retrying requests if necessary, for example, by refreshing an authentication token. ```javascript import got from 'got'; let accessToken = 'initial-token'; const api = got.extend({ mutableDefaults: true, hooks: { afterResponse: [ (response, retryWithMergedOptions) => { if (response.statusCode === 401) { accessToken = refreshToken(); // fetch a new token const updatedOptions = {headers: {authorization: `Bearer ${accessToken}`}}; api.defaults.options.merge(updatedOptions); return retryWithMergedOptions(updatedOptions); } return response; } ] } }); ``` -------------------------------- ### Enable HTTP/2 Support with `http2` Source: https://context7.com/sindresorhus/got/llms.txt Set `http2: true` to enable HTTP/2 with automatic ALPN negotiation. Got will fall back to HTTP/1.1 if the server does not support HTTP/2. ```javascript import got from 'got'; const {headers} = await got('https://httpbin.org/anything', {http2: true}); console.log(headers[':status']); //=> 200 ``` -------------------------------- ### Allow Connections to Servers with Legacy Renegotiation Source: https://github.com/sindresorhus/got/blob/main/documentation/5-https.md Configure `secureOptions` with `crypto.constants.SSL_OP_LEGACY_SERVER_CONNECT` to allow connections to legacy servers that do not support secure renegotiation. ```javascript import crypto from 'node:crypto'; import got from 'got'; // Allow connections to servers with legacy renegotiation await got('https://legacy-server.com', { https: { secureOptions: crypto.constants.SSL_OP_LEGACY_SERVER_CONNECT } }); ``` -------------------------------- ### Custom JSON Response Parsing Source: https://github.com/sindresorhus/got/blob/main/documentation/2-options.md Customize how JSON responses are parsed by providing a custom `parseJson` function. This example uses `@hapi/bourne` to prevent prototype pollution. ```javascript import got from 'got'; import Bourne from '@hapi/bourne'; // Preventing prototype pollution by using Bourne const parsed = await got('https://example.com', { parseJson: text => Bourne.parse(text) }).json(); console.log(parsed); ``` -------------------------------- ### Provide Multiple Client Keys with Different Passphrases Source: https://github.com/sindresorhus/got/blob/main/documentation/5-https.md Use this when multiple client keys are available, each protected by a different passphrase. Each key object should specify its PEM buffer and passphrase. ```javascript import got from 'got'; // Multiple keys with different passphrases await got('https://example.com', { https: { key: [ {pem: fs.readFileSync('./client_key1.pem'), passphrase: 'passphrase1'}, {pem: fs.readFileSync('./client_key2.pem'), passphrase: 'passphrase2'}, ], certificate: [ fs.readFileSync('./client_cert1.pem'), fs.readFileSync('./client_cert2.pem') ] } }); ``` -------------------------------- ### Custom Retry Delay Calculation Source: https://github.com/sindresorhus/got/blob/main/documentation/7-retry.md Example of customizing the delay between retries by scaling down the computed delay value. This function is called only when a retry is allowed by default rules. ```typescript import got from 'got'; await got('https://httpbin.org/anything', { retry: { limit: 3, calculateDelay: ({computedValue}) => { // When computedValue is 0, the default logic says don't retry // (limit exceeded, non-retryable error, etc.) if (computedValue === 0) { return 0; } // Scale down the delay return computedValue / 10; } } }); ``` -------------------------------- ### got.extend Source: https://github.com/sindresorhus/got/blob/main/documentation/10-instances.md Configures a new 'got' instance by merging default options with provided options. This is useful for creating clients with specific base URLs, headers, or other configurations. ```APIDOC ## got.extend(...options, ...instances) ### Description Configure a new `got` instance with merged default options. The options are merged with the parent instance's `defaults.options` using [`options.merge(…)`](2-options.md#merge). ### Tip - `options` can include `handlers` and `mutableDefaults`. ### Note - Properties that are not enumerable, such as `body`, `json`, and `form`, will not be merged. ### Example ```js import got from 'got'; const client = got.extend({ prefixUrl: 'https://httpbin.org', headers: { 'x-foo': 'bar' } }); const {headers} = await client.get('headers').json(); console.log(headers['x-foo']); //=> 'bar' const jsonClient = client.extend({ responseType: 'json', resolveBodyOnly: true, headers: { 'x-lorem': 'impsum' } }); const {headers: headers2} = await jsonClient.get('headers'); console.log(headers2['x-foo']); //=> 'bar' console.log(headers2['x-lorem']); //=> 'impsum' ``` ### Handler Notes - Handlers can be asynchronous and can return a `Promise`, but never a `Promise` when `options.isStream` is `true` (set internally for `got.stream()` requests). - Streams must always be handled synchronously. - In order to perform async work using streams, the `beforeRequest` hook should be used instead. ### Recommended Handler Approach ```js import got from 'got'; // Create a non-async handler, but we can return a Promise later. const handler = (options, next) => { // Internally set for requests created via `got.stream()`. if (options.isStream) { // It's a Stream, return synchronously. return next(options); } // For asynchronous work, return a Promise. return (async () => { try { const response = await next(options); response.yourOwnProperty = true; return response; } catch (error) { // Every error will be replaced by this one. // Before you receive any error here, // it will be passed to the `beforeError` hooks first. // Note: this one won't be passed to `beforeError` hook. It's final. throw new Error('Your very own error.'); } })(); }; const instance = got.extend({handlers: [handler]}); ``` ```