Check out v4 of the Fauna CLI

v4 of the Fauna CLI is now in beta.

The new version introduces enhancements to the developer experience, including an improved authentication workflow. To get started, check out the CLI v4 quick start.

Cloudflare Worker integration

The Fauna integration for Cloudflare lets you connect and query a Fauna database from a Cloudflare Worker.

When set up, the integration automatically creates a Fauna authentication key. The integration stores the key’s secret in a Worker environment variable. You can use the environment variable with the Fauna JavaScript driver or other Fauna drivers to run queries from the Worker.

Set up the integration

To connect a Cloudflare worker to an existing Fauna database:

  1. Log in to the Cloudflare dashboard and select your account.

  2. In Account Home, select Workers & Pages.

  3. In the Workers tab, select your Worker.

  4. Select Integrations > Fauna.

  5. Follow the setup flow and select your Fauna database.

  6. In your Cloudflare Worker, install the Fauna JavaScript driver:

    npm install fauna

    The following TypeScript example shows how to run a Fauna query in a Cloudflare Worker. The credentials needed to connect to Fauna have been automatically added as secrets to your Worker through the integration:

    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 new Fauna client using the secret from the environment.
          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>;

Manage the integration

You can manage the Cloudflare Fauna integration from the Fauna Dashboard.

Manage authentication keys

To view authentication keys for an integrated Cloudflare Worker, select your database and click the Keys tab.

Keys for a Cloudflare Worker integration are prepended with _cloudflare_key_.

Key tab for a database in the Fauna Dashboard

You can delete the key to disable the integration.

Manage OAuth Apps

When you connect a Cloudflare Worker to your database, Fauna creates an OAuth client app in your Fauna account.

To view your account’s OAuth apps, go to Account > OAuth Apps in the Fauna Dashboard.

OAuth Apps in the Fauna Dashboard

You can delete the app to disable the integration.

Is this article helpful? 

Tell Fauna how the article can be improved:
Visit Fauna's forums or email docs@fauna.com

Thank you for your feedback!