---
sidebar_position: 1
title: Cloudflare Workers
description: Query MotherDuck from Cloudflare Workers using the Postgres wire protocol
feature_stage: preview
---

[Cloudflare Workers](https://workers.cloudflare.com/) is an edge compute platform for running serverless functions globally. Workers can connect to MotherDuck through the [Postgres endpoint](/key-tasks/authenticating-and-connecting-to-motherduck/postgres-endpoint) using the [`pg`](https://www.npmjs.com/package/pg) npm package.

## Connection

Workers connect to MotherDuck using a standard Postgres connection string:

```typescript
import { Client } from "pg";

const connectionString =
  `postgresql://user:${MOTHERDUCK_TOKEN}@pg.us-east-1-aws.motherduck.com:5432/${DATABASE}?sslmode=require`;
const client = new Client({ connectionString });
await client.connect();
```

Key requirements:

- The `nodejs_compat` compatibility flag must be enabled in `wrangler.toml` — it provides the `node:net` module that `pg` needs for TCP connections.
- Use `?sslmode=require`. MotherDuck's Postgres endpoint only accepts encrypted connections, and Cloudflare Workers delegates certificate verification to the runtime's TLS stack.
- Store your MotherDuck token as a [Wrangler secret](https://developers.cloudflare.com/workers/configuration/secrets/) — never commit tokens to source code.

## Connection pooling with Hyperdrive

For production workloads, [Cloudflare Hyperdrive](https://developers.cloudflare.com/hyperdrive/) provides built-in connection pooling. This reduces latency by reusing connections across Worker invocations instead of opening a new connection per request.

```toml
# wrangler.toml
[[hyperdrive]]
binding = "MD_HYPERDRIVE"
id = "<your-hyperdrive-config-id>"
```

```typescript
const client = new Client({
  connectionString: env.MD_HYPERDRIVE.connectionString,
});
```

For local development with `wrangler dev`, add a `localConnectionString` to the Hyperdrive binding or export `CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_MD_HYPERDRIVE`. That lets you test the Worker locally against MotherDuck before deploying the Hyperdrive-backed version.

## Tutorial

For a step-by-step guide to building and deploying a Cloudflare Worker that queries MotherDuck, see [Connect from Cloudflare Workers](/key-tasks/authenticating-and-connecting-to-motherduck/postgres-endpoint/cloudflare-workers).
