Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updates suggestions #185

Closed
wants to merge 29 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions 040-SDK/020-Python/010-overview.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,9 @@ The format of the database URL (`db_url`) parameter must follow the format of: `
There are multiple options to pass your Xata credentials to the client. Xata will check the following using this order of precedence:

1. Parameters passed to the constructor
1. Environment variables
1. The `.env` file
1. Via `.xatarc` configuration file
2. Environment variables
3. The `.env` file
4. Via `.xatarc` configuration file

The `.xatarc` file is generated by the [Xata CLI](/docs/getting-started/installation#install-the-xata-cli) in the current directory when running the command `xata init`.

Expand Down
168 changes: 168 additions & 0 deletions 070-Integrations/024-cloudflare-workers.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
---
title: Cloudflare Workers with Xata
navTitle: Cloudflare Workers
keywords: ['cloudflare', 'integration']
description: Use Cloudflare Workers with Xata to improve performance
slug: integrations/cloudflare
published: true
---

[Cloudflare](https://www.cloudflare.com/en-gb/) is a content delivery and security service that optimizes website performance and mitigates security risks for sites. [Cloudflare Workers](https://workers.cloudflare.com/) enable you to run code directly on Cloudflare's network to reduce latency and improve performance, and can be used for tasks like customizing web content, handling API requests, and modifying web traffic, for faster response times.

The completed [Cloudflare and Xata code](https://github.com/xataio/examples/tree/main/apps/getting-started-cloudflare-workers) is available in the [Xata `examples` repo](https://github.com/xataio/examples) on GitHub.

You can integrate Xata with Cloudflare using the following methods:

- Using the Cloudflare dashboard (UI method): This approach involves using the Cloudflare dashboard for configuration.
- Using the Wrangler (CLI method): Alternatively, you can use Cloudflare's CLI tool, [Wrangler](https://developers.cloudflare.com/workers/wrangler/), for a command-line based integration.

## Integrate using Cloudflare dashboard

Integrate a Cloudflare Worker with an existing Xata database by using the dashboard, with th e folowing:

1. Navigate to the [Cloudflare dashboard](https://dash.cloudflare.com/).
2. Click **Workers & Pages** > **Overview**
3. Choose a Worker from your Cloudflare account to integrate with.
4. Click **Integrations**.
5. Select the Xata card and click **Add Integration**. You're redirected to the "Add Xata to Worker" flow.

![One click Xata Cloudflare integration](images/cloudflare-integration-env.png)

6. Follow the flow to grant permissions, authorize Cloudflare, and configure your secrets. Choose a Xata workspace to connect with, and select the desired database and branch.
7. Click _Add Integration_.

The secrets are added to the environment variables of the Worker. Your endpoint response should be available remotely at `<YOUR_WORKER>.<YOUR_SUBDOMAIN>.workers.dev`

## Integrate using the CLI

The following covers setting up a "Hello World" sample Cloudflare app and integrating it with Xata, using the Xata client and Wrangler.

### Before you begin

- Ensure you [install the Xata CLI and authenticate](https://xata.io/docs/getting-started/installation)

### Create a new Cloudflare app

Choose the "Hello World" Worker example and accept the default prompt options.

```sh
npm create cloudflare@latest getting-started-cloudflare-workers
```

After the command has completed, navigate to the `getting-started-cloudflare-workers` directory, and run the application locally:

```sh
cd getting-started-cloudflare-workers
npm run wrangler dev
```

By default, the application runs on `http://localhost:8787`, where "Hello World" is displayed in your browser.

### Deploy your app remotely

```sh
npx wrangler deploy
```

Preview your Worker at `<YOUR_WORKER>.<YOUR_SUBDOMAIN>.workers.dev.`, where "Hello World" is displayed in the browser.

### Install the Xata client

Run the following command in the root directory of your project:

```sh
xata init
```

Accept the default settings during the configuration process. After completion, a `.env` file will be generated in your app's folder. This file includes the necessary credentials for your Cloudflare Worker to access your database. Add the following credentials to your `.env` file:

```bash title=".env"
XATA_API_KEY=<YOUR_API_KEY_HERE>
XATA_BRANCH=main
```

- Replace `<YOUR_API_KEY_HERE>` with your generated API key, accessible from the _Account Settings_ page in the Xata UI.
- Specify your preferred branch in the `XATA_BRANCH` variable.

### Initialize the Xata client

There are two methods for initializing the Xata client in Cloudflare Workers:

- ES modules syntax (recommended): This is the current, recommended method for apps that are being developed or maintained actively.
- Service workers syntax (deprecated): This older method is still available but not recommended for new projects.

#### ES modules syntax (recommended)

```ts title="src/index.ts"
import { XataClient } from './xata';

export interface Env {
XATA_BRANCH: string;
XATA_API_KEY: string;
}

export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const xata = new XataClient({
apiKey: env.XATA_API_KEY,
branch: env.XATA_BRANCH
});
// Note that the table name "Posts" may vary
// depending on the shape of your schema
const posts = await xata.db.Posts.getAll();
return new Response(`Total Posts: ${posts.length}`);
}
};
```

#### Service workers syntax (deprecated)

```ts title="src/index.ts"
import { XataClient } from './xata';

async function handler(request: Request) {
const xata = new XataClient({
apiKey: XATA_API_KEY,
branch: XATA_BRANCH
});
// Note that the table name "Posts" may vary
// depending on the shape of your schema
const posts = await xata.db.Posts.getAll();
return new Response(`Total Posts: ${posts.length}`);
}

// Initialize Worker
addEventListener('fetch', (event) => {
event.respondWith(handler(event.request));
});
```

## Environment variables

Environment variables keep API keys and sensitive data safe, allowing you to easily manage and change app settings.

### Add local environment variables

Create a file named `.dev.vars` in your project's root directory and add your Xata environment values. This file enables Cloudflare to access these values when running in development mode.

```bash title=".dev.vars"
XATA_API_KEY=<YOUR_API_KEY_HERE>
XATA_BRANCH=main
```

- Replace `<YOUR_API_KEY_HERE>` with your generated API key, accessible from the _Account Settings_ page in the Xata UI.
- Specify your preferred branch in the `XATA_BRANCH` variable.

### Setting remote environment variables

To make the environment variables accessible in your Worker when it is deployed remotely, you have two options:

- It's recommended, you use the one-click guided workflow available in the Cloudflare dashboard. This automatically sets the environment variables necessary to interact with your database from a remote Cloudflare worker. Your endpoint response should be available remotely at `<YOUR_WORKER>.<YOUR_SUBDOMAIN>.workers.dev`
- Alternatively, you can set the variables manually via the Cloudflare dashboard. Follow [Cloudflare's docs](https://developers.cloudflare.com/workers/configuration/environment-variables/#add-environment-variables-via-the-dashboard) for manually adding environment variables via the dashboard.

![Adding environment variables manually](images/cloudflare-manual-env.png)

## Related resources

- [Cloudflare Workers](https://developers.cloudflare.com/workers/)
- [Cloudflare Workers environment variables](https://developers.cloudflare.com/workers/configuration/environment-variables/)
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.