Introduction to Cloudflare Workers

The Cloudflare docs describe Workers as:

Cloudflare Workers provides a serverless execution environment that allows you to create new applications or augment existing ones without configuring or maintaining infrastructure.

Hmm, so that’s nice generic tech speak but it’s a big vague IMO. However, Cloudflare do provide a very good set of examples for how to use Workers e.g. a worker that accepts a POST request with JSON payload, a Geolocation aware Hello World!, and a worker that is aware of multiple cron schedules. Be sure to check these example out as they are an excellent HOWTO resource.

Note, workers can work in a front-end or back-end scenario, but for this post we will be focused on back-end only.

Types of Workers

The cron example there is a clue that there are different types of Workers. These are called handlers, and there are six different types:

Let’s briefly examine three of these handlers, fetch, scheduled, and tail.

Fetch / HTTP Handler

A fetch handler is defined by implementing the fetch function. The following Hello World! example shows how to send a simple text response:

export default {
	async fetch(request, env, ctx) {
		return new Response('Hello World!');
	},
};

To send a JSON response the shortcut .json function can be used:

export default {
  async fetch(request, env, ctx) {
    const data = {
      hello: "world",
    };

    return Response.json(data);
  },
};

Scheduled / Cron Handler

A cron handler is defined by implementing the schedule function:

export default {
  async scheduled(event, env, ctx) {
    console.log("cron processed");
  },
};

A cron handler cannot return a response as there is no accompanying request. Cron handlers for jobs that need to execute on a schedule e.g. running a report, monitoring a resource, etc.

The schedule is set via cron expressions and defined in the worker config file, called wrangler.toml (more about this in a future post). The following file contains a trigger that schedules the handler to execute every day at 00:00.

name = "worker"

# ...

[triggers]
crons = ["0 0 * * *"]

Tail Handler

A tail handler is as mentioned earlier for processing log output. This is because Cloudflare don’t provide a built-in logging service for workers. Therefore, it’s not possible to open a worker in the dashboard, and examine the log from the last run.

This is where tail handlers come in. By binding a tail handler to your worker, when your worker completes execution, it sends all the log output from that run to the bound tail worker. The tail worker can then process the log events into an appropriate format, and forward them to the logging platform of choice.

A tail handler is defined by implementing the tail function. The following example forwards unmodified log events directly to a logging API:

export default {
  async tail(events, env, ctx) {
    fetch("<YOUR_ENDPOINT>", {
      method: "POST",
      body: JSON.stringify(events),
    })
  }
}

Summary

This post should have given a very brief glimpse into Cloudflare Workers and what they might be used for. To see some real world handlers be sure to checkout the timecop project.

References

Last updated: July 3, 2024 at 07:54