Lightweight universal Cloudflare API client library for Node.js, Browser, and CF Workers

Overview

Cloudflare API Client

NPM Version NPM Downloads TypeScript Donate Discord

Lightweight universal HTTP client for Cloudflare API based on Fetch API that works in Node.js, browser, and CF Workers environment. Optimized for a good developer experience and minimal code with zero dependencies supporting tree-shaking.

Getting Started

# Install using NPM
$ npm install cloudflare-client --save

# Install using Yarn
$ yarn add cloudflare-client

Once the library is installed, you can cherry pick and configure individual Cloudflare API endpoints that you need. If you bundle your code (e.g. with Rollup), only the selected modules will be included into the application bundle.

import * as Cloudflare from "cloudflare-client";

// EXAMPLE 1:
//   Initialize an HTTP client for managing Cloudflare DNS
//   records using API token for authentication
const dnsRecords = Cloudflare.dnsRecords({
  zoneId: "<CLOUDFLARE_ZONE_ID>",
  accessToken: "<CLOUDFLARE_API_TOKEN>",
});

// EXAMPLE 2:
//   Initialize an HTTP client for managing Cloudflare Workers
//   KV store using API key and email for authentication
const kv = Cloudflare.kv({
  accountId: "<CLOUDFLARE_ZONE_ID>",
  authKey: "<CLOUDFLARE_AUTH_KEY>",
  authEmail: "<CLOUDFLARE_AUTH_EMAIL>",
});

User

// Initialize an HTTP client for the `user` API endpoint
// using an API token for authentication
const user = Cloudflare.user({ accessToken: "xxx" });

// Fetch the currently logged in / authenticated user details
// https://api.cloudflare.com/#user-user-details
const userDetails = await user.get();
// => {
//   id: "7c5dae5552338874e5053f2534d2767a",
//   email: "[email protected]",
//   ...
// }

User Tokens

// Initialize an HTTP client for the `userTokens` API endpoint
// using an API token for authentication
const userTokens = Cloudflare.userTokens({ accessToken: "xxx" });

// Verify the user's token
// https://api.cloudflare.com/#user-api-tokens-verify-token
const token = await userTokens.verify();
// => {
//   id: "ed17574386854bf78a67040be0a770b0",
//   status: "active"
// }
// Initialize an HTTP client for the `userTokens` API endpoint
// using an auth key and email
const userTokens = Cloudflare.userTokens({ authKey: "xxx", authEmail: "xxx" });

// Get token details
// https://api.cloudflare.com/#user-api-tokens-token-details
const token = await userTokens.get("ed17574386854bf78a67040be0a770b0");
// => {
//   id: "ed17574386854bf78a67040be0a770b0",
//   name: "My Token",
//   status: "active",
//   policies: [...],
//   ...
// }

DNS Records

// Initialize an HTTP client for managing DNS records
// within the target zone using API token for authentication
const dnsRecords = Cloudflare.dnsRecords({ zoneId: "xxx", accessToken: "xxx" });
// Find all DNS records of type "A"
const records = await dnsRecords.find({ type: "A" }).all();

// Find the first DNS record with the specified name
const record = await dnsRecords.find({ type: "A", name: "test" }).first();
// => {
//  id: "372e67954025e0ba6aaa6d586b9e0b59",
//  type: "A",
//  name: "test.example.com",
//  content: "192.0.2.1",
//  ...
// }
// Fetch the list of DNS records and iterate through the result set using `for await`
const records = await dnsRecords.find({ type: "A" });

for await (const record of records) {
  console.log(record);
}
// Get a specific DNS record by its ID
// https://api.cloudflare.com/#dns-records-for-a-zone-dns-record-details
const record = await dnsRecords.get("372e67954025e0ba6aaa6d586b9e0b59");

// Create a new DNS record
// https://api.cloudflare.com/#dns-records-for-a-zone-create-dns-record
const record = await dnsRecords.create({
  type: "A",
  name: "test.example.com",
  content: "192.0.2.1",
  proxied: true,
});

// Replace DNS record
// https://api.cloudflare.com/#dns-records-for-a-zone-update-dns-record
const record = await dnsRecords.replace("372e67954025e0ba6aaa6d586b9e0b59", {
  type: "A",
  name: "test.example.com",
  content: "192.0.2.1",
  proxied: true,
});

