Cloudflare TypeScript API Library

repository·main·Indexed 20 days ago

https://github.com/cloudflare/cloudflare-typescript

The official TypeScript library (version 7.0.0) providing type-safe access to the Cloudflare REST API for server-side environments. It supports Node.js 20+, Deno, Bun, Cloudflare Workers, and Vercel Edge Runtime. Key features include auto-pagination, tree-shaking for reduced bundle size, configurable retries and timeouts, and comprehensive TypeScript definitions for request and response fields.

Tokens
283.6K
Snippets
875
Records
1.8K
Agent score
73%

What's inside cloudflare-typescript

  1. Iterate through paginated results

    main

    Cloudflare API list methods are paginated. You have two ways to handle this:

    1. Auto-pagination: Use the for await ... of syntax to automatically fetch all pages as you iterate.
    2. Manual pagination: Request a single page and use .hasNextPage() and .getNextPage() to navigate manually.
    // Option 1: Auto-pagination
    async function fetchAllAccounts(params) {
      const allAccounts = [];
      for await (const account of client.accounts.list()) {
        allAccounts.push(account);
      }
      return allAccounts;
    }
    
    // Option 2: Manual pagination
    let page = await client.accounts.list();
    for (const account of page.result) {
      console.log(account);
    }
    
    while (page.hasNextPage()) {
      page = await page.getNextPage();
      // ...
    }
  2. Reduce bundle size with tree shaking

    main

    To reduce bundle size, you can create a tree-shakable client that only includes the specific API resources you need. This is done by importing createClient from cloudflare/tree-shakable and providing a resources array.

    Each API resource has two versions:

    • Full resource (e.g., Zones): Includes all subresources.
    • Base resource (e.g., BaseZones): Does not include subresources.

    The tree-shaken client is fully typed. You can use the PartialCloudflare type to explicitly type variables or function parameters for a client containing specific resources.

    import { createClient } from 'cloudflare/tree-shakable';
    import { Zones } from 'cloudflare/resources/zones/zones';
    import { BaseAccounts } from 'cloudflare/resources/accounts/accounts';
    
    const client = createClient({
      resources: [Zones, BaseAccounts],
    });
    
    // The client is fully typed
    const zone = await client.zones.create({
      account: { id: '...' },
      name: 'example.com',
    });
  3. Handle Web API changes for `withResponse`, `asResponse`, and `APIError.headers`

    main

    The library now uses the built-in Web fetch API across all platforms. If your code relies on node-fetch-specific properties, you must update it to use standardized Web alternatives:

    1. Response Bodies: The body property is now a Web ReadableStream instead of a Node.js Readable. To use Node.js stream methods like .pipe(), wrap the body using Readable.fromWeb() from the node:stream module.
    2. Error Headers: The headers property on APIError objects is now an instance of the Web Headers class. It is no longer a plain Record<string, string | null | undefined>.
    // Before:
    const res = await client.example.retrieve('string/with/slash').asResponse();
    res.body.pipe(process.stdout);
    
    // After:
    import { Readable } from 'node:stream';
    const res = await client.example.retrieve('string/with/slash').asResponse();
    Readable.fromWeb(res.body).pipe(process.stdout);
  4. Use native streams instead of `fileFromPath` for uploads

    main

    The fileFromPath helper has been removed. For file uploads, use native Node.js streams or runtime-specific file APIs (like Bun.file for Bun).

    // Before
    Cloudflare.fileFromPath('path/to/file');
    
    // After
    import fs from 'fs';
    fs.createReadStream('path/to/file');
  5. Provide explicit arguments for request options overloads

    main

    When calling methods that do not require a body, query, or header parameters, you can no longer pass the options object as the first argument. You must now explicitly provide null, undefined, or an empty object {} as the first argument to reach the options argument.

    Example transition:

    - client.example.list({ headers: { ... } });
    + client.example.list({}, { headers: { ... } });
    + client.example.list(null, { headers: { ... } });
    + client.example.list(undefined, { headers: { ... } });
    client.example.list();
    client.example.list({}, { headers: { ... } });
    client.example.list(null, { headers: { ... } });
    client.example.list(undefined, { headers: { ... } });
    - client.example.list({ headers: { ... } });
    + client.example.list({}, { headers: { ... } });
  6. Update imports for core modules

    main

    The library has been refactored to separate internal and public code. Many modules previously available at the top level have been moved to a core directory. Update your import paths as follows:

    // Before
    import 'cloudflare/error';
    import 'cloudflare/pagination';
    import 'cloudflare/resource';
    import 'cloudflare/uploads';
    
    // After
    import 'cloudflare/core/error';
    import 'cloudflare/core/pagination';
    import 'cloudflare/core/resource';
    import 'cloudflare/core/uploads';
  7. Make custom or undocumented requests

    main

    If you need to interact with undocumented endpoints or use undocumented parameters, you can bypass the library's type safety:

    • Undocumented Endpoints: Use the HTTP verb methods directly on the client (e.g., client.post('/path')). Client options like retries are still respected.
    • Undocumented Parameters: Pass the parameter and use // @ts-expect-error to suppress TypeScript errors. For GET requests, extra params are sent as query strings; for other verbs, they are sent in the request body.
    • Undocumented Response Properties: Access properties on the returned object using // @ts-expect-error or by casting to a custom type.

    Note: The library does not validate or strip extra properties at runtime; they will be sent to the API as-is.

    // Undocumented endpoint
    await client.post('/some/path', {
      body: { some_prop: 'foo' },
      query: { some_query_arg: 'bar' },
    });
    
    // Undocumented parameter
    client.zones.create({
      // @ts-expect-error baz is not yet public
      baz: 'undocumented option',
    });
  8. Replace `httpAgent` with `fetchOptions` for proxy support

    main

    The httpAgent option has been removed because it relied on node:http agents, which are incompatible with the built-in fetch implementation used by modern runtimes. To configure proxies or custom fetch behavior, use the fetchOptions property. If you are in a Node.js environment, use undici.ProxyAgent to provide a dispatcher within fetchOptions.

    import Cloudflare from 'cloudflare';
    import * as undici from 'undici';
    
    const proxyAgent = new undici.ProxyAgent(process.env.PROXY_URL);
    const client = new Cloudflare({
      fetchOptions: {
        dispatcher: proxyAgent,
      },
    });