├── static └── demo.png ├── LICENSE ├── README.md └── workers └── todos.js /static/demo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kristianfreeman/cloudflare-workers-todos/HEAD/static/demo.png -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Kristian Freeman 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Cloudflare Workers Todo List App 2 | 3 | This is the source code for my Cloudflare Workers project - a simple todo application, powered by Cloudflare KV as the primary data source. 4 | 5 | ![](./static/demo.png) 6 | 7 | This project is served entirely from the edge, meaning that `workers/todo.js` is the primary file. 8 | 9 | **Note that to experiment with this project, or fork it for your own usage, you'll need access to both Cloudflare Workers and Cloudflare KV.** 10 | 11 | An example version of this project can be found at [todo.kristianfreeman.com](https://todo.kristianfreeman.com). In the blog post for this project, as well as any references to URLs below, you should assume that they are _relative_ to the base URL, `todo.kristianfreeman.com`. 12 | 13 | ## Workers 14 | 15 | The Worker script runs at the edge of the network (Cloudflare), between the client and the origin. 16 | 17 | ### `workers/todos.js` 18 | 19 | This script handles reading and writing todos from KV, as well as making them available in the HTML of the client. 20 | 21 | 1. Hooks into the `fetch` event on the root path to call a `handleRequest` function. 22 | 2. Looks for a GET or PUT and routes to the correct function: 23 | 24 | #### GET requests 25 | 26 | 1. Reads from the Cloudflare KV cache to get the todo array data. The cache _key_ for this is based on the originating IP, meaning that every IP will have a different todo list. 27 | 2. If the cache key isn't found, a default empty set of todos is generated and pushed into cache. 28 | 3. Before the response is served to the user, the worker renders the text of the static HTML, and replaces `var todos;` with the actual data from the cache. 29 | 4. The static HTML is used to generate a `Response` (with a `Content-Type` header set to `text/html`) and rendered on the client. 30 | 31 | The static HTML for this project is nested inside of the Workers script. A small script after the `body` tag takes a given `todos` data set (filled in by the Worker script) and generates a UI based on it. The UI is written in pure JavaScript, but could easily be rewritten using React or Vue. 32 | 33 | The application allows you to view todos from the KV cache, add new todos, and update (mark as complete) existing todos. When any updates occur to the local `todos` data, the page makes a `PUT` request to `/`. 34 | 35 | #### PUT requests 36 | 37 | 1. Reads the body of the `PUT` request, attempting to parse it as JSON to ensure that it's valid content. 38 | 2. If the content is valid, it is persisted into the Cloudflare KV store. 39 | 3. A response is constructed, returning the request body back as the response body. Because the KV cache is _eventually consistent_, we can't reliably return the data from _setting_ the cache here. 40 | 4. If anything goes wrong during this process, a new response is constructed, returning a 500 status code to the client. 41 | 42 | ## Using this project 43 | 44 | This application is intended to be deployed in a single stage: the Workers script in `workers/` should be deployed to Cloudflare Workers, and configured in the following format: 45 | 46 | - `workers/todos.js` should be matched with your _root_ path: for instance, `todo.kristianfreeman.com`. 47 | 48 | You should also set up a Cloudflare KV namespace for your project, [using the Cloudflare API](https://developers.cloudflare.com/workers/kv/writing-data/). In this example, I use `KRISTIAN_TODOS`, but you can obviously call it whatever fits your version of the project. In particular, make sure that you do a find-and-replace for `KRISTIAN_TODOS`, and _also_ find out your namespace ID. The documentation linked above will instruct you on how to do that. 49 | 50 | In addition, you need access to a few API keys and values for use inside of `workers/todos.js`: 51 | 52 | - Account ID, available in the Worker editor URL (see [these docs again](https://developers.cloudflare.com/workers/kv/writing-data/) for instructions) 53 | - KV namespace ID, as mentioned above 54 | - Your Cloudflare email address 55 | - Your Cloudflare API key, available on [your Profile page](https://dash.cloudflare.com/profile) 56 | -------------------------------------------------------------------------------- /workers/todos.js: -------------------------------------------------------------------------------- 1 | const html = todos => ` 2 | 3 | 4 | 5 | 6 | 7 | Todos 8 | 9 | 10 | 11 | 12 |
13 |
14 |

Todos

15 |
16 | 17 | 18 |
19 |
20 |
21 |
22 | 23 | 24 | 80 | 81 | ` 82 | 83 | const defaultData = { todos: [] } 84 | 85 | const setCache = (key, data) => KRISTIAN_TODOS.put(key, data) 86 | const getCache = key => KRISTIAN_TODOS.get(key) 87 | 88 | async function getTodos(request) { 89 | const ip = request.headers.get('CF-Connecting-IP') 90 | const cacheKey = `data-${ip}` 91 | let data 92 | const cache = await getCache(cacheKey) 93 | if (!cache) { 94 | await setCache(cacheKey, JSON.stringify(defaultData)) 95 | data = defaultData 96 | } else { 97 | data = JSON.parse(cache) 98 | } 99 | const body = html(JSON.stringify(data.todos || []).replace(/ { 127 | event.respondWith(handleRequest(event.request)) 128 | }) 129 | --------------------------------------------------------------------------------