Skip to content

Latest commit

 

History

History

cloudflare-pages-D1

Northwind Traders (by subZero)

Running on Cloudflare's Pages + D1

This is a demo of subZero library capabilities, leveraged in a NextJS app, to automatically expose a PostgREST compatible backend on top of the underlying database.

See the source code on GitHub.

Features / Advantages

  • Integrates in your codebase as a library (no need to deploy a separate service)
  • Runs in any context (Docker, AWS Lambda, Vercel, Netlify, Fly.io, Cloudflare Pages, Deno, Node, etc)
  • Implemented in Rust with JS/TypeScript bindings through WASM with no dependencies
  • Multiple databases supported:
    • SQLite (including Cloudflare D1)
    • PostgreSQL (including YugabyteDB, CockroachDB, TimescaleDB, etc)
    • ClickHouse
    • MySQL (PlanetScaleDB upcoming)
  • Supports advanced analytical queries (window functions, aggregates, etc)

Example details

  • Frontend is implemented in NextJS

  • Everything is deployed to Cloudflare Pages

  • Data is stored in D1 Cloudflare's SQLite compatible edge database

  • The backend runs in a single serverless function (see Cloudflare Functions for details). Most of the code deals with the configuration of the backend, and 99% of the functionality is within these lines:

    // generate the SQL query from request object
    const { query, parameters } = await subzero.fmtStatement(publicSchema, `${urlPrefix}/`, role, req, queryEnv)
    // .....
    // prepare the statement
    const statement = env.DB.prepare(query).bind(...parameters)
    // execute the query
    const result = await statement.first()
    // ...
    // this is a json string
    const body = result.body
    // ...
    // return the response
    return new Response(body, { /* ... */})

Running locally

  • Clone the repo
    git clone https://github.com/subzerocloud/showcase.git
  • cd to the example directory
    cd showcase/cloudflare-pages-D1
  • Install dependencies (you will need to have SQLite installed on your machine)
    yarn install
  • Populate the database
    yarn seed
  • Run in dev mode
    yarn dev
  • Open the app in your browser
    open http://localhost:3000

Credits