Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@apiclient.xyz/cloudflare

mojoio382MIT6.4.1TypeScript support: included

A TypeScript client for managing Cloudflare accounts, zones, DNS records, and workers with ease.

Cloudflare, DNS management, zone management, worker management, TypeScript, API client, cloud infrastructure, automated DNS, CDN management, open source

readme

@apiclient.xyz/cloudflare

An elegant, class-based TypeScript client for the Cloudflare API that makes managing your Cloudflare resources simple and type-safe.

npm version License: MIT

Features

  • Comprehensive coverage of the Cloudflare API including zones, DNS records, and Workers
  • Class-based design with intuitive methods for all Cloudflare operations
  • Strong TypeScript typing for excellent IDE autocompletion and type safety
  • Fully integrated with the official Cloudflare client using modern async iterators
  • Convenience methods for common operations to reduce boilerplate code
  • Promise-based API for easy async/await usage
  • ESM compatible for modern JavaScript projects
  • Comprehensive error handling for robust applications

Installation

# Using npm
npm install @apiclient.xyz/cloudflare

# Using yarn
yarn add @apiclient.xyz/cloudflare

# Using pnpm
pnpm add @apiclient.xyz/cloudflare

Quick Start

import * as cflare from '@apiclient.xyz/cloudflare';

// Initialize with your API token
const cfAccount = new cflare.CloudflareAccount('your-cloudflare-api-token');

// Use convenience methods for quick operations
await cfAccount.convenience.createRecord('subdomain.example.com', 'A', '192.0.2.1', 3600);

// Or work with the powerful class-based API
const zone = await cfAccount.zoneManager.getZoneByName('example.com');
await zone.purgeCache();

Usage Guide

Account Management

Initialize your Cloudflare account with your API token:

import * as cflare from '@apiclient.xyz/cloudflare';

const cfAccount = new cflare.CloudflareAccount('your-cloudflare-api-token');

// If you have multiple accounts, you can preselect one
await cfAccount.preselectAccountByName('My Company Account');

// List all accounts you have access to
const myAccounts = await cfAccount.listAccounts();

Zone Management

Zones represent your domains in Cloudflare.

// Get all zones in your account
const allZones = await cfAccount.convenience.listZones();

// Get a specific zone by domain name
const myZone = await cfAccount.zoneManager.getZoneByName('example.com');

// Get zone ID directly
const zoneId = await cfAccount.convenience.getZoneId('example.com');

// Create a new zone
const newZone = await cfAccount.zoneManager.createZone('newdomain.com');

// Purge cache for an entire zone
await cfAccount.convenience.purgeZone('example.com');
// Or using the zone object
await myZone.purgeCache();

// Purge specific URLs
await myZone.purgeUrls(['https://example.com/css/styles.css', 'https://example.com/js/app.js']);

// Enable/disable development mode
await myZone.enableDevelopmentMode(); // Enables dev mode for 3 hours
await myZone.disableDevelopmentMode();

// Check zone status
const isActive = await myZone.isActive();
const usingCfNameservers = await myZone.isUsingCloudflareNameservers();

DNS Record Management

Manage DNS records for your domains with ease.

// List all DNS records for a domain
const allRecords = await cfAccount.convenience.listRecords('example.com');

// Create a new DNS record
await cfAccount.convenience.createRecord('api.example.com', 'A', '192.0.2.1', 3600);

// Create a CNAME record
await cfAccount.convenience.createRecord('www.example.com', 'CNAME', 'example.com', 3600);

// Get a specific DNS record
const record = await cfAccount.convenience.getRecord('api.example.com', 'A');

// Update a DNS record (automatically creates it if it doesn't exist)
await cfAccount.convenience.updateRecord('api.example.com', 'A', '192.0.2.2', 3600);

// Remove a specific DNS record
await cfAccount.convenience.removeRecord('api.example.com', 'A');

// Clean (remove) all records of a specific type
await cfAccount.convenience.cleanRecord('example.com', 'TXT');

// Support for ACME DNS challenges (for certificate issuance)
await cfAccount.convenience.acmeSetDnsChallenge({
  hostName: '_acme-challenge.example.com',
  challenge: 'token-validation-string',
});
await cfAccount.convenience.acmeRemoveDnsChallenge({
  hostName: '_acme-challenge.example.com',
  challenge: 'token-validation-string',
});

Workers Management

Create and manage Cloudflare Workers with full TypeScript support.

// Create or update a worker
const workerScript = `
addEventListener('fetch', event => {
  event.respondWith(new Response('Hello from Cloudflare Workers!'))
})`;

const worker = await cfAccount.workerManager.createWorker('my-worker', workerScript);

// List all workers
const allWorkers = await cfAccount.workerManager.listWorkerScripts();

// Get an existing worker
const existingWorker = await cfAccount.workerManager.getWorker('my-worker');

// Set routes for a worker
await worker.setRoutes([
  {
    zoneName: 'example.com',
    pattern: 'https://api.example.com/*',
  },
  {
    zoneName: 'example.com',
    pattern: 'https://app.example.com/api/*',
  },
]);

// Get all routes for a worker
const routes = await worker.getRoutes();

// Update a worker's script
await worker.updateScript(`
addEventListener('fetch', event => {
  event.respondWith(new Response('Updated worker content!'))
})`);

// Delete a worker
await worker.delete();
// Or using the worker manager
await cfAccount.workerManager.deleteWorker('my-worker');

Complete Example

Here's a complete example showing how to manage multiple aspects of your Cloudflare account:

import * as cflare from '@apiclient.xyz/cloudflare';

async function manageCloudflare() {
  try {
    // Initialize with API token from environment variable
    const cfAccount = new cflare.CloudflareAccount(process.env.CLOUDFLARE_API_TOKEN);

    // Preselect account if needed
    await cfAccount.preselectAccountByName('My Company');

    // Get zone and check status
    const myZone = await cfAccount.zoneManager.getZoneByName('example.com');
    console.log(`Zone active: ${await myZone.isActive()}`);
    console.log(`Using CF nameservers: ${await myZone.isUsingCloudflareNameservers()}`);

    // Configure DNS
    await cfAccount.convenience.createRecord('api.example.com', 'A', '192.0.2.1');
    await cfAccount.convenience.createRecord('www.example.com', 'CNAME', 'example.com');

    // Create a worker and set up routes
    const workerCode = `
    addEventListener('fetch', event => {
      const url = new URL(event.request.url);

      if (url.pathname.startsWith('/api/')) {
        event.respondWith(new Response(JSON.stringify({ status: 'ok' }), {
          headers: { 'Content-Type': 'application/json' }
        }));
      } else {
        event.respondWith(fetch(event.request));
      }
    })`;

    const worker = await cfAccount.workerManager.createWorker('api-handler', workerCode);
    await worker.setRoutes([{ zoneName: 'example.com', pattern: 'https://api.example.com/*' }]);

    // Purge cache for specific URLs
    await myZone.purgeUrls(['https://example.com/css/styles.css']);

    console.log('Configuration completed successfully');
  } catch (error) {
    console.error('Error managing Cloudflare:', error);
  }
}

manageCloudflare();

API Documentation

CloudflareAccount

The main entry point for all Cloudflare operations.

class CloudflareAccount {
  constructor(apiToken: string);

  // Account management
  async listAccounts(): Promise<Array<ICloudflareTypes['Account']>>;
  async preselectAccountByName(accountName: string): Promise<void>;

  // Managers
  readonly zoneManager: ZoneManager;
  readonly workerManager: WorkerManager;

  // Official Cloudflare client
  readonly apiAccount: cloudflare.Cloudflare;

  // Convenience namespace with helper methods
  readonly convenience: {
    // Zone operations
    listZones(domainName?: string): Promise<CloudflareZone[]>;
    getZoneId(domainName: string): Promise<string>;
    purgeZone(domainName: string): Promise<void>;

    // DNS operations
    listRecords(domainName: string): Promise<CloudflareRecord[]>;
    getRecord(domainName: string, recordType: string): Promise<CloudflareRecord | undefined>;
    createRecord(
      domainName: string,
      recordType: string,
      content: string,
      ttl?: number,
    ): Promise<any>;
    updateRecord(
      domainName: string,
      recordType: string,
      content: string,
      ttl?: number,
    ): Promise<any>;
    removeRecord(domainName: string, recordType: string): Promise<any>;
    cleanRecord(domainName: string, recordType: string): Promise<void>;

    // ACME operations
    acmeSetDnsChallenge(dnsChallenge: IDnsChallenge): Promise<any>;
    acmeRemoveDnsChallenge(dnsChallenge: IDnsChallenge): Promise<any>;
  };
}

CloudflareZone

Represents a Cloudflare zone (domain).

class CloudflareZone {
  // Properties
  readonly id: string;
  readonly name: string;
  readonly status: string;
  readonly paused: boolean;
  readonly type: string;
  readonly nameServers: string[];

  // Methods
  async purgeCache(): Promise<any>;
  async purgeUrls(urls: string[]): Promise<any>;
  async isActive(): Promise<boolean>;
  async isUsingCloudflareNameservers(): Promise<boolean>;
  async isDevelopmentModeActive(): Promise<boolean>;
  async enableDevelopmentMode(): Promise<any>;
  async disableDevelopmentMode(): Promise<any>;
}

CloudflareRecord

Represents a DNS record.

class CloudflareRecord {
  // Properties
  readonly id: string;
  readonly type: string;
  readonly name: string;
  readonly content: string;
  readonly ttl: number;
  readonly proxied: boolean;

  // Methods
  async update(content: string, ttl?: number): Promise<any>;
  async delete(): Promise<any>;
}

CloudflareWorker

Represents a Cloudflare Worker.

class CloudflareWorker {
  // Properties
  readonly id: string;
  readonly script: string;
  readonly routes: IWorkerRoute[];

  // Methods
  async getRoutes(): Promise<IWorkerRoute[]>;
  async setRoutes(routes: Array<IWorkerRouteDefinition>): Promise<void>;
  async updateScript(scriptContent: string): Promise<CloudflareWorker>;
  async delete(): Promise<boolean>;
}

interface IWorkerRouteDefinition {
  zoneName: string;
  pattern: string;
}

Utility Functions

The library includes helpful utility functions:

// Validate a domain name
CloudflareUtils.isValidDomain('example.com'); // true

// Extract zone name from a domain
CloudflareUtils.getZoneName('subdomain.example.com'); // 'example.com'

// Validate a record type
CloudflareUtils.isValidRecordType('A'); // true

// Format URL for cache purging
CloudflareUtils.formatUrlForPurge('example.com/page'); // 'https://example.com/page'

// Format TTL value
CloudflareUtils.formatTtl(3600); // '1 hour'

What's New in 6.2.0

  • Improved async iterator support: Fully leverages the official Cloudflare client's async iterator pattern
  • Enhanced error handling: Better error detection and recovery
  • Simplified API: More consistent method signatures and return types
  • Better type safety: Improved TypeScript typing throughout the library
  • Detailed logging: More informative logging for easier debugging

Development & Testing

To build the project:

npm run build
# or
pnpm run build

To run tests:

npm test
# or
pnpm run test

License

MIT © Lossless GmbH