Cloudflare Workers

A cloudflare worker component is an app component that uses the Cloudflare worker application type.

Fork a demo cloudflare worker

Fork this cloudflare worker to get started quickly with most of the boilerplate ready:

$bit
Copiedcopy

Run the following to make the cloudflare worker application type (that handles cloudflare worker apps) loadable by your workspace:

$bit
Copiedcopy

Run the following to make the app (worker) loadable by your workspace:

$bit
Copiedcopy

Create a new cloudflare worker

Run the following to create a new Node component:

$bit
Copiedcopy

Add the .cf-worker.ts app plugin file:

// hello-worker.cf-worker.ts

import type { CloudflareOptions } from '@teambit/cloud-providers.aspects.cloudflare-worker';

export const HelloWorldApp: CloudflareOptions = {
  // the name for your worker app (used by bit)
  name: 'hello-world-worker',

  // an entry file for your worker's dev/prod builds
  entry: require.resolve('./hello-world.app-root'),

  // your cloudflare details for deployment
  deployOptions: {
    // the auth token for cloudflare (https://developers.cloudflare.com/api/tokens/create)
    auth: { token: process.env.CLOUDFLARE_TOKEN },
    // your cloudflare account id
    accountId: '37ec40bec82f25b95678f21f01ca64a0',
    // the cloudflare hosting zone id
    zoneId: 'ec8d03e740264543065fad46cb2c528f',
    // the url for the deployed worker
    routes: ['teambit.cloud/hello-world'],
  },
};

export default HelloWorldApp;
CopiedCopy

Run the following to make the AWS lambda application type loadable by your workspace:

$bit
Copiedcopy

Run the following to make your app loadable by the workspace:

$bit
Copiedcopy

Run locally

Run the following to run the app locally:

$bit
Copiedcopy

The output should be similar to the following:

hello-worker app is running on http://localhost:3000

Head to localhost:3000 to see the worker's response:

{ "hello": "world" }
CopiedCopy

Deploy to Cloudflare

Configure the deploy options of your cloudflare worker as shown below. It's recommended to store your credentials in environment variables.

deployOptions: {
    // the auth token for cloudflare (https://developers.cloudflare.com/api/tokens/create)
    auth: { token: process.env.CLOUDFLARE_TOKEN },
    // your cloudflare account id
    accountId: "37ec40bec82f25b95678f21f01ca64a0",
    // the cloudflare hosting zone id
    zoneId: "ec8d03e740264543065fad46cb2c528f",
    // the url for the deployed worker
    routes: ["teambit.cloud/hello-world"],
  },
CopiedCopy

Snap your lambda component to deploy it:

$bit
Copiedcopy