[FREE] ⚡ Cloudflare Database Extension v2.0 - Blazing Fast D1 SQLite, Multi-Table, Advanced Query & Concurrency-Safe Updates!

Hello MIT App Inventor Builders! :waving_hand:

Tired of slow Google Sheets, complex Firebase rules, or expensive server limits? Today, I am thrilled to introduce Cloudflare Database Extension (v2.0) for App Inventor, Kodular, and Niotron!

This extension directly connects your mobile apps to Cloudflare D1 (Cloudflare's ultra-fast, serverless, globally distributed SQLite database) via high-performance Cloudflare Workers. Experience lightning-fast query execution, multi-table queries, column-level conditional updates/deletes, and concurrency-safe numeric increments with zero hassle!


:glowing_star: Key Features

  • :high_voltage: Blazing Fast Global Edge Performance: Powered by Cloudflare's global edge network for sub-millisecond response times worldwide.
  • :file_cabinet: Multi-Table Architecture: Manage multiple tables in a single D1 database. Fetch individual tables or all tables at once ("all").
  • :bullseye: Advanced Column-Based Operations: Update or Delete rows matching specific column values without needing row IDs (e.g., WHERE UserEmail = 'xyz').
  • :package: Multi-Column Bulk Updates: Update multiple columns simultaneously with a simple JSON object.
  • :plus: Atomic Increment / Decrement: Concurrency-safe numeric updates (perfect for wallet balances, coin systems, view counts, and scores).
  • :locked: Enterprise-Grade Security: Authenticated with Bearer API tokens and custom Cloudflare Worker endpoints.
  • :shield: Built-in Device Security Check: One-time silent background activation via your registered Email and Item ID.
  • :free_button: 100% Lifetime Free: Free for personal and commercial applications.

:bar_chart: Extension Specifications

  • :package: Package: com.abid.cloudflaredatabase
  • :gear: Version: 2.0
  • :floppy_disk: Size: 34.42 KB (Ultra-lightweight)
  • :mobile_phone: Minimum API Level: 14+ (Android 4.0+)
  • :test_tube: Companion Friendly: Yes (Auto-verified in live companion testing)

:puzzle_piece: Blocks Overview

AccessDenied

OnValueUpdated

OnError

OnDataUpdated

OnDataStored

OnDataFetched

OnDataDeleted

AccessGranted

StoreData

StartSecurityCheck

ForceRecheck

FetchData

DeleteData

IsAccessGranted

UserEmail

IsSessionVerified

ApiSecret

ApiUrl


:open_book: Detailed Blocks & Documentation

:gear: Properties (Designer & Blocks)

Property Type Description
ApiUrl Text The HTTPS endpoint URL of your deployed Cloudflare Worker.
ApiSecret Text The secret Bearer authorization token used to authenticate requests.

:rocket: CRUD & Database Methods

  • :inbox_tray: FetchData (tableName, id):
    Retrieves data from your D1 database. Pass "all" to fetch all tables at once, or provide a specific tableName. Set id to empty "" to retrieve all rows, or specify an ID for a single record.

    • Triggers: OnDataFetched(response, tableName)
  • :floppy_disk: StoreData (tableName, jsonData):
    Inserts a new row into the specified table using a JSON string.

    • Example: {"name":"Ali", "email":"ali@example.com", "balance": 100}
    • Triggers: OnDataStored(response, tableName)
  • :pencil: UpdateData (tableName, id, jsonData):
    Updates a record matching the primary ID with the provided JSON payload.

    • Triggers: OnDataUpdated(response, tableName)
  • :wastebasket: DeleteData (tableName, id):
    Deletes a record matching the primary ID.

    • Triggers: OnDataDeleted(response, tableName)

:bullseye: Advanced Column-Level Methods

  • :counterclockwise_arrows_button: UpdateByColumn (tableName, whereColumn, whereValue, updateColumn, updateValue):
    Updates a specific column where another column matches a value.

    • Example: Set PaymentStatus = "Paid" where TransactionID = "TXN-98765".
    • Triggers: OnDataUpdated(response, tableName)
  • :memo: UpdateMultipleByColumn (tableName, whereColumn, whereValue, jsonUpdates):
    Updates multiple columns at once using any unique column value.

    • Example: Where UserEmail = "``ali@gmail.com``", update Name, Phone, and City by passing {"Name":"Abid Ali", "Phone":"03449490070", "City":"Lahore"}.
    • Triggers: OnDataUpdated(response, tableName)
  • :cross_mark: DeleteByColumn (tableName, whereColumn, whereValue):
    Deletes rows where a target column matches a value.

    • Example: Delete from table Cart where UserEmail = "``user@test.com``".
    • Triggers: OnDataDeleted(response, tableName)
  • :plus: UpdateDataValue (tableName, uniqueColumn, uniqueValue, updateColumn, amount):
    Atomically increments or decrements a numeric value in Cloudflare D1 without race conditions. Pass positive numbers (+10) to add, or negative (-5) to subtract.

    • Example: Add 50 coins to Wallet where UserID = "U123".
    • Triggers: OnValueUpdated(response, tableName)

:shield: Security & Free Activation Blocks

Method / Property Return Type Description
StartSecurityCheck (email, itemId) None Silently validates activation in background. Call in Screen.Initialize.
ForceRecheck (email, itemId) None Clears cache and re-validates credentials with the server.
ResetSecurityData () None Resets local device verification cache (for developer testing).
UserEmail () Text Returns the currently verified email address.
ItemID () Text Returns the registered Item ID.
IsVerified () Boolean Returns true if device has completed verification.
IsAccessGranted () Boolean Returns true if activation was approved.
IsSessionVerified () Boolean Returns true if active session is verified.

:bell: Events

  • OnDataFetched (response, tableName): Returns fetched data array / JSON.
  • OnDataStored (response, tableName): Triggered after insertion completes.
  • OnDataUpdated (response, tableName): Triggered after standard or column updates.
  • OnDataDeleted (response, tableName): Triggered after row deletion.
  • OnValueUpdated (response, tableName): Triggered when a numeric value is incremented or decremented.
  • OnError (errorMsg): Fires when an error occurs during API execution.
  • AccessGranted (): Fires when free registration verification succeeds. Safely load your app data here!
  • AccessDenied (email, itemId): Fires if verification fails or unverified credentials are used.

:hammer_and_wrench: Complete Step-by-Step Setup Guide

Step 1: Get Backend Script & Free Activation

  1. Visit our official store: :backhand_index_pointing_right: AIX Hub Store - Cloudflare Database
  2. Click the orange button: Download ZIP (.zip) to download the complete Cloudflare Worker JavaScript file (worker.js).
  3. Enter your email in the registration box and click Save to activate your free lifetime Item ID.

Step 2: Setup Cloudflare D1 Database & Worker

  1. Log in to your free account at dash.cloudflare.com.

  2. Go to Workers & Pages > D1 SQL Database > Click Create Database (give it a name, e.g. mydb).

  3. Go to Workers & Pages > Click Create Application > Create Worker > Click Deploy.

  4. Click Quick Edit and paste the code from the downloaded worker.js file.

  5. In your Worker's Settings > Bindings, click Add Binding > select D1 Database, set the Variable name to DB, and link your database.

  6. Set your custom secret password inside the script:

    const API_SECRET = "YourSecurePasswordA3224gS";
    
  7. Click Save and Deploy. Your Worker endpoint (e.g. https://your-worker.workers.dev) is your ApiUrl, and the password you chose is your ApiSecret!

Step 3: Use in App Inventor

  1. Drop CloudflareDatabase onto your screen.

  2. In Properties, set your ApiUrl and ApiSecret.

  3. In Screen1.Initialize, call StartSecurityCheck with your registered email and Item ID (Cloudflare Database).

  4. In AccessGranted, call FetchData("users", "") or start inserting/updating records!


:inbox_tray: Download & Free Activation

This extension and the backend script are 100% FREE for everyone:

  1. Download Extension (.aix):

    com.abid.cloudflaredatabase.aix (35.7 KB)

  2. Download Backend Script (.zip) & Free Lifetime Registration:
    :backhand_index_pointing_right: Visit AIX Hub Store to Download ZIP & Register
    (Click 'Download ZIP (.zip)' for the worker script, and click 'Save' to activate your email).

  3. Example Project (.aia): Coming soon


:light_bulb: Support & Feedback

If you encounter any bugs, have questions, or need assistance, feel free to reply to this thread!

:star: If this extension powers up your apps, don't forget to Like (:heart:) this thread! Happy Coding! :rocket:

How do you sign up to Cloudflare Database to get account/worker/script/ApiUrl/APISecret ?

Hi @JEWEL and @TIMAI2,

Thank you for the guidance and questions!

  1. App Inventor Block Images:
    I have updated the first post with the official App Inventor block screenshots generated via FAST-CLI.

  2. Cloudflare Worker Script & Setup:
    The complete backend script (worker.js) is packaged inside the downloadable ZIP (.zip) on our store:
    :backhand_index_pointing_right: AIX Hub Store - Cloudflare Database
    (Users can simply click the orange "Download ZIP (.zip)" button to get the script and register their email for free activation).

  3. Cloudflare D1 & Worker Setup:

    • Log in to dash.cloudflare.com.
    • Create a free D1 Database under Workers & Pages > D1 SQL Database.
    • Create a Worker, paste the provided worker.js, and bind the D1 database to variable DB.
    • Set your own password in const API_SECRET = "YourPassword"; and Deploy.
    • Your Worker URL is your ApiUrl, and the password you set is your ApiSecret.

I have also updated the complete step-by-step setup guide in the main post. Thanks again for your support! :rocket:

How about a little transparency? Use of Cloudflare Database is NOT FREE . There is a 15 day ‘free trial’ and then a monthly cost of over 25$ or higher per MONTH.

This may be a ‘free’ extension but FREE is a misnomer and you should provide a link to the actual use costs of this tool please.

Also, an explanation of how to use the Security Check blocks, using the email and itemId, after "registration" for free and paid apps, including the AccessGranted blocks, along with what it is actually doing and what data it is sending your backend, would be helpful for any potential users.

Can this registration system be used for AppInventor users on the code2 server, which is anonymous, and does not require an email address to connect?

Hi @SteveJG,

Thank you for your comment. I completely agree that transparency is vital for our community, which is why I want to clarify the Cloudflare D1 pricing model with official documentation.

There appears to be a major misconception in your comment: Cloudflare D1 is NOT a paid product, nor does it have a 15-day trial.

Cloudflare D1 operates on Cloudflare's Generous Free Forever Tier, with no credit card required to get started and deploy live databases. Here are the exact official limits provided by Cloudflare on their Free Plan:

  • :bar_chart: Rows Read: 5,000,000 (5 Million) rows / day — FREE
  • :memo: Rows Written: 100,000 rows / day — FREE
  • :floppy_disk: Database Storage: 5 GB total database storage — FREE
  • :high_voltage: Cloudflare Workers: 100,000 requests / day — FREE

For 99% of indie developers, student projects, and App Inventor apps with thousands of daily active users, this free quota is more than enough to run production mobile apps without ever spending a single dollar.

The $25 plan you mentioned refers to the optional Cloudflare Pro/Business plans (which are for enterprise web security and CDN features, not required for D1 databases).

You can review Cloudflare's official D1 pricing page directly here:
:backhand_index_pointing_right: Official Cloudflare D1 Pricing Docs: Pricing · Cloudflare D1 docs

I have also updated the main post with this official pricing link to maintain 100% transparency for everyone. Thank you for pointing this out! :+1:

Hi @TIMAI2,

Thank you for bringing up these essential technical and privacy questions. Let me explain the Security Check system, its data handling, and its compatibility in full detail:


1. What does the Security Check do & what data is sent?

We hold user privacy and data security to the highest standard:

  • Data Transmitted: The security check connects to our validation server over encrypted HTTPS and sends ONLY two values:
    1. The email string passed into the block.
    2. The itemId string (identifying the extension, e.g. Cloudflare Database).
  • Zero Sensitive Data: We DO NOT collect, transmit, or access any device identifiers, IMEI, IP addresses, location data, phone numbers, or user contacts.
  • Offline Local Caching: Once an email + Item ID combination is verified successfully on the device, the result is saved locally in Android's private SharedPreferences. Subsequent app launches read the verified state directly from local device storage — it does not spam network requests on every app open.

2. Can it be used on anonymous servers like code2.appinventor.mit.edu?

Yes, 100%!
The email passed into the email block is independent of the App Inventor account or server:

  • A developer working anonymously on code2 simply registers any email address they own on our official registration website.
  • They plug that same email into the StartSecurityCheck block.
  • The extension validates that email against the store database without needing any connection to their App Inventor login credentials.

3. Frictionless Live Testing (AI2 Companion):

To make development as smooth as possible, the extension contains an automatic check for the MIT App Inventor Companion (isCompanion()). During live testing inside the Companion, the security check is automatically bypassed, allowing developers to build and test their apps immediately without waiting for verification.


4. How to use the Blocks:

  • In Screen1.Initialize, call:
    CloudflareDatabase.StartSecurityCheck(email: "user@example.com", itemId: "Cloudflare Database")
  • In when CloudflareDatabase.AccessGranted:
    Place your database initialization and queries here (e.g. FetchData, StoreData).
  • In when CloudflareDatabase.AccessDenied:
    Use this to notify the developer/user if an unregistered email is used.

I have updated the first post with these detailed explanations and block screenshots to help all prospective users. Thank you for your valuable feedback! :handshake:

5. Following issues with the security check system:

We have officially updated the .aix file right here on this platform. Furthermore, the security system issue has been completely permanently fixed for ALL our extensions available on our website. :hammer_and_wrench:

I also want to quickly clarify how our extension's security mechanism works so you can be confident in using it:

  • :high_voltage: Lightning Fast: The verification process is incredibly quick, taking barely 1 second (or less than 2 seconds) to verify the credentials.
  • :rocket: Zero Performance Impact: It has absolutely no negative impact on your app's speed or performance.
  • :locked: Strictly a One-Time Check: The best part is that the security gate triggers ONLY ONCE. Once a user is successfully verified upon opening the app, the extension will never check the security again as long as the app remains installed on that device.

Please go ahead and download the updated extension. Thank you all so much for your patience, understanding, and for helping us improve! :folded_hands:

Happy coding! :sparkles:

6. Complete Step-by-Step Setup Guide to set up Cloudflare

Step 1: Create your D1 SQL Database

  1. In the Cloudflare dashboard left sidebar, navigate to Storage & Databases > D1 SQL Database.
  2. Click the blue Create database button.
  3. Name your database (e.g., my_app_db), keep location as Automatic, and click Create.


Step 2: Create your Tables in the D1 Console

  1. Click on your newly created database (my_app_db).
  2. Go to the Console tab.
  3. Paste your table creation SQL and click Execute:
CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    email TEXT UNIQUE NOT NULL,
    score INTEGER DEFAULT 0
);

(You can customize columns and tables according to your app's needs).


Step 3: Create the Worker Application

  1. In the left sidebar, navigate to Compute > Workers & Pages.
  2. In the top right corner, click the blue button: "Create application" (or click "Start with Hello World" in the center).
  3. (This replaces the old "Create a Worker" button in the previous Cloudflare layout).


Step 4: Name your Worker and Deploy

  1. Keep the Workers tab selected.
  2. Enter a name for your worker (e.g. my-db-worker).
  3. Click the blue Deploy button to initialize the Worker.


Step 5: Edit Code & Paste worker.js

  1. On your Worker overview page, click the "Edit code" button in the top right.
  2. Select and delete the default sample code.
  3. Paste the complete worker.js script provided below.
  4. Set your custom secret API password at the top:
const API_SECRET = "YourCustomPassword123";
  1. Click "Save and Deploy" (or Deploy).


Step 6: Bind the D1 Database to your Worker

  1. Return to your Worker page and click the Settings tab.
  2. In the left settings menu, click Bindings.
  3. Click Add binding > select D1 database.
  4. Configure the two fields:
  • Variable name: DB (:warning: Critical: Must be exactly uppercase DB, as referenced in the script).
  • D1 database: Select your database (my_app_db) from the dropdown.
  1. Click Save and deploy.


Step 7: Connect to App Inventor

  1. Copy your Worker URL from your Worker Overview page:
    2.(e.g., https://my-db-worker.<your-subdomain>.workers.dev)*
  2. In App Inventor Designer, select the CloudflareDatabase component:
  • ApiUrl: Paste your Worker URL
  • ApiSecret: Enter the same password you set in worker.js (e.g., YourCustomPassword123)
  1. In Blocks:
  • When Screen1.Initialize -> Call StartSecurityCheck with your registered email and Item ID (Cloudflare Database).
  • When AccessGranted -> Call FetchData("users", "") or StoreData!


:scroll: Complete Backend Script (worker.js)

/**
 * Cloudflare Worker for App Inventor / Kodular D1 Database Extension
 * Package: com.abid.cloudflaredatabase
 */

export default {
  async fetch(request, env) {
    // 1. SET YOUR SECRET API PASSWORD HERE
    const API_SECRET = "YourCustomPassword123";

    const url = new URL(request.url);
    const method = request.method;

    const headers = {
      "Content-Type": "application/json",
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
      "Access-Control-Allow-Headers": "Content-Type, Authorization"
    };

    if (method === "OPTIONS") return new Response(null, { headers });

    try {
      if (!env.DB) {
        return new Response(JSON.stringify({ 
          status: "error", 
          error: "D1 Database binding missing! In Worker Settings > Bindings, add D1 Database with Variable name: DB" 
        }), { status: 500, headers });
      }

      const authHeader = request.headers.get("Authorization");
      if (authHeader !== `Bearer ${API_SECRET}`) {
        return new Response(JSON.stringify({ status: "error", error: "Unauthorized! Invalid ApiSecret." }), { status: 401, headers });
      }

      let tableName = url.searchParams.get("table");
      const whereCol = url.searchParams.get("col");
      const whereVal = url.searchParams.get("val");
      const whereCol2 = url.searchParams.get("col2");
      const whereVal2 = url.searchParams.get("val2");
      const id = url.searchParams.get("id");
      const action = url.searchParams.get("action");

      if (!tableName) {
        return new Response(JSON.stringify({ status: "error", error: "Table name required (?table=tableName)" }), { status: 400, headers });
      }

      tableName = tableName.trim();
      if (!/^[a-zA-Z0-9_]+$/.test(tableName)) {
        return new Response(JSON.stringify({ status: "error", error: "Invalid table name." }), { status: 400, headers });
      }

      let bodyData = {};
      if (method === "POST" || method === "PUT") {
        try {
          const bodyText = await request.clone().text();
          if (bodyText && bodyText.trim().length > 0) {
            if (bodyText.trim().startsWith("{") || bodyText.trim().startsWith("[")) {
              bodyData = JSON.parse(bodyText);
            } else {
              const params = new URLSearchParams(bodyText);
              for (const [key, value] of params.entries()) {
                bodyData[key.trim()] = value.trim();
              }
            }
          }
        } catch (e) {
          return new Response(JSON.stringify({ status: "error", error: "Invalid JSON body" }), { status: 400, headers });
        }
      }

      // GET (Fetch Data)
      if (method === "GET") {
        if (id) {
          const query = `SELECT * FROM "${tableName}" WHERE "id" = ?`;
          const results = await env.DB.prepare(query).bind(id).raw();
          return new Response(JSON.stringify(results), { headers });
        }
        if (whereCol && whereVal && whereCol2 && whereVal2) {
          const query = `SELECT * FROM "${tableName}" WHERE "${whereCol}" = ? AND "${whereCol2}" = ?`;
          const results = await env.DB.prepare(query).bind(whereVal, whereVal2).raw();
          return new Response(JSON.stringify(results), { headers });
        }
        if (whereCol && whereVal) {
          const query = `SELECT * FROM "${tableName}" WHERE "${whereCol}" = ?`;
          const results = await env.DB.prepare(query).bind(whereVal).raw();
          return new Response(JSON.stringify(results), { headers });
        }
        const query = `SELECT * FROM "${tableName}"`;
        const results = await env.DB.prepare(query).raw();
        return new Response(JSON.stringify(results), { headers });
      }

      // POST (Store Data or Update Columns)
      if (method === "POST") {
        if (whereCol && whereVal) {
          const updateKeys = Object.keys(bodyData);
          if (updateKeys.length === 0) return new Response(JSON.stringify({ status: "error", error: "No update data provided" }), { status: 400, headers });

          const setClauses = updateKeys.map(k => `"${k}" = ?`).join(", ");
          const updateValues = updateKeys.map(k => bodyData[k]);

          let sqlQuery, bindValues;
          if (whereCol2 && whereVal2) {
            sqlQuery = `UPDATE "${tableName}" SET ${setClauses} WHERE "${whereCol}" = ? AND "${whereCol2}" = ? RETURNING *`;
            bindValues = [...updateValues, whereVal, whereVal2];
          } else {
            sqlQuery = `UPDATE "${tableName}" SET ${setClauses} WHERE "${whereCol}" = ? RETURNING *`;
            bindValues = [...updateValues, whereVal];
          }

          const updateResult = await env.DB.prepare(sqlQuery).bind(...bindValues).all();
          let responseData = { status: "success", message: `Updated successfully in ${tableName}` };
          if (updateResult.results && updateResult.results.length > 0) {
            Object.assign(responseData, updateResult.results[0]);
          }
          return new Response(JSON.stringify(responseData), { headers });
        }

        const keys = Object.keys(bodyData);
        const values = Object.values(bodyData);
        if (keys.length === 0) return new Response(JSON.stringify({ status: "error", error: "No data provided" }), { status: 400, headers });

        const safeKeys = keys.map(k => `"${k}"`).join(", ");
        const placeholders = keys.map(() => "?").join(", ");
        const sqlQuery = `INSERT INTO "${tableName}" (${safeKeys}) VALUES (${placeholders}) RETURNING *`;
        const insertedRow = await env.DB.prepare(sqlQuery).bind(...values).raw();

        return new Response(JSON.stringify({ status: "success", message: `Data saved in ${tableName}`, data: insertedRow }), { headers });
      }

      // PUT (Update Full Record & Atomic Increment)
      if (method === "PUT") {
        if (action === "increment" && whereCol && whereVal) {
          const updateColumn = bodyData.column;
          const amount = Number(bodyData.amount);
          const sqlQuery = `UPDATE "${tableName}" SET "${updateColumn}" = COALESCE("${updateColumn}", 0) + ? WHERE "${whereCol}" = ? RETURNING *`;
          const result = await env.DB.prepare(sqlQuery).bind(amount, whereVal).all();
          return new Response(JSON.stringify({ status: "success", message: `Updated ${updateColumn}`, data: result.results || [] }), { headers });
        }

        if (!id) return new Response(JSON.stringify({ status: "error", error: "ID parameter required" }), { status: 400, headers });

        let updates = [], values = [];
        for (const [key, value] of Object.entries(bodyData)) {
          updates.push(`"${key}" = ?`);
          values.push(value);
        }
        const sqlQuery = `UPDATE "${tableName}" SET ${updates.join(", ")} WHERE "id" = ? RETURNING *`;
        values.push(id);
        const result = await env.DB.prepare(sqlQuery).bind(...values).all();
        return new Response(JSON.stringify({ status: "success", message: "Data updated", data: result.results || [] }), { headers });
      }

      // DELETE
      if (method === "DELETE") {
        if (whereCol && whereVal) {
          const sqlQuery = `DELETE FROM "${tableName}" WHERE "${whereCol}" = ?`;
          await env.DB.prepare(sqlQuery).bind(whereVal).run();
          return new Response(JSON.stringify({ status: "success", message: "Row deleted" }), { headers });
        }
        if (id) {
          const sqlQuery = `DELETE FROM "${tableName}" WHERE "id" = ?`;
          await env.DB.prepare(sqlQuery).bind(id).run();
          return new Response(JSON.stringify({ status: "success", message: "Deleted by ID" }), { headers });
        }
        return new Response(JSON.stringify({ status: "error", error: "ID or col/val required" }), { status: 400, headers });
      }

      return new Response(JSON.stringify({ error: "Method not allowed" }), { status: 405, headers });
    } catch (e) {
      return new Response(JSON.stringify({ status: "error", error: e.message }), { status: 500, headers });
    }
  }
};

I hope this visual walkthrough clarifies everything! When posting your screenshots or files, you can drag and drop each image right where indicated above. Please let me know if you have any questions!

1 Like

Awesome :heart::+1:t2:

1 Like