Cloudflare Workers with Xata
Cloudflare is a content delivery network that optimizes website performance and mitigates security risks for sites. Cloudflare Workers 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, or modifying web traffic.
A complete Cloudflare and Xata starter is available in the Xata examples
repo on GitHub.
-
Ensure you install the Xata CLI and authenticate
-
Ensure you have a basic project with Cloudflare workers running
Run the following command in the root directory of your project:
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. It should look like this:
XATA_API_KEY=<YOUR_API_KEY_HERE>
XATA_BRANCH=<YOUR_BRANCH_HERE>
A file called .xatarc
should also be generated at the project root, with the following contents:
{
"databaseURL": "<YOUR_DATABASE_URL_HERE>",
"codegen": {
"output": "src/xata.ts"
}
}
Warning: You'll need to move these vars into a file called
.dev.vars
at your project root for local development. This file enables Cloudflare to access these values when running in development mode. For more information, see Cloudflare's documentation.
You should end up with a .dev.vars
file that looks like this at your project root:
XATA_API_KEY=<YOUR_API_KEY_HERE>
XATA_BRANCH=<YOUR_BRANCH_HERE>
XATA_DATABASE_URL=<YOUR_DATABASE_URL_HERE>
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.
import { XataClient } from './xata';
export interface Env {
XATA_BRANCH: string;
XATA_API_KEY: string;
XATA_DATABASE_URL: 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,
databaseURL: env.XATA_DATABASE_URL
});
// 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}`);
}
};
import { XataClient } from './xata';
async function handler(request: Request) {
const xata = new XataClient({
apiKey: XATA_API_KEY,
branch: XATA_BRANCH,
databaseURL: XATA_DATABASE_URL
});
// 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 keep API keys and sensitive data safe, allowing you to easily manage and change app settings.
To add environment variables to a remotely deployed Worker, you have two options:
- Use the one-click guided workflow provided in the Cloudflare dashboard (recommended).
- Alternatively, you can set the variables manually via the Cloudflare dashboard.
To integrate a Cloudflare Worker with an existing Xata database, follow these steps in the Cloudflare dashboard:
- Navigate to the Cloudflare dashboard.
- Click Workers & Pages > Overview
- Choose a Worker from your Cloudflare account to integrate with.
- Click Integrations.
- Select the Xata card and click Add Integration. You're redirected to the "Add Xata to Worker" flow.
- 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.
- 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
.
Follow Cloudflare's docs for manually adding environment variables via the dashboard.