new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Cloudflare Workers · all subjects

bindings

223 notes in this subject, read out of this brain and free to use. This is page 1 of 4.

Connect Workers to Neon using Hyperdrive

You can connect Workers to Neon using Hyperdrive (recommended) or using the Neon serverless driver @neondatabase/serverless. Both provide connection pooling and reduce the amount of round trips required to create a secure connection from Workers to your database.

Neon serverless driver example with Workers

The following example shows how to use the @neondatabase/serverless driver to query a Neon database from a Worker. The database connection string should be stored as a secret and passed via env.DATABASE_URL: import { Client } from "@neondatabase/serverless"; export default { async fetch(request, env, ctx) { const client = new Client(env.DATABASE_URL); await client.connect(); const { rows } = await client.query("SELECT * FROM elements"); return new Response(JSON.stringify(rows)); }, };

Neon serverless PostgreSQL overview

Neon is a fully managed serverless PostgreSQL database. It separates storage and compute to offer modern developer features such as serverless, branching, and bottomless storage.

Hyperdrive provides lowest latencies for Neon connections

Hyperdrive can provide the lowest possible latencies because it performs the database connection setup and connection pooling across Cloudflare's network. Hyperdrive supports native database drivers, libraries, and ORMs, and is included in all Workers plans.

Supabase client query example in Workers

