Skip to content

Latest commit

 

History

History
 
 

worker-postgres

Template: worker-postgres

Deploy to Cloudflare Workers

This repo contains example code and a PostgreSQL driver that can be used in any Workers project. If you are interested in using the driver outside of this template, copy the driver/postgres module into your project's node_modules or directly alongside your source.

Setup

To create a my-project directory using this template, run:

$ npm init cloudflare my-project worker-postgres
# or
$ yarn create cloudflare my-project worker-postgres
# or
$ pnpm create cloudflare my-project worker-postgres

Note: Each command invokes create-cloudflare for project creation.

Usage

Before you start, please refer to the official tutorial.

const client = new Client({
	user: '<DATABASE_USER>',
	database: '<DATABASE_NAME>',
	// hostname is the full URL to your pre-created Cloudflare Tunnel, see documentation here:
	// https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/create-tunnel
	hostname: env.TUNNEL_HOST || 'https://dev.example.com',
	password: env.DATABASE_PASSWORD, // use a secret to store passwords
	port: '<DATABASE_PORT>',
});

await client.connect();

Please Note:

  • you must use this config object format vs. a database connection string
  • the hostname property must be the URL to your Cloudflare Tunnel, NOT your database host
    • your Tunnel will be configured to connect to your database host

Running the Postgres Demo

postgres/docker-compose.yml

This docker-compose composition will get you up and running with a local instance of postgresql, pgbouncer in front to provide connection pooling, and a copy of cloudflared to enable your applications to securely connect, through a encrypted tunnel, without opening any ports up locally.

Usage

from within scripts/postgres, run:

  1. Create credentials file (first time only)
docker run -v ~/.cloudflared:/etc/cloudflared cloudflare/cloudflared:2021.10.5 login
  1. Start a local dev stack (cloudflared/pgbouncer/postgres)
TUNNEL_HOSTNAME=dev.example.com docker-compose up