Cloudflare Node.js Bindings

repository·master·Indexed 43 days ago

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

A Promise-based Node.js client for the Cloudflare v4 API (version 2.9.1). It provides a programmatic 'BREAD' (Browse, Read, Edit, Add, and Delete) interface for managing resources such as DNS records, Argo Tunnels, Zones, and Workers KV namespaces. Supports authentication via API Keys and API Tokens, as well as HTTPS proxy configuration.

Tokens
8.4K
Snippets
36
Records
44
Agent score
79%

What's inside Cloudflare

  1. Use the Cloudflare API via the `cf` instance

    master

    All resources are accessed through the cf instance using the pattern: cf.{ RESOURCE_NAME }.{ METHOD_NAME }.

    Every method returns a Promise, allowing for standard .then() chaining or the use of async/await.

    // Using .then()
    cf.zones.read('ZONE_ID').then(function (resp) {
      return resp.result.status;
    });
    
    // Using async/await
    async function getZoneStatus(id) {
      var resp = await cf.zones.read(id);
      return resp.result.status;
    }
  2. Install and initialize the Cloudflare Node.js bindings

    master

    The Cloudflare Node.js bindings provide a Promise-based interface for the Cloudflare v4 API, supporting async/await and automatic Gzip/Deflate compression. It requires Node.js v4 or greater.

    Note: This repository is being archived in favor of cloudflare/cloudflare-typescript. For stability in production projects, consider pinning to 2.x releases as v3.x is a rewrite that may contain breaking changes before GA.

    var cf = require('cloudflare')({
      // configuration options
    });
  3. Configure the SDK using API Tokens (BETA)

    master

    To use API Tokens for authentication, provide your token in the configuration object. Tokens can be created in the Cloudflare dashboard under My Profile -> API Tokens.

    var cf = require('cloudflare')({
      token: 'your Cloudflare API token'
    });
  4. Configure the SDK using API Keys

    master

    To use API Keys for authentication, provide your account email address and your API key. You can find your API key in the Cloudflare dashboard under My Profile -> API Tokens.

    var cf = require('cloudflare')({
      email: 'you@example.com',
      key: 'your Cloudflare API key'
    });
  5. Perform basic DNS record operations

    master

    The DNSRecords resource includes several basic operations inherited from the Resource base class:

    • browse(zone_id): Lists all DNS records for a zone.
    • read(zone_id, id): Retrieves a specific DNS record by its ID.
    • add(zone_id, record): Creates a new DNS record for a zone.
    • del(zone_id, id): Deletes a specific DNS record by its ID.
  6. Initialize the Cloudflare client

    master

    To use the Cloudflare SDK, instantiate the Cloudflare class by passing an authentication object. The client supports both API Keys and API Tokens.

    Authentication Options

    When constructing the client, provide an auth object containing one of the following:

    • email: Your Cloudflare account email address (required when using key).
    • key: Your Cloudflare API key (used with email).
    • token: Your Cloudflare API token (preferred for scoped access).

    Proxy Configuration

    The client automatically detects and configures an HTTPS proxy if the following environment variables are set:

    • HTTPS_PROXY or https_proxy
    • NO_PROXY or no_proxy (to exclude specific hosts)

    If a proxy is configured, the client will use it to reach https://api.cloudflare.com.

    const Cloudflare = require('cloudflare');
    
    // Using an API Token (Recommended)
    const client = new Cloudflare({
      token: 'YOUR_API_TOKEN'
    });
    
    // Using an API Key
    const clientWithKey = new Cloudflare({
      email: 'user@example.com',
      key: 'YOUR_API_KEY'
    });
  7. Access Cloudflare resources via the Cloudflare client

    master

    The Cloudflare client instance provides access to various Cloudflare resources through properties. These resources are initialized with the internal client and allow you to interact with specific parts of the Cloudflare API.

    Available resource properties include:

    • argoTunnels
    • dnsRecords
    • enterpriseZoneWorkersScripts
    • enterpriseZoneWorkersRoutes
    • enterpriseZoneWorkersKVNamespaces
    • enterpriseZoneWorkersKV
    • ips
    • pageRules
    • zones
    • zoneSettings
    • zoneCustomHostNames
    • zoneWorkers
    • zoneWorkersScript
    • zoneWorkersRoutes
    • user
    • userTokens
    • stream
    const Cloudflare = require('cloudflare');
    const client = new Cloudflare({ token: 'YOUR_API_TOKEN' });
    
    // Example: Accessing DNS records
    // Note: Actual method calls depend on the resource implementation
    client.dnsRecords.list({ zone_id: '...' });
  8. Manage Enterprise Zone Workers KV namespaces

    master

    The EnterpriseZoneWorkersKV resource provides an interface for interacting with Cloudflare Workers KV namespaces within an Enterprise Zone. It allows for basic CRUD operations on keys, including single and bulk operations.

    Note: All methods require an account_id and a namespace_id as part of the resource path.

    // Example usage of EnterpriseZoneWorkersKV methods
    
    // List all keys in a namespace
    await enterpriseZoneWorkersKV.browse(accountId, namespaceId);
    
    // Add a single key-value pair
    await enterpriseZoneWorkersKV.add(accountId, namespaceId, 'my-key', 'my-value');
    
    // Read a value by key
    const value = await enterpriseZoneWorkersKV.read(accountId, namespaceId, 'my-key');
    
    // Delete a single key
    await enterpriseZoneWorkersKV.del(accountId, namespaceId, 'my-key');
    
    // Bulk add multiple key-value pairs
    await enterpriseZoneWorkersKV.addMulti(accountId, namespaceId, [{ key: 'k1', value: 'v1' }, { key: 'k2', value: 'v2' }]);
    
    // Bulk delete multiple keys
    await enterpriseZoneWorkersKV.delMulti(accountId, namespaceId, ['k1', 'k2']);
  9. Manage User Tokens with the UserTokens resource

    master

    The UserTokens resource provides an interface for managing Cloudflare User Tokens via the /user/tokens API endpoint. It allows you to list, create, retrieve, update, and delete tokens, as well as perform security operations like rolling or verifying secrets.

    Available methods include:

    • browse(): List user tokens.
    • read(id): Retrieve details for a specific user token by its id.
    • add(token): Create a new user token using a token configuration object.
    • del(id): Delete a user token by its id.
    • roll(id): Rotate the secret for a specific user token by its id.
    • verify(): Verify the current token secret.
    • browsePermissionGroups(): List all available permission groups for token creation.
    // Example usage (assuming a client instance is initialized)
    
    // List all tokens
    const tokens = await userTokens.browse();
    
    // Create a new token
    const newToken = await userTokens.add({ /* token configuration */ });
    
    // Roll a token's secret
    const rolledToken = await userTokens.roll('TOKEN_ID');
    
    // Verify the token secret
    const verification = await userTokens.verify();
    
    // Browse available permission groups
    const groups = await userTokens.browsePermissionGroups();
  10. Manage Enterprise Zone Workers Scripts

    master

    The EnterpriseZoneWorkersScripts resource provides an interface to manage Cloudflare Workers scripts within an Enterprise account. It allows you to retrieve, upload (edit), list (browse), and delete scripts via the accounts/:accountId/workers/scripts API endpoint.

    // Example usage pattern for EnterpriseZoneWorkersScripts
    // Note: This assumes an initialized instance of EnterpriseZoneWorkersScripts
    
    // Retrieve a script
    const script = await enterpriseZoneWorkersScripts.read(accountId, 'my-script-name');
    
    // Upload/Update a script
    const updatedScript = await enterpriseZoneWorkersScripts.edit(accountId, 'my-script-name', '/* script content */');
    
    // List all scripts
    const scriptsList = await enterpriseZoneWorkersScripts.browse(accountId);
    
    // Delete a script
    const deletedScript = await enterpriseZoneWorkersScripts.del(accountId, 'my-script-name');
  11. Manage Zone Workers Routes

    master

    The ZoneWorkersRoutes resource allows you to manage Workers routes for a specific Cloudflare zone. You can list, retrieve, create, update, or delete routes that trigger Workers based on specific patterns (like hostnames or paths) within a zone.

    Base path: zones/:zoneId/workers/routes

    // Note: This is a conceptual usage based on the resource definition
    // Actual instantiation depends on your client setup
    
    // List all routes in a zone
    const routes = await zoneWorkersRoutes.browse(zone_id);
    
    // Create a new route
    const newRoute = await zoneWorkersRoutes.add(zone_id, { pattern: 'example.com/*', zone_id: zone_id });
    
    // Update an existing route
    const updatedRoute = await zoneWorkersRoutes.edit(zone_id, route_id, { pattern: 'new-pattern.com/*' });
    
    // Get a specific route
    const route = await zoneWorkersRoutes.read(zone_id, route_id);
    
    // Delete a route
    await zoneWorkersRoutes.del(zone_id, route_id);
  12. Manage DNS records with DNSRecords

    master

    The DNSRecords resource provides an interface for managing DNS records within a specific Cloudflare zone. It maps to the /zones/:zoneID/dns_records API endpoint and supports standard CRUD operations along with specialized methods for exporting and editing records.

    // Note: Usage requires an initialized Cloudflare client instance
    // to access the DNSRecords resource.
    
    // Example: List all DNS records for a zone
    const records = await dnsRecords.browse('zone_id');
    
    // Example: Add a new DNS record
    const newRecord = await dnsRecords.add('zone_id', {
      type: 'A',
      name: 'example.com',
      content: '1.2.3.4'
    });