Skip to content

neondatabase/serverless-cfworker-demo

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

36 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@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.

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 .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 within psql.

  • Set environment variables — Create a file .dev.vars, setting the environment variable DATABASE_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 from http://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).

Feedback and support

Please visit Neon Community or Support.