Cloudflare Worker

This document describes integrating with the Spec Platform through a Cloudflare worker.

Prerequisites

Please ensure that your development environment has the following dependencies installed with the latest version:

  1. Follow Cloudflare’s “Get started guide” to install Wrangler in your development environment.

    This is the Cloudflare Workers command-line interface, which allows you to create, edit, and publish Workers projects to your Cloudflare account.

  2. Following installation, authenticate wrangler.

  3. A TypeScript or JavaScript project to install.

  4. The Spec Worker Library for Cloudflare.

  5. Check out the configuration options for the Spec Platform in Config.

Instructions

  1. Configure a new project with Wrangler, or open an existing project.

  2. Install NPM Spec Proxy Cloudflare Worker into project:

    1. npm i –save @specprotected/spec-proxy-cloudflare-worker

  3. Open index.ts file and copy the worker code from the Prerequisites.

  4. Publish the worker. Open a terminal window and run wrangler publish

Configuring Worker Route

With the worker published, we can now use the Cloudflare admin console to configure a route that will use the Spec worker code.

  1. Click "Workers" from Cloudflare sidebar

  2. Select the newly published worker, and find the "Triggers" section.

  3. Click "Add Route" to add a new route for the worker.

    1. Enter URL that matches the traffic path you would like to send to Spec

    2. Select zone that pertains to the domain for your project.

    3. Add route.

  4. The Spec Cloudflare Worker is now live!

Spec Worker Library

If no existing workers exist, the following is Spec's recommended worker code. If there are existing workers, Spec's Product Success will assist in merging the following code with your existing code.

Worker Example

// Import the Spec Proxy library function
import { specProxyProcess } from "@specprotected/spec-proxy-cloudflare-worker";

// Normal Edge Worker event listener
addEventListener("fetch", (event) => {
  // If we don't catch the exception, fail open to original traffic path
  event.passThroughOnException();
  
  // Config object that may be hardcoded or use Cloudflare environment variables
  const config = {
    inlineMode: true,
    disableSpecProxy: false
  };
  
  // Spec library processes the request and returns a new, modified one back to you.
  // Please ensure that you use the returned request as the destination request
  // of your worker script. This will ensure that traffic is routed appropriately.
  let request = specProxyProcess(event, config);

  // This is the simplest form where the worker script doesn't do anything else
  event.respondWith(request);
});

Check Edge Workers page for configuration options.

Last updated