Skip to content

Commit d2df724

Browse files
docs: document customizing fetch (#204)
1 parent 5983d5e commit d2df724

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

README.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,45 @@ const completion: Completions.Completion = await response.parse();
289289
console.log(completion.completion);
290290
```
291291

292+
## Customizing the fetch client
293+
294+
By default, this library uses `node-fetch` in Node, and expects a global `fetch` function in other environments.
295+
296+
If you would prefer to use a global, web-standards-compliant `fetch` function even in a Node environment,
297+
(for example, if you are running Node with `--experimental-fetch` or using NextJS which polyfills with `undici`),
298+
add the following import before your first import `from "Anthropic"`:
299+
300+
<!-- prettier-ignore -->
301+
```ts
302+
// Tell TypeScript and the package to use the global web fetch instead of node-fetch.
303+
// Note, despite the name, this does not add any polyfills, but expects them to be provided if needed.
304+
import "@anthropic-ai/sdk/shims/web";
305+
import Anthropic from "@anthropic-ai/sdk";
306+
```
307+
308+
To do the inverse, add `import "@anthropic-ai/sdk/shims/node"` (which does import polyfills).
309+
This can also be useful if you are getting the wrong TypeScript types for `Response` - more details [here](https://github.com/anthropics/anthropic-sdk-typescript/src/_shims#readme).
310+
311+
You may also provide a custom `fetch` function when instantiating the client,
312+
which can be used to inspect or alter the `Request` or `Response` before/after each request:
313+
314+
```ts
315+
import { fetch } from 'undici'; // as one example
316+
import Anthropic from '@anthropic-ai/sdk';
317+
318+
const client = new Anthropic({
319+
fetch: (url: RequestInfo, init?: RequestInfo): Response => {
320+
console.log('About to make request', url, init);
321+
const response = await fetch(url, init);
322+
console.log('Got response', response);
323+
return response;
324+
},
325+
});
326+
```
327+
328+
Note that if given a `DEBUG=true` environment variable, this library will log all requests and responses automatically.
329+
This is intended for debugging purposes only and may change in the future without notice.
330+
292331
## Configuring an HTTP(S) Agent (e.g., for proxies)
293332

294333
By default, this library uses a stable agent for all http/https requests to reuse TCP connections, eliminating many TCP & TLS handshakes and shaving around 100ms off most requests.

0 commit comments

Comments
 (0)