serverless-cfworker-demo
serverless-cfworker-demo copied to clipboard
Demo app for @neondatabase/serverless — details at https://blog.cloudflare.com/neon-postgres-database-from-workers/
@neondatabase/serverless example: query Neon PostgreSQL from a Cloudflare Worker
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 app
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.htmldeployed to Cloudflare Pages). -
You can see the JSON data it fetches at https://places.neon-demo.workers.dev/ (this is
index.tsdeployed as a Cloudflare Worker)
Please note that the UNESCO data is copyright © 1992 – 2022 UNESCO/World Heritage Centre. All rights reserved.
The driver
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.
How to run
To run this app locally:
-
Get the data — Download the Excel listing from the UNESCO Syndication page. Open the
.xlsfile 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.psqlagainst your database withinpsql. -
Set environment variables — Create a file
.dev.vars, setting the environment variableDATABASE_URLto 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 --localEdit
presentation/index.htmlto 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.htmlto fetch from the deployed endpoint).
Feedback and support
Please visit Neon Community or Support.