A boilerplate for Cloudflare's Edge Worker with request handler and CRON-triggered schedule handler.
/
: Returns an OK status response./pages
: Returns a 404 status response./dummy
: Calls an API from https://dummyjson.com/products and calculates its price with the discounts provided./keyvalue
: Uses Cloudflare's KV storage to store and retrieve the current time.
Setting a 0 7 * * *
CRON Trigger in Cloudflare's Dashboard will use Cloudflare's KV storage to store and retrieve current time.
To use this boilerplate, you will need a Cloudflare account and an active Workers subscription. Follow these steps to deploy the worker:
-
Clone the repository:
git clone https://github.com/alvinwilta/cloudflare-worker-boilerplate.git
-
Install the Cloudflare Workers CLI:
npm install -g @cloudflare/wrangler
-
Install the required packages:
npm i
-
Log in to your Cloudflare account:
wrangler login
-
Run the command:
wrangler kv:namespace create <namespace_name> wrangler kv:namespace create --preview <namespace_name>
where
<namespace_name>
is the name you want to give your KV store. -
Adjust deployment configuration accordingly in
wrangler.toml
name = "example" main = "src/index.ts" compatibility_date = "2023-03-10" account_id = "$CLOUDFLARE_ACCOUNT_ID" route = "$APP_HOSTNAME" # Put your generated KV id here kv_namespaces = [{ binding = "$KV_NAME", preview_id = "$PREVIEW_ID", id = "$PRODUCTION_ID" }] [vars] APP_ENV = "$APP_ENV" APP_HOSTNAME = "$APP_HOSTNAME" # Optional [triggers] crons = ["* * * * *"]
-
Add CRON Trigger from your Cloudflare Dashboard in
Workers > Services > Triggers > Cron Triggers
. -
Deploy the worker:
wrangler publish
interfaces/
: interface definitions used in this project.routes/
: route services that are invoked for each API request.configuration.ts
: define all API requests provided by the worker.handler.ts
: handle request, option request for CORS Preflight, and scheduled request.index.test.ts
: unit test powered by Vitest.wrangler.toml
: configuration file for Wrangler to run and publish the worker.tsconfig.json
: Typescript configuration file..dev.vars.example
: wrangler env file for local development.
Anyone and everyone is welcome to contribute. You can start by checking out the list of open issues.
Copyright © 2023-present by Alvin Wilta. This source code is licensed under the MIT license found in the LICENSE file.