This repo provides an example of using Neon's @neondatabase/serverless
driver package to query PostgreSQL from a Cloudflare Worker, and to cache the results.
The example is a web app that returns a list of your nearest UNESCO World Heritage Sites.
-
You can see the app deployed at https://places-neon-demo.pages.dev/ (this is static HTML file
presentation/index.html
deployed to Cloudflare Pages). -
You can see the JSON data it fetches at https://places.neon-demo.workers.dev/ (this is
index.ts
deployed as a Cloudflare Worker)
Please note that the UNESCO data is copyright © 1992 – 2022 UNESCO/World Heritage Centre. All rights reserved.
Neon's @neondatabase/serverless
driver is based on and offers the same API as the node-postgres package, which is what you get with npm install pg
.
We've simply shimmed the Node libraries it requires, and replaced net.Socket
and tls.connect
with implementations that encrypt and transfer the data over WebSockets.
Find out more about the driver from the @neondatabase/serverless
README on npmjs.com or GitHub.
To run this app locally:
-
Get the data — Download the Excel listing from the UNESCO Syndication page. Open the
.xls
file and save it as a.csv
. -
Create the database — Create a new project in the Neon dashboard, and connect to it securely using
psql
(substituting your own PostgreSQL connection string, of course):mkdir -p $HOME/.postgresql curl https://letsencrypt.org/certs/isrgrootx1.pem > $HOME/.postgresql/isrgrootx1.pem psql "postgresql://user:[email protected]:5432/main?sslmode=verify-full&sslrootcert=$HOME/.postgresql/isrgrootx1.pem"
-
Load the data — Run the SQL commands in
data/import.psql
against your database withinpsql
. -
Set environment variables — Create a file
.dev.vars
, setting the environment variableDATABASE_URL
to the PostgreSQL connection string you'll find in your Neon dashboard. That should look something like this:DATABASE_URL=postgresql://user:[email protected]:5432/main
-
Install and run
npm install npm install -g wrangler@latest npx wrangler dev --local
Edit
presentation/index.html
to fetch fromhttp://localhost:8787
, and open that address in your browser. -
Deploy
npx wrangler secret put DATABASE_URL # same connection string as in `.dev.vars` npx wrangler publish
(You may then need to edit
presentation/index.html
to fetch from the deployed endpoint).
Please visit Neon Community or Support.