Cloudflare Workers quick start

Use Fauna’s JavaScript driver to query e-commerce demo data using a Cloudflare Worker. The Worker uses TypeScript. You’ll set up the Worker using the Cloudflare Wrangler CLI and the Fauna Cloudflare integration.

 

  1. Create a database with demo data

    Log in to the Fauna Dashboard, and create a database with the following configuration:

    • Region group: Choose your preferred region group, which determines where your data resides.

    • Use demo data: Enabled.

    • Enable backups: Disabled.

    Leave the other options as is.

    Create demo database

  2. Create and deploy a Cloudflare Worker

    In your terminal:

    • Install the Wrangler CLI.

    • Create a Cloudflare Worker named my-fauna-worker.

    • Install the Fauna JavaScript driver.

    • Deploy the Cloudflare Worker.

    npm install -g wrangler@latest
    npm create cloudflare my-fauna-worker -- \
      --category hello-world \
      --type hello-world \
      --lang ts \
      --git false \
      --deploy true
    cd my-fauna-worker
    npm install fauna
  3. Set up the Fauna integration

    1. In your browser, log in to the Cloudflare dashboard and select your account.

    2. In Account Home, select Workers & Pages.

    3. In the Workers tab, select the my-fauna-worker Worker.

    4. Select Integrations > Fauna.

    5. If prompted, log in to Fauna and authorize the integration.

    6. Follow the integration setup flow and select:

      • Your Fauna database

      • The server-readonly database role

      • FAUNA_SECRET as the Secret Name.

    7. Click Finish.

    Fauna Cloudflare integration

  4. Edit the Worker’s code

    In your local my-fauna-worker directory, edit the src/index.ts file and replace the code with the following:

    import { Client, fql, FaunaError, ServiceError } from "fauna";
    
    // This interface defines the structure of the environment
    // variables that get passed in.
    export interface Env {
      FAUNA_SECRET: string;
    }
    
    export default {
      async fetch(request, env, ctx): Promise<Response> {
        // 1. Initialize a Fauna client using the FAUNA_SECRET env var.
        const client = new Client({ secret: env.FAUNA_SECRET });
    
        // Extract the email from the query string. Otherwise, use an
        // email address that's in the Fauna sample data.
        const url = new URL(request.url);
        const email =
          url.searchParams.get("email")
            || "alice.appleseed@example.com";
    
        try {
          // 2. Execute an FQL query to retrieve data from Fauna.
          //    In this example, it queries 'Customer.byEmail(...)' for
          //    a particular user. 'first()' ensures only the first
          //    matching result is returned as email has a unique
          //    constraint on it in this collection.
          const getData = await client.query(
            fql`Customer.byEmail(${email}).first()`
          );
    
          // 3. Return the retrieved data as a JSON response.
          return new Response(
            JSON.stringify(getData),
            { status: 200 }
          );
        } catch (error) {
          // 4. Handle Fauna-specific errors separately from
          //    other errors.
          if (error instanceof FaunaError) {
            // If it's a service error (e.g., a problem with the
            // query or the Fauna service itself), log the Fauna
            // queryInfo summary to the console for debugging.
            if (error instanceof ServiceError) {
              console.error(error.queryInfo?.summary);
            } else {
              // Otherwise, return a generic error response for
              // Fauna errors.
              return new Response(
                "Error " + error,
                { status: 500 }
              );
            }
          }
          // 5. For any other error, return a less specific
          //    message to prevent leaking internal error
          //    details to the caller.
          return new Response(
            "An error occurred, " +
            error.message, {
            status: 500,
          });
        }
      },
    } satisfies ExportedHandler<Env>;
  5. Re-deploy and test the Worker

    In your local my-fauna-worker directory, use the Wrangler CLI to re-deploy the app. Then use curl to make a GET HTTP request to the URL from the deployment output.

    The Worker returns a query response containing sample e-commerce customer from the Fauna demo data.

    curl -X GET $(wrangler deploy | grep -o 'https://[^ ]*') | jq .
    {
      "data": {
        "coll": {
          "name": "Customer"
        },
        "id": "111",
        "ts": {
          "isoString": "2099-01-08T19:30:22.700Z"
        },
        "cart": {
          "coll": {
            "name": "Order"
          },
          "id": "419541310615060553"
        },
        "orders": {
          "after": "hdW..."
        },
        "name": "Alice Appleseed",
        "email": "alice.appleseed@example.com",
        "address": {
          "street": "87856 Mendota Court",
          "city": "Washington",
          "state": "DC",
          "postalCode": "20220",
          "country": "US"
        }
      },
      ...
    }
\