Skip to content

Demo of a Cloudflare Worker

Notifications You must be signed in to change notification settings

Rusty-Magnet-Ltd/cloudflare_worker

Repository files navigation

Cloudflare Worker

CircleCI

Code powers foobar.rustymagnet.xyz.

Learnings

Testing

Testing requires the "cloudflare:test" to get environment variables into vitest:

import { env } from "cloudflare:test";

it("/carpark ok", async () => {
    const res = await app.request("/carpark", {}, env);
    expect(res.status).toBe(200);
});

Secrets

Local code uses a .dev.vars to read secret environment variables. The normal .env file is used by Cloudflare code. Default test values can be set in the wrangler.toml file as below; these can be source controlled safely as they only for CI/CD tests and don't get deployed to actually workers. It would be different if the wranger deploy --env=testing was used:

[env.testing.vars]
SECURITY_HEADER_NAME = "X-Header"
SECRET_KEY = "dummy"
ENVIRONMENT = "DEVELOPMENT"

debug

console.log() output is available. Use the tail command in the cli tool. This also outputs Cloudflare added headers like cf-ipcountry, asn, ray-id, True IP.

wrangler tail foo

Set up

Deploy code to Cloudflare Worker

sequenceDiagram

   participant Engineer
   participant GitHub
   participant CircleCI
   participant Cloudflare
   Engineer->>GitHub: code change
   GitHub->>CircleCI: invoke change
   CircleCI->>CircleCI: set up Cloudflare's Wranger cli tool
   CircleCI->>CircleCI: Lint and test code
   CircleCI->>Cloudflare: upload new code with Wrangler cli
Loading

Design choices

  • Started on itty-router. But docs and testing was clearer in Hono.
  • The app uses Grouping of routers to make it simple to slim down code into discrete files. Link here.
  • Setting the ENVIRONMENT variable needs to be handled; a great article here
  • A Boilerplate on structuring project.
  • The JWT work was based these helpers.

About

Demo of a Cloudflare Worker

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published