// Update DNS record
// https://api.cloudflare.com/#dns-records-for-a-zone-patch-dns-record
const record = await dnsRecords.update("372e67954025e0ba6aaa6d586b9e0b59", {
  proxied: false,
});

// Delete DNS record
// https://api.cloudflare.com/#dns-records-for-a-zone-delete-dns-record
await dnsRecords.delete("372e67954025e0ba6aaa6d586b9e0b59");

Workers KV

// Initialize an HTTP client for managing CF Workers KV store
const kv = Cloudflare.kv({
  accountId: "xxx",
  authKey: "xxx",
  authEmail: "xxx",
});

KV Namespaces

// Fetch the list of all KV namespaces
// https://api.cloudflare.com/#workers-kv-namespace-list-namespaces
const namespaces = await kv.find().all();

// Create a new namespace named "Example"
// https://api.cloudflare.com/#workers-kv-namespace-create-a-namespace
const ns = await kv.create("Example");
// => {
//   id: "0f2ac74b498b48028cb68387c421e279",
//   title: "Example",
//   supports_url_encoding: true
// }

// Update/rename a namespace
// https://api.cloudflare.com/#workers-kv-namespace-rename-a-namespace
await kv.update("0f2ac74b498b48028cb68387c421e279", "New Name");

// Delete a namespace
// https://api.cloudflare.com/#workers-kv-namespace-remove-a-namespace
await kv.delete("0f2ac74b498b48028cb68387c421e279");

Key-Value Pairs

// Initialize the API endpoint client for managing key-value pairs
const ns = kv.namespace("0f2ac74b498b48028cb68387c421e279");

// Fetch the list of all the keys
const keys = await ns.keys().all();

// Fetch the list of all the keys prefixed "example"
const keys = await ns.keys({ prefix: "example" }).all();

// Create or update a key-value pair in Cloudflare KV store
// using JSON encoding by default (`JSON.stringify(value)`).
await ns.set("key", { some: "value" });

// Read key-pair value from Cloudflare KV store
const value = await ns.get("key");
// => {
//  some: "name"
// }

// Delete a key-pair
await ns.delete("key");
// Save a key-value pair as plain text (as opposed to JSON-serialized)
await ns.set("όνομα", "José", { encode: false });

// Read a key-value pair as plain text
const value = await ns.get("όνομα", { decode: false });
// => "José"

Source Code

For more information and usage examples check out the source code / tests:

Backers 💰

              

Related Projects

How to Contribute

You're very welcome to create a PR or send me a message on Discord.

$ git clone https://github.com/kriasoft/cloudflare-client.git
$ cd ./cloudflare-client
$ yarn install
$ yarn test

NOTE: In order to run unit tests locally you will need Node.js v16.15 or newer and Cloudflare API token.

License

Copyright © 2022-present Kriasoft. This source code is licensed under the MIT license found in the LICENSE file.


Made with by Konstantin Tarkus (@koistya, blog) and contributors.

You might also like...

A Cloudflare Workers service that fetches and renders Notion pages as HTML, Markdown, or JSON.

notion-fetch A Cloudflare Workers service that fetches and renders Notion pages as HTML, Markdown, or JSON. Powered by Durable Objects and R2. Usage P

Jan 6, 2023

A flexible gateway for running ML inference jobs through cloud providers or your own GPU. Powered by Replicate and Cloudflare Workers.

Cogflare (Working title) Cogflare is a Cloudflare Workers application that aims to simplify running distributed ML inference jobs through a central AP

Dec 12, 2022

A URL shortener that runs on Cloudflare Workers

ITP Works A URL shortener that runs on Cloudflare Workers. It stores the rules in Cloudflare KV storage and sends a 301 redirect when a matched pathna

Mar 4, 2022

Starting template for building a Remix site with CloudFlare Workers (ES Modules Syntax)

Starting template for building a Remix site with CloudFlare Workers (ES Modules Syntax)

May 20, 2022

Remix + Cloudflare Workers + DO + Turborepo

Remix + Cloudflare Workers + DO + Turborepo A starter to get you up and going with Remix on Cloudflare with all the latest and greatest. What's inside

Dec 12, 2022

Remix + Cloudflare Workers + Wrangler2 + Tailwind + ESLint + Prettier + Vitest + Playwright

Welcome to Remix! Remix Docs Development You will be running two processes during development: The Miniflare server (miniflare is a local environment

Dec 19, 2022

Server-side rendering blog runs on Cloudflare workers

Serverside rendered blog I have tried something completely against to current web trends. What are these? I am using the React as backend framework wi

Jun 24, 2022

A collection of useful tools for building web apps on Cloudflare Workers.

Keywork is a batteries-included, magic-free, library for building web apps on Cloudflare Workers. Features 💪 Written in TypeScript 📚 Modules Support

Dec 22, 2022

A starter template for Remix + Cloudflare Workers + DO + KV + Turborepo

Remix + Cloudflare Workers starter with Turborepo 🚀 Starter to get going with Remix and Cloudflare Workers. This template is based on the starter cre

Jan 2, 2023
Releases(v0.3.2)
  • v0.3.2(Jul 2, 2022)

    Allow to manage custom hostnames (a.k.a. Cloudflare for SaaS)

    import * as Cloudflare from "cloudflare-client";
    
    // Initialize an HTTP client for interacting with Cloudflare API
    const hostnames = Cloudflare.customHostnames({
      zoneId: env.CLOUDFLARE_ZONE_ID,
      accessToken: env.CLOUDFLARE_API_TOKEN,
    });
    
    // Create a new custom hostname
    const hostname = await hostnames.create({ hostname: "app.koistya.com" });
    // => { id: "xxx", hostname: "xxx", ownership_verification: ..., ... }
    
    // Update hostname
    await hostnames.update(hostname.id, { ssl: { ... } });
    
    // Delete hostname
    await hostnames.delete(hostname.id);
    
    // Find hostnames
    const records = await hostnames.find({ ... }).all();
    
    Source code(tar.gz)
    Source code(zip)
  • v0.3.0(Jun 25, 2022)

    Getting Started

    import * as Cloudflare from "cloudflare-client";
    
    // EXAMPLE 1:
    //   Initialize an HTTP client for managing Cloudflare DNS
    //   records using API token for authentication
    const dnsRecords = Cloudflare.dnsRecords({
      zoneId: "<CLOUDFLARE_ZONE_ID>",
      accessToken: "<CLOUDFLARE_API_TOKEN>",
    });
    
    // EXAMPLE 2:
    //   Initialize an HTTP client for managing Cloudflare Workers
    //   KV store using API key and email for authentication
    const kv = Cloudflare.kv({
      accountId: "<CLOUDFLARE_ZONE_ID>",
      authKey: "<CLOUDFLARE_AUTH_KEY>",
      authEmail: "<CLOUDFLARE_AUTH_EMAIL>",
    });
    

    User

    // Initialize an HTTP client for the `user` API endpoint
    // using an API token for authentication
    const user = Cloudflare.user({ accessToken: "xxx" });
    
    // Fetch the currently logged in / authenticated user details
    // https://api.cloudflare.com/#user-user-details
    const userDetails = await user.get();
    // => {
    //   id: "7c5dae5552338874e5053f2534d2767a",
    //   email: "[email protected]",
    //   ...
    // }
    

    User Tokens

    // Initialize an HTTP client for the `userTokens` API endpoint
    // using an API token for authentication
    const userTokens = Cloudflare.userTokens({ accessToken: "xxx" });
    
    // Verify the user's token
    // https://api.cloudflare.com/#user-api-tokens-verify-token
    const token = await userTokens.verify();
    // => {
    //   id: "ed17574386854bf78a67040be0a770b0",
    //   status: "active"
    // }
    
    // Initialize an HTTP client for the `userTokens` API endpoint
    // using an auth key and email
    const userTokens = Cloudflare.userTokens({ authKey: "xxx", authEmail: "xxx" });
    
    // Get token details
    // https://api.cloudflare.com/#user-api-tokens-token-details
    const token = await userTokens.get("ed17574386854bf78a67040be0a770b0");
    // => {
    //   id: "ed17574386854bf78a67040be0a770b0",
    //   name: "My Token",
    //   status: "active",
    //   policies: [...],
    //   ...
    // }
    

    DNS Records

    // Initialize an HTTP client for managing DNS records
    // within the target zone using API token for authentication
    const dnsRecords = Cloudflare.dnsRecords({ zoneId: "xxx", accessToken: "xxx" });
    
    // Find all DNS records of type "A"
    const records = await dnsRecords.find({ type: "A" }).all();
    
    // Find the first DNS record with the specified name
    const record = await dnsRecords.find({ type: "A", name: "test" }).first();
    // => {
    //  id: "372e67954025e0ba6aaa6d586b9e0b59",
    //  type: "A",
    //  name: "test.example.com",
    //  content: "192.0.2.1",
    //  ...
    // }
    
    // Fetch the list of DNS records and iterate through the result set using `for await`
    const records = await dnsRecords.find({ type: "A" });
    
    for await (const record of records) {
      console.log(record);
    }
    
    // Get a specific DNS record by its ID
    // https://api.cloudflare.com/#dns-records-for-a-zone-dns-record-details
    const record = await dnsRecords.get("372e67954025e0ba6aaa6d586b9e0b59");
    
    // Create a new DNS record
    // https://api.cloudflare.com/#dns-records-for-a-zone-create-dns-record
    const record = await dnsRecords.create({
      type: "A",
      name: "test.example.com",
      content: "192.0.2.1",
      proxied: true,
    });
    
    // Replace DNS record
    // https://api.cloudflare.com/#dns-records-for-a-zone-update-dns-record
    const record = await dnsRecords.replace("372e67954025e0ba6aaa6d586b9e0b59", {
      type: "A",
      name: "test.example.com",
      content: "192.0.2.1",
      proxied: true,
    });
    
    // Update DNS record
    // https://api.cloudflare.com/#dns-records-for-a-zone-patch-dns-record
    const record = await dnsRecords.update("372e67954025e0ba6aaa6d586b9e0b59", {
      proxied: false,
    });
    
    // Delete DNS record
    // https://api.cloudflare.com/#dns-records-for-a-zone-delete-dns-record
    await dnsRecords.delete("372e67954025e0ba6aaa6d586b9e0b59");
    

    Workers KV

    // Initialize an HTTP client for managing CF Workers KV store
    const kv = Cloudflare.kv({
      accountId: "xxx",
      authKey: "xxx",
      authEmail: "xxx",
    });
    

    KV Namespaces

    // Fetch the list of all KV namespaces
    // https://api.cloudflare.com/#workers-kv-namespace-list-namespaces
    const namespaces = await kv.find().all();
    
    // Create a new namespace named "Example"
    // https://api.cloudflare.com/#workers-kv-namespace-create-a-namespace
    const ns = await kv.create("Example");
    // => {
    //   id: "0f2ac74b498b48028cb68387c421e279",
    //   title: "Example",
    //   supports_url_encoding: true
    // }
    
    // Update/rename a namespace
    // https://api.cloudflare.com/#workers-kv-namespace-rename-a-namespace
    await kv.update("0f2ac74b498b48028cb68387c421e279", "New Name");
    
    // Delete a namespace
    // https://api.cloudflare.com/#workers-kv-namespace-remove-a-namespace
    await kv.delete("0f2ac74b498b48028cb68387c421e279");
    

    Key-Value Pairs

    // Initialize the API endpoint client for managing key-value pairs
    const ns = kv.namespace("0f2ac74b498b48028cb68387c421e279");
    
    // Fetch the list of all the keys
    const keys = await ns.keys().all();
    
    // Fetch the list of all the keys prefixed "example"
    const keys = await ns.keys({ prefix: "example" }).all();
    
    // Create or update a key-value pair in Cloudflare KV store
    // using JSON encoding by default (`JSON.stringify(value)`).
    await ns.set("key", { some: "value" });
    
    // Read key-pair value from Cloudflare KV store
    const value = await ns.get("key");
    // => {
    //  some: "name"
    // }
    
    // Delete a key-pair
    await ns.delete("key");
    
    // Save a key-value pair as plain text (as opposed to JSON-serialized)
    await ns.set("όνομα", "José", { encode: false });
    
    // Read a key-value pair as plain text
    const value = await ns.get("όνομα", { decode: false });
    // => "José"
    
    Source code(tar.gz)
    Source code(zip)
  • v0.2.0(Jun 22, 2022)

    An HTTP client for Cloudflare API that works in Node.js, browser, and CF Workers environment.

    # Install using NPM
    $ npm install cloudflare-client --save
    
    # Install using Yarn
    $ yarn add cloudflare-client
    

    Usage Example

    import * as cf from "cloudflare-client";
    
    const settings = { zoneId: "xxx", accessToken: "<CLOUDFLARE_API_TOKEN>" };
    
    // Get the currently logged in / authenticated user
    // https://api.cloudflare.com/#user-user-details
    await cf.user(settings).get();
    
    // Verify the user's token
    // https://api.cloudflare.com/#user-api-tokens-verify-token
    await cf.userTokens(settings).verify();
    
    // Find a single DNS Record matching the search parameters
    // https://api.cloudflare.com/#dns-records-for-a-zone-list-dns-records
    await cf.dnsRecords(settings).find({ type: "A" });
    
    // Get the list of DNS Records for the target zone
    // https://api.cloudflare.com/#dns-records-for-a-zone-list-dns-records
    await cf.dnsRecords(settings).findMany({ type: "A" });
    
    // Get DNS Record details
    // https://api.cloudflare.com/#dns-records-for-a-zone-dns-record-details
    await cf.dnsRecords(settings).get("xxx");
    
    // Create DNS record
    // https://api.cloudflare.com/#dns-records-for-a-zone-create-dns-record
    await cf.dnsRecords(settings).create({ type: "A", content: "127.0.0.1", ... });
    
    // Update DNS record
    // https://api.cloudflare.com/#dns-records-for-a-zone-update-dns-record
    await cf.dnsRecords(settings).update({ id: "xxx", content: "127.0.0.1", ... });
    
    // Patch DNS record
    // https://api.cloudflare.com/#dns-records-for-a-zone-patch-dns-record
    await cf.dnsRecords(settings).patch({ id: "xxx", content: "127.0.0.1", ... });
    
    // Delete DNS record
    // https://api.cloudflare.com/#dns-records-for-a-zone-delete-dns-record
    await cf.dnsRecords(settings).delete(id);
    
    Source code(tar.gz)
    Source code(zip)
Owner
Kriasoft
Here on GitHub we share our experience with web infrastructure, scalable web application design, and DevOps.
Kriasoft
Google-Drive-Directory-Index | Combining the power of Cloudflare Workers and Google Drive API will allow you to index your Google Drive files on the browser.

?? Google-Drive-Directory-Index Combining the power of Cloudflare Workers and Google Drive will allow you to index your Google Drive files on the brow

Aicirou 127 Jan 2, 2023
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
A zero-dependency, strongly-typed web framework for Bun, Node and Cloudflare workers

nbit A simple, declarative, type-safe way to build web services and REST APIs for Bun, Node and Cloudflare Workers. Examples See some quick examples b

Simon Sturmer 16 Sep 16, 2022
基于 gh-proxy + Jsdelivr+ cnpmjs + cloudflare workers 的 GitHub Serverless API 工具。

better-github-api Better, Eazy, Access Anywhere 介绍 基于 gh-proxy + Jsdelivr + cnpmjs + cloudflare workers 的 GitHub Serverless API 工具。 cdn.js:仅含 gh-proxy

One Studio 11 Nov 23, 2022
Dead-simple CORS handling for any itty-router API (test with Cloudflare Workers, but works anywhere)!

Simple CORS-handling for any itty-router API. Designed on Cloudflare Workers, but works anywhere. Features Tiny. Currently ~600 bytes, with zero-depen

Kevin R. Whitley 6 Dec 16, 2022
Firebase/Admin Auth Javascript Library for Cloudflare Workers

Flarebase Auth Firebase/Admin Auth Javascript Library for Cloudflare Workers Supported operations: createSessionCookie() verifySessionCookie() signInW

Marco Cimolai 38 Jan 1, 2023
Abusing Cloudflare Workers to establish persistence and exfiltrate sensitive data at the edge.

Abusing Cloudflare Workers This repository contains companion code for the blog post MITM at the Edge: Abusing Cloudflare Workers. malicious-worker/ c

Christophe Tafani-Dereeper 10 Sep 16, 2022