Skip to content

Commit 7bcb5b1

Browse files
elithrarporsager
authored andcommitted
add Cloudflare Workers to README
1 parent 63ec056 commit 7bcb5b1

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

README.md

+28
Original file line numberDiff line numberDiff line change
@@ -1060,6 +1060,34 @@ const sql = postgres({
10601060
})
10611061
```
10621062

1063+
### Cloudflare Workers support
1064+
1065+
Postgres.js has built-in support for the [TCP socket API](https://developers.cloudflare.com/workers/runtime-apis/tcp-sockets/) in Cloudflare Workers, which is [on-track](https://github.com/wintercg/proposal-sockets-api) to be standardized and adopted in Node.js and other JavaScript runtimes, such as Deno.
1066+
1067+
You can use Postgres.js directly in a Worker, or to benefit from connection pooling and query caching, via the [Hyperdrive](https://developers.cloudflare.com/hyperdrive/learning/connect-to-postgres/#driver-examples) service available to Workers by passing the Hyperdrive `connectionString` when creating a new `postgres` client as follows:
1068+
1069+
```ts
1070+
// Requires Postgres.js 3.4.0 or later
1071+
import postgres from 'postgres'
1072+
1073+
interface Env {
1074+
HYPERDRIVE: Hyperdrive;
1075+
}
1076+
1077+
export default async fetch(req: Request, env: Env, ctx: ExecutionContext) {
1078+
// The Postgres.js library accepts a connection string directly
1079+
const sql = postgres(env.HYPERDRIVE.connectionString)
1080+
const results = await sql`SELECT * FROM users LIMIT 10`
1081+
return Response.json(results)
1082+
}
1083+
```
1084+
1085+
In `wrangler.toml` you will need to enable `node_compat` to allow Postgres.js to operate in the Workers environment:
1086+
1087+
```toml
1088+
node_compat = true # required for database drivers to function
1089+
```
1090+
10631091
### Auto fetching of array types
10641092

10651093
Postgres.js will automatically fetch table/array-type information when it first connects to a database.

0 commit comments

Comments
 (0)