Video summary
Using APIs and Databases with Cloudflare Workers (Advanced Course)
Main summary
Key takeaways
Overview: Adding “state” to Cloudflare Workers
Cloudflare Workers can lose in-memory data on refresh or restart if you don’t use an external state mechanism. This video explains why that happens and shows three common ways to manage/persist state:
- Cloudflare Workers KV (Key-Value Store) for simple cached values
- Fast reads
- Expirations
- JSON handling
- Cloudflare D1 (serverless SQL database) for structured/relational data
- SQL queries
- Migrations
- Querying and CRUD-style operations
- Prisma (ORM/wrapper over D1) for typed data models
- Schema-defined models
- Auto-generated SQL/migrations
- Typed query APIs
Example 1: API + caching with Workers KV
Goal
Call an external API (GitHub) from a Worker and cache responses in KV.
Steps / concepts covered
- Create a Worker with TypeScript and a lightweight web framework (Hono) to structure routes.
- Add an endpoint:
GET /:username→ fetcheshttps://api.github.com/users/:username/repos(repos data)- Returns JSON to the client
- Add KV caching:
- Before calling GitHub, attempt
KV.get(username) - If a cached value exists, return it immediately
- If not:
- Fetch from GitHub
- Store it in KV via
KV.put(username, JSON.stringify(data)) - Return the fetched data
- Before calling GitHub, attempt
- Performance emphasis:
- Repeated requests become much faster when served from KV (tens of milliseconds vs. ~1 second from the external API)
KV specifics called out
- Best for read-heavy workloads and caching
- Supports expiration keys
- Supports JSON parsing when retrieving (via JSON options/bindings)
Example 2: Structured persistence with Cloudflare D1 (SQL)
Goal
Build a small Movies API persisted in D1, including migrations and CRUD-like operations.
Setup / tooling covered
- Use
npx wrangler ...to:- Create a D1 database:
wrangler D1 create - Bind the D1 database to the Worker via
wrangler.toml
- Create a D1 database:
- Create and apply D1 migrations:
wrangler D1 migrations create ...wrangler D1 migrations apply ...
- Important deployment note:
- If you deploy without running migrations in production, endpoints will fail with an internal server error
- Fix by applying migrations with the
--remoteflag
Data modeling and migration
A movies table is created with columns:
id(auto-increment primary key)title(TEXT, NOT NULL)release_date(TEXT, NOT NULL)rating(INTEGER, NOT NULL)
API endpoints implemented
GET /movies- Executes:
SELECT * FROM movies
- Executes:
GET /favorites- Executes:
ORDER BY rating DESC LIMIT 3
- Executes:
PUT /movies/:id- Reads JSON body like
{ rating: ... } - Updates with bound parameters:
UPDATE movies SET rating = ? WHERE id = ? RETURNING *
- Returns a success status
- Shows that updating a rating reorders the favorites list afterward
- Reads JSON body like
Additional insight
- Mentions a local D1 workflow:
- Locally behaves like a SQLite database
- Migrations can then be applied remotely to the actual D1 instance
Example 3: Prisma + Hono + D1 (starter kit concept)
Goal
Show how Prisma simplifies D1 usage with schema-defined models and typed queries.
Prisma positioning
Prisma is described as an ORM wrapper for D1:
- Define models in a Prisma schema
- Prisma generates SQL migrations
- Provides typed query APIs (create/find/update/delete)
An analogy is given: Prisma is like “Ruby on Rails for JavaScript” (high-level comparison).
What the starter kit covers (conceptually)
Combines:
- Hono X (Hono extension) for frontend UI + backend endpoints
- Cloudflare D1 as the database
- Prisma for schema/model + querying
Prisma workflow shown
- Create a Prisma schema model (example: a
todotable):id(autoincrement integer)description(string)completed(boolean)createdAt(datetime)
- Generate migrations from the schema (conceptually):
- “Prisma CLI generates a SQL migration”
- Query/update data via Prisma client methods:
findManyfindUniqueupdate
- Endpoint-level integration:
- Routes render todo lists
- A route toggles completion based on
id
Mentions another related integration
- Brief mention of an additional integration with Drizzle (for more fully featured data models with D1)
Key repositories / resources mentioned
- GitHub repo for the API + KV example:
github.com/ChristianFreeman/API-and-KV-example
- A GitHub repo/starter mentioned for D1 + Prisma + Hono X (full name referenced but not fully restated)
Main speaker / sources
- Christian Freeman (Cloudflare Developer Advocate)