This example shows how to query a Supabase database from a Worker: import { createClient } from '@supabase/supabase-js'; export default { async fetch(request, env) { const supabase = createClient(env.SUPABASE_URL, env.SUPABASE_KEY); const { data, error } = await supabase.from('countries').select('*'); if (error) throw error; return new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json', }, }); }, };

Hyperdrive for Supabase database access

Hyperdrive enables direct connection to the underlying Postgres database in Supabase, providing the lowest latency for database queries accessed server-side from Workers. Hyperdrive supports native database drivers, libraries, and ORMs, and is included in all Workers plans.

Supabase integration options for Workers

Cloudflare Workers can connect to Supabase in two ways: using the Supabase client (@supabase/supabase-js) for full Supabase features, or using Hyperdrive for direct PostgreSQL database access. Hyperdrive provides lower latencies through connection pooling across Cloudflare's network and is included in all Workers plans.

Supabase client setup in Workers

To use the Supabase client with Workers: install @supabase/supabase-js, add your Supabase URL and anon key as secrets using 'npx wrangler secret put SUPABASE_URL' and 'npx wrangler secret put SUPABASE_KEY' (found in Supabase Dashboard under Settings > API), then import createClient from @supabase/supabase-js and instantiate with env.SUPABASE_URL and env.SUPABASE_KEY.

Upstash QStash setup with Cloudflare Workers

To connect Cloudflare Workers to Upstash QStash: (1) Configure the publicly available HTTP endpoint that will receive messages. (2) Add Upstash QStash token as a secret using Wrangler: 'npx wrangler secret put QSTASH_TOKEN'. (3) Install the @upstash/qstash package. (4) Use the QStash client to send messages to your configured endpoint.

Upstash Redis credentials in Wrangler

Upstash Redis credentials are configured as secrets with default names UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN. The Redis.fromEnv(env) method automatically picks up these default secret names. If secrets are renamed, they must be declared explicitly when instantiating the Redis client.

Upstash QStash token configuration

Upstash QStash token is added as a secret with the default name QSTASH_TOKEN. The token is obtained from the Upstash Console under QStash settings and added using Wrangler: 'npx wrangler secret put QSTASH_TOKEN'.

Upstash Redis setup with Cloudflare Workers

To connect Cloudflare Workers to Upstash Redis: (1) Create an Upstash database or load existing data to Upstash. (2) Insert test data using the Upstash console CLI or local redis-cli. (3) Add Upstash Redis URL and token as secrets using Wrangler: 'npx wrangler secret put UPSTASH_REDIS_REST_URL' and 'npx wrangler secret put UPSTASH_REDIS_REST_TOKEN'. (4) Install the @upstash/redis package. (5) Use Redis.fromEnv(env) to instantiate the client in your Worker.

Upstash Redis example in Worker

The following example shows how to query Upstash Redis in a Cloudflare Worker: import { Redis } from "@upstash/redis/cloudflare"; export default { async fetch(request, env) { const redis = Redis.fromEnv(env); const country = request.headers.get("cf-ipcountry"); if (country) { const greeting = await redis.get(country); if (greeting) { return new Response(greeting); } } return new Response("Hello What's up!"); }, };

Xata features

Xata provides instant copy-on-write database branches, zero-downtime schema changes, data anonymization, AI-powered performance monitoring, and BYOC (Bring Your Own Cloud) capabilities.

Hyperdrive benefits for Xata connections

Hyperdrive provides lower latencies by performing database connection setup and connection pooling across Cloudflare's network. Hyperdrive supports native database drivers, libraries, and ORMs, and is included in all Workers plans.

Xata PostgreSQL integration with Hyperdrive

Xata is a PostgreSQL database platform that can be connected to Cloudflare Workers using Hyperdrive. Hyperdrive provides connection pooling and reduces round trips required to create a secure connection from Workers to Xata databases.

Vectorize overview

Vectorize is a globally distributed vector database that enables you to build full-stack, AI-powered applications with Cloudflare Workers.

Turso database URL and token should be defined in Env interface

In your Worker code, define the Env interface to include TURSO_URL and TURSO_AUTH_TOKEN as optional string properties. These environment variables and secrets are set when you configure the Turso integration.

Install @libsql/client npm package for Turso

Install the Turso client library using 'npm install @libsql/client' to enable your Worker to connect to and query Turso databases.

Connect to Turso database and execute SQL queries

Connect to a Turso database using 'turso db shell <DATABASE_NAME>' to open an interactive shell where you can execute SQL queries directly.

Get Turso database URL and create authentication token

Retrieve your database URL with 'turso db show <DATABASE_NAME> --url' and create an authentication token with 'turso db tokens create <DATABASE_NAME>'.

Add Turso credentials as Worker secrets with Wrangler

Add Turso database credentials to your Worker using Wrangler: 'npx wrangler secret put TURSO_URL' and 'npx wrangler secret put TURSO_AUTH_TOKEN'. When prompted, paste your database URL and authentication token respectively.

Authenticate Turso CLI with GitHub account

Before creating a Turso database, authenticate with your GitHub account by running 'turso auth login'. This is required before you can create and manage databases.

Install Turso CLI with homebrew or scripted installation

To install Turso CLI, use either 'brew install tursodatabase/tap/turso' on macOS and Linux with homebrew, or 'curl -sSfL https://get.tur.so/install.sh | bash' for manual scripted installation. Verify installation with 'turso --version'.

Turso is an edge-hosted distributed SQLite database

Turso is an edge-hosted, distributed database based on libSQL, an open-source fork of SQLite. It was designed to minimize query latency for applications where queries come from anywhere in the world.

Turso Worker example with libSQL client

This example shows how to connect to a Turso database and execute a SELECT query in a Cloudflare Worker using the libSQL client library: ```ts import { Client as LibsqlClient, createClient } from "@libsql/client/web"; export interface Env { TURSO_URL?: string; TURSO_AUTH_TOKEN?: string; } export default { async fetch(request, env, ctx): Promise<Response> { const client = buildLibsqlClient(env); try { const res = await client.execute("SELECT * FROM elements"); return new Response(JSON.stringify(res), { status: 200, headers: { "Content-Type": "application/json" }, }); } catch (error) { console.error("Error executing SQL query:", error); return new Response( JSON.stringify({ error: "Internal Server Error" }), { status: 500, }, ); } }, } satisfies ExportedHandler<Env>; function buildLibsqlClient(env: Env): LibsqlClient { const url = env.TURSO_URL?.trim(); if (url === undefined) { throw new Error("TURSO_URL env var is not defined"); } const authToken = env.TURSO_AUTH_TOKEN?.trim(); if (authToken == undefined) { throw new Error("TURSO_AUTH_TOKEN env var is not defined"); } return createClient({ url, authToken }); } ``` The example demonstrates querying a Turso database, handling errors, and returning results as JSON.

Analytics Engine writes are non-blocking

Analytics Engine writes do not block and do not impact request latency. There is no need to await or use waitUntil() when writing data points.

Analytics Engine binding configuration

Add an Analytics Engine dataset binding to wrangler.json using the 'analytics_engine_datasets' array. Each binding object requires a 'binding' property (the name exposed to the Worker) and a 'dataset' property (the dataset name). The dataset is created automatically when you first write to it.

Analytics Engine writeDataPoint method

The writeDataPoint method accepts an object with three properties: 'blobs' (array of strings for dimensions like paths, regions, status codes, or customer IDs), 'doubles' (array of numbers for counts, durations, or sizes), and 'indexes' (array of strings used as the sampling key for grouping related events). All three properties are typically used together.

Analytics Engine use cases

Workers Analytics Engine is designed for tracking custom metrics, building usage-based billing, and understanding service health on a per-customer basis. Unlike logs, it is optimized for aggregated queries over high-cardinality data.

Analytics Engine write data points example

Example showing how to write page view and response timing events to Analytics Engine: ```ts interface Env { ANALYTICS: AnalyticsEngineDataset; } export default { async fetch(request: Request, env: Env): Promise<Response> { const url = new URL(request.url); // Write a page view event env.ANALYTICS.writeDataPoint({ blobs: [ url.pathname, request.headers.get("cf-connecting-country") ?? "unknown", ], doubles: [1], // Count indexes: [url.hostname], // Sampling key }); // Write a response timing event const start = Date.now(); const response = await fetch(request); const duration = Date.now() - start; env.ANALYTICS.writeDataPoint({ blobs: [url.pathname, response.status.toString()], doubles: [duration], indexes: [url.hostname], }); // Writes are non-blocking - no need to await or use waitUntil() return response; }, }; ```

Access OPENAI_API_KEY from environment bindings

Pass the OpenAI API key to the SDK from environment bindings. In Workers, access it via env.OPENAI_API_KEY. Create a new OpenAI client by passing {apiKey: env.OPENAI_API_KEY} to the OpenAI constructor.

Astro bindings integration with Cloudflare platform

With bindings enabled in Astro with on-demand rendering, your application can integrate with the Cloudflare Developer Platform for access to compute, storage, AI and more. Bindings are accessible in your Astro locals via the Cloudflare runtime.

Analog bindings support for Cloudflare products

Analog applications can be fully integrated with the Cloudflare Developer Platform using product bindings in both local development and production. Bindings are configured and accessed in Analog API routes through Nitro's Cloudflare provider as documented in the Nitro documentation.

Bindings support for Docusaurus

Bindings can be used with Docusaurus projects to connect to other Cloudflare services, enabling you to store and retrieve data within your Docusaurus application.

Access bindings in Hono apps

Bindings in Hono apps can be accessed using the Hono bindings API. Bindings are configured in wrangler.jsonc and can be added to access Cloudflare resources like KV, D1, R2, Queues, and Durable Objects. See the Hono documentation for specific implementation details.

Nuxt bindings integration

Nuxt applications can be fully integrated with the Cloudflare Developer Platform using product bindings in both local development and production. Bindings are accessed in Nuxt event handlers, with configuration details available in the Nuxt/Nitro documentation.

Qwik bindings integration

Qwik applications can be integrated with Cloudflare Developer Platform bindings (such as KV, D1, R2, Queues, and Durable Objects) in both local development and production. Bindings are configured and accessed in Qwik endpoint methods according to Qwik's deployment documentation for Cloudflare Pages.

Access bindings in SolidStart applications

SolidStart applications can access Cloudflare bindings using getRequestEvent().nativeEvent.context.cloudflare.env. This allows full integration with the Cloudflare Developer Platform in both local development and production.

Waku bindings integration

Waku applications can be fully integrated with the Cloudflare Developer Platform in both local development and production by using product bindings. Bindings can be configured and accessed in React Server Components. The Waku Cloudflare documentation provides information about configuring bindings and how to access them in React Server Components.

Add Durable Objects and Workflows to React Router Worker entry file

Because you have direct access to the Worker entry file (workers/app.ts), you can add additional exports such as Durable Objects and Workflows alongside the React Router request handler.

Accessing bindings in React Router loader function

Example showing how to access Cloudflare bindings in a React Router loader function: export function loader({ context }: Route.LoaderArgs) { return { message: context.cloudflare.env.VALUE_FROM_CLOUDFLARE }; }

Access bindings in React Router loader and action functions

Bindings configured in wrangler.jsonc are available within context.cloudflare in React Router loader or action functions, allowing full integration with the Cloudflare Developer Platform.

React Router with Workflows example

Example of setting up a Workflow in a React Router Worker entry file: The workers/app.ts file exports a MyWorkflow class extending WorkflowEntrypoint<Env>, which defines steps using step.do() and step.sleep(). The wrangler.jsonc configures workflows with name, binding, and class_name. A route action accesses the workflow via context.cloudflare.env.MY_WORKFLOW.create() to instantiate and check status.

Accessing bindings from React through Worker API

To use bindings in a React application, configure them in wrangler.jsonc in the Worker backend at ./worker/index.ts. The React application then calls the Worker API endpoints via fetch() requests, allowing the Worker to handle binding access and return responses.

React SPA cannot directly access Workers bindings

React applications cannot directly access Workers bindings. Instead, the React application makes fetch() requests to the Worker backend API, which can then handle the request and access bindings.

Accessing Cloudflare bindings in Vike

Cloudflare API bindings (D1, KV, etc.) are accessed through the env object imported from 'cloudflare:workers'. For example, env.KV.get('my-key') accesses a KV store, and env.LOG_LEVEL accesses an environment variable.

Accessing bindings from Vue applications

Vue applications cannot directly access Workers bindings. Instead, Vue applications make fetch() requests to the Worker backend at ./server/index.ts, which can handle the request and use bindings. This allows indirect access to bindings through the backend API.

Compute bindings for Workers

Cloudflare Workers can integrate with compute services via Bindings: Workers AI for machine learning models powered by serverless GPUs, Workflows for durable long-running operations with automatic retries, Vectorize for vector database and AI-powered semantic search, and Browser Run for programmatic serverless browser instances.

Storage bindings for Workers

Cloudflare Workers can connect to storage services via Bindings: Durable Objects for scalable stateful storage and real-time coordination, D1 for serverless SQL databases built for fast global queries, KV for low-latency key-value storage with edge caching, Queues for guaranteed delivery with no egress bandwidth charges, Hyperdrive for connecting to external databases with accelerated cached queries, and R2 for zero-egress object storage.

Media and CDN bindings for Workers

Cloudflare Workers can integrate with media and content delivery services: Cache/CDN for global caching with high-performance low-latency delivery, and Images for streamlined image infrastructure from a single API.

Durable Object storage and SQL access in Python

In a Python Durable Object class, access storage via self.ctx.storage with async methods: get(key), put(key, value). Access SQL via self.ctx.storage.sql.exec(sql_statement) which returns a result object with one() method to fetch a single row. For example: result = self.ctx.storage.sql.exec("SELECT 'Hello' as greeting").one(); greeting = result.greeting.

Access bindings in Python Worker

Bindings are available on the `self.env` attribute in a Python Worker's class methods. For example, to access a Queue binding named QUEUE: await self.env.QUEUE.send(message).

Query D1 Database from Python Worker

Use await self.env.DB.prepare(sql_statement).run() to execute queries on a D1 database binding. The prepare() method takes the SQL statement and returns a prepared statement object; call run() to execute it. For example: results = await self.env.DB.prepare("PRAGMA table_list").run().

Publish message to Queue from Python Worker

Use await self.env.QUEUE.send(message) to publish to a Queue binding. The method accepts an optional contentType parameter; the default is "json". For text messages, pass contentType="text". For example: await self.env.QUEUE.send("hello", contentType="text") or await self.env.QUEUE.send({"hello": "world"}).

Accessing bindings in Python Workers

Bindings declared in wrangler.json are accessed through the env object in Python Workers. For example, a KV namespace binding named FOO declared in wrangler.json is accessed via self.env.FOO in the Worker class. Bindings for R2, KV, D1, Queues, Durable Objects, Service Bindings, Workers AI, and Vectorize are supported.

KV binding example in Python Worker

Example of using a KV binding in a Python Worker: wrangler.json configuration: ```jsonc { "main": "./src/index.py", "kv_namespaces": [ { "binding": "FOO", "id": "<YOUR_KV_NAMESPACE_ID>" } ] } ``` Python code: ```python from workers import WorkerEntrypoint, Response class Default(WorkerEntrypoint): async def fetch(self, request): await self.env.FOO.put("bar", "baz") bar = await self.env.FOO.get("bar") return Response(bar) # returns "baz" ```

Python Workers bindings to Cloudflare services

Python Workers support bindings to an ecosystem of Cloudflare services including state storage and databases (KV, D1, Durable Objects), Environment Variables, Secrets, Service Bindings, AI capabilities (Workers AI, Vectorize), file storage with R2, and Durable Workflows and Queues.

Env bindings in workers-rs

The Env parameter in Rust Workers provides access to bindings: Secret (secret value), Var (environment variable from wrangler.toml), KvStore (Workers KV namespace), ObjectNamespace (Durable Object binding), Fetcher (service binding to another Worker), Bucket (R2 bucket binding), D1Database (D1 database binding), Queue (Queues producer binding), Ai (Workers AI binding), Hyperdrive (Hyperdrive binding), AnalyticsEngineDataset (Analytics Engine binding), DynamicDispatcher (Dynamic Dispatch binding), SecretStore (Secrets Store binding), and RateLimiter (Rate Limiting binding).

Add single KV key-value pair

Use the command: wrangler kv key put <KEY> <VALUE> --binding=<BINDING> --local to add a single key-value pair to a local KV namespace. This syntax requires Wrangler version 3.60.0 or later. Earlier versions use the kv:... syntax.

Give your agent this brain