This Todo App is a project demonstrating the creation of an end-to-end type-safe web application quickly and cost-effectively by combining tRPC, Cloudflare Pages, Cloudflare Pages Functions, and Cloudflare D1. This repository contains the source code for the application, as well as instructions on how to set up and deploy it.
- Host static content on Cloudflare Pages
- Implement serverless functions for API endpoints using Cloudflare Pages Functions
- Utilize tRPC for type-safe communication between backend and frontend
- Use Cloudflare D1 as a lightweight, SQLite-based database solution
- Node.js (v18 or higher)
- Cloudflare account
-
Create a repository from this template repository using the GitHub CLI
gh repo create yapc-kyoto-2023-demo --template toyamarinyon/trpc-d1-todo
-
Instal dependencies
npm install
Note I prefer pnpm over npm but Cloudflare Pages builds do not yet support pnpm.
-
Create your database
Run the following command and give your database a name:
npx wrangler d1 create <DATABASE_NAME>
-
Configure database binding with wrangler.toml
You need to configure database binding to run it and test it locally with wrangler.toml
Add the following to your wrangler.toml file:
[[ d1_databases ]] binding = "<BINDING_NAME>" database_name = "<DATABASE_NAME>" database_id = "<UUID>"
Set your binding name by updating the <BINDING_NAME> value. Your binding is available in your Cloudflare Pages Functions at env.<BINDING_NAME>. You will find the values for database_name and database_id in your terminal after you run the create command in step 3.
-
Run a query against your D1 database
You can create our database with schema.sql:
# schema.sql DROP TABLE IF EXISTS tasks; CREATE TABLE tasks ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, description TEXT, completion_datetime DATETIME );
Let's create database by running:
npx wrangler d1 execute <DATABASE_NAME> --local --file=./schema.sql
Then validate your data is in your database by running:
npx wrangler d1 execute <DATABASE_NAME> --local --command='SELECT * FROM tasks'
-
Run locally with Wrangler
While in your project directory, test your database locally by running:
npx wrangler pages dev --local --persist --d1=<DATABASE_NAME> -- npm run dev
When you run
wrangler pages dev -- npm run dev
, Wrangler will let you run your Pages application locally, which includes pass throughnpm run dev
to run vite development server and running your Functions.will give you a URL (most likely localhost:8787) to review your Worker.
- Log in to the Cloudflare dashboard.
- Select your account in Account Home > Pages.
- Select Create a project > Connect to Git.
- Select your new GitHub repository.
- In the Set up builds and deployments, set
npm run build
as the Build command, anddist
as the Build output directory. - Select Environment variables (advanced) > + Add variable > configure a
NODE_VERSION
variable with a value of any version of Node greater than14.18
-- this example uses16
: