A great place for platforms to get started on Cloudflare Workers!

Overview

Workers for Platforms Example Project

For SaaS companies, it's challenging to keep up with the never ending requests for customizations. You want your development team to focus on building the core business instead of building and maintaining custom features for every customer use case. Workers for Platforms gives your customers the ability to build services and customizations (powered by Workers) while you retain full control over how their code is executed and billed. The dynamic dispatch namespaces feature makes this possible.

By creating a dispatch namespace and using the dispatch_namespaces binding in a regular fetch handler, you have a “dispatch Worker”:

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request, env) {
  // "dispatcher" is a binding defined in wrangler.toml
  // "customer-worker-1" is a script previously uploaded to the dispatch namespace
  const worker = env.dispatcher.get("customer-worker-1");
  return worker.fetch(request);
}

This is the perfect way for a platform to create boilerplate functions, handle routing to “user Workers”, and sanitize responses. You can manage thousands of Workers with a single Cloudflare Workers account!

In this example

A customer of the platform can upload Workers scripts with a form, and the platform will upload it to a dispatch namespace. An eyeball can request a script by url, and the platform will dynamically fetch the script and return the response to the eyeball. For simplicity, this project is a single Worker that does everything: serve HTML, dispatch Workers, etc. In a real application, it would be ideal to split this Worker into several.

Scripts uploaded to the dispatch namespace are tagged using Script Tags. The dispatch namespace API supports filtering scripts by Script Tag which enables useful CRUD workflows. This platform adds customer_id as a script tag, making it possible to do script access control and query customers' scripts.

Customers of the platform are stored in Workers D1 (sqlite database) with tokens to authenticate specific API interactions. This is not a specific Workers for Platforms feature, but it shows how easy it is to build out functionality for platform management. Beyond authentication, notice how extra data does not need to be stored or managed for the Workers for Platforms workflow!

This project depends on:

Getting started

Your Cloudflare account needs access to Workers for Platforms and D1. Please talk to your CSM or request access in our Discord.

As of 7 Sept 2022, you need to install wrangler@d1 to use the D1 binding: npm install wrangler@d1.

  1. Install the package and dependencies:

    npm install
    
  2. Create a D1 database and copy the ID into wrangler.toml:

    npx wrangler d1 create workers-for-platforms-example-project
    
  3. Edit the [vars] in wrangler.toml and set the DISPATCH_NAMESPACE_AUTH_KEY secret (instructions in wrangler.toml). For local development, you also have to create a .dev.vars file with the same environment variables:

    DISPATCH_NAMESPACE_ACCOUNT_ID = "replace_me"
    DISPATCH_NAMESPACE_AUTH_EMAIL = "replace_me"
    DISPATCH_NAMESPACE_AUTH_KEY = "replace_me"
    
  4. Create a namespace. Replace $(ACCOUNT), $(API_TOKEN), and $(NAMESPACE):

    curl -X POST https://api.cloudflare.com/client/v4/accounts/$(ACCOUNT)/workers/dispatch/namespaces \
      -H 'Authorization: Bearer $(API_TOKEN)' \
      -H 'Content-Type: application/json' \
      -d '{"name": "$(NAMESPACE)"}'
    

    You can use either Authorization: Bearer <...> or X-Auth-Email + X-Auth-Key headers for authentication. Go to Workers dashboard -> click "API Tokens" on right sidebar. Then either:

    1. Click "Create Token". This token is used with Bearer. OR:
    2. Click "View" next to "Global API Key". This token is the X-Auth-Key.
  5. Run the Worker in dev local mode.

    npx wrangler dev --local
    

    Or publish:

    npx wrangler publish
    

    As of 7 Sept 2022, dynamic dispatch does not work in wrangler dev mode. However, it will work when published. We will support this in the future.

Once the Worker is live, visit localhost:8787 in a browser and click the Initialize link. Have fun!

If you change the name of the dispatch namespace in wrangler.toml, make sure to update it here, too:

// ./src/env.ts
export const DISPATCH_NAMESPACE_NAME = 'workers-for-platforms-example-project';

For dev testing, here's a snippet to use in a NodeJS environment (like Chrome Dev Tools) to exercise the API:

await (await fetch("http://localhost:8787/script/my-customer-script", {
  "headers": {
    "X-Customer-Token": "d4e5f6"
  },
  "method": "PUT",
  "body": "...my-script-content..."
})).text();

Or using curl:

curl -X PUT http://localhost:8787/script/my-customer-script -H 'X-Customer-Token: d4e5f6' -d '...my-script-content...'

Troubleshooting

  • Use npx wrangler tail to capture logs.
  • Try a re-publish and wait a minute.

Example project roadmap

  • Showcase a Trace Worker and Workers Logpush to collect trace events for both the platform Worker and dispatched customer Workers.
You might also like...

A collection of useful tools for building web apps on Cloudflare Workers.

Keywork is a batteries-included, magic-free, library for building web apps on Cloudflare Workers. Features 💪 Written in TypeScript 📚 Modules Support

Dec 22, 2022

Abusing Cloudflare Workers to establish persistence and exfiltrate sensitive data at the edge.

Abusing Cloudflare Workers This repository contains companion code for the blog post MITM at the Edge: Abusing Cloudflare Workers. malicious-worker/ c

Sep 16, 2022

Lightweight universal Cloudflare API client library for Node.js, Browser, and CF Workers

Cloudflare API Client Lightweight universal HTTP client for Cloudflare API based on Fetch API that works in Node.js, browser, and CF Workers environme

Nov 13, 2022

A starter template for Remix + Cloudflare Workers + DO + KV + Turborepo

Remix + Cloudflare Workers starter with Turborepo 🚀 Starter to get going with Remix and Cloudflare Workers. This template is based on the starter cre

Jan 2, 2023

A Cloudflare Workers service that fetches and renders Notion pages as HTML, Markdown, or JSON.

notion-fetch A Cloudflare Workers service that fetches and renders Notion pages as HTML, Markdown, or JSON. Powered by Durable Objects and R2. Usage P

Jan 6, 2023

A flexible gateway for running ML inference jobs through cloud providers or your own GPU. Powered by Replicate and Cloudflare Workers.

Cogflare (Working title) Cogflare is a Cloudflare Workers application that aims to simplify running distributed ML inference jobs through a central AP

Dec 12, 2022

Firebase/Admin Auth Javascript Library for Cloudflare Workers

Flarebase Auth Firebase/Admin Auth Javascript Library for Cloudflare Workers Supported operations: createSessionCookie() verifySessionCookie() signInW

Jan 1, 2023

A zero-dependency, strongly-typed web framework for Bun, Node and Cloudflare workers

nbit A simple, declarative, type-safe way to build web services and REST APIs for Bun, Node and Cloudflare Workers. Examples See some quick examples b

Sep 16, 2022

Low cost, low effort P2P WebRTC serverless signalling using Cloudflare Workers

Low cost, low effort P2P WebRTC serverless signalling using Cloudflare Workers

P2PCF P2PCF enables free (or cheap) serverless WebRTC signalling using a Cloudflare worker and a Cloudflare R2 bucket. The API is inspired by P2PT, bu

Jan 8, 2023
Comments
Owner
Cloudflare
Cloudflare
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
基于 gh-proxy + Jsdelivr+ cnpmjs + cloudflare workers 的 GitHub Serverless API 工具。

better-github-api Better, Eazy, Access Anywhere 介绍 基于 gh-proxy + Jsdelivr + cnpmjs + cloudflare workers 的 GitHub Serverless API 工具。 cdn.js:仅含 gh-proxy

One Studio 11 Nov 23, 2022
A URL shortener that runs on Cloudflare Workers

ITP Works A URL shortener that runs on Cloudflare Workers. It stores the rules in Cloudflare KV storage and sends a 301 redirect when a matched pathna

Yifei Gao 3 Mar 4, 2022
Starting template for building a Remix site with CloudFlare Workers (ES Modules Syntax)

Starting template for building a Remix site with CloudFlare Workers (ES Modules Syntax)

null 12 May 20, 2022
Google-Drive-Directory-Index | Combining the power of Cloudflare Workers and Google Drive API will allow you to index your Google Drive files on the browser.

?? Google-Drive-Directory-Index Combining the power of Cloudflare Workers and Google Drive will allow you to index your Google Drive files on the brow

Aicirou 127 Jan 2, 2023
Remix + Cloudflare Workers + DO + Turborepo

Remix + Cloudflare Workers + DO + Turborepo A starter to get you up and going with Remix on Cloudflare with all the latest and greatest. What's inside

Jacob Ebey 38 Dec 12, 2022
Remix + Cloudflare Workers + Wrangler2 + Tailwind + ESLint + Prettier + Vitest + Playwright

Welcome to Remix! Remix Docs Development You will be running two processes during development: The Miniflare server (miniflare is a local environment

null 48 Dec 19, 2022
Server-side rendering blog runs on Cloudflare workers

Serverside rendered blog I have tried something completely against to current web trends. What are these? I am using the React as backend framework wi

null 3 Jun 24, 2022