092a6ba55be3af5893d0cf923547e099c6d95011
				
			
			
		
	@apiclient.xyz/cloudflare
An elegant, class-based TypeScript client for the Cloudflare API that makes managing your Cloudflare resources simple and type-safe.
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
- Built on the official Cloudflare client but with a more developer-friendly interface
- Convenience methods for common operations to reduce boilerplate code
- Promise-based API for easy async/await usage
- ESM and browser compatible for maximum flexibility
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('example.com', 'challenge-token-here');
await cfAccount.convenience.acmeRemoveDnsChallenge('example.com');
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();
// Delete a worker
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
    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 selection
  async listAccounts(): Promise<any[]>;
  async preselectAccountByName(accountName: string): Promise<void>;
  
  // Managers
  readonly zoneManager: ZoneManager;
  readonly workerManager: WorkerManager;
  
  // Direct API access
  async request(endpoint: string, method?: string, data?: any): Promise<any>;
  
  // Convenience namespace with helper methods
  readonly convenience: {
    // Zone operations
    listZones(): 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>;
    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(domainName: string, token: string): Promise<any>;
    acmeRemoveDnsChallenge(domainName: string): 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 name: string;
  
  // Methods
  async getRoutes(): Promise<any[]>;
  async setRoutes(routes: Array<{ zoneName: string, pattern: string }>): Promise<any>;
}
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'
Development & Testing
To build the project:
npm run build
To run tests:
npm test
License
MIT © Lossless GmbH
Description
				An elegant, class-based TypeScript client for the Cloudflare API that makes managing your Cloudflare resources simple and type-safe.
						
						
						
					Languages
				
				
								
								
									TypeScript
								
								100%