Search Sreeni's Insights

Filter by content type
cloud April 3, 2018 6 min read

How to set up a local development environment for Cloudflare Workers? - Part 2

Set up a local development environment for Cloudflare Workers with Node.js, Yeoman and TypeScript, unit test the handler and bundle it with webpack.

Share:

How to set up a local development environment for Cloudflare Workers? - Part 2

Writing a worker in the browser editor of the Cloudflare dashboard is a nice way to try it out, but it is not how we want to build production code. There is no version control, no unit tests and no code review, and the only way to see whether the code works is to deploy it. When we started using workers, there were no tools to develop them locally, so we created a small setup which simulates the worker environment in Node.js and lets us write, test and bundle workers on our machines. In the previous article, we discussed what a Cloudflare Worker is, how it works, and when to use it. In this article, we are going to see how to set up a local development environment for workers with TypeScript, how to unit test a worker, and how to bundle and deploy it to Cloudflare.

Cloudflare Workers series:

  1. What is Cloudflare Worker and why do we need it?
  2. How to set up a local development environment for Cloudflare Workers? (this article)
  3. How to write Cloudflare Workers? Common patterns with examples
  4. Cloudflare Workers use cases and lessons learned

TL;DR Summary

  • Use Node.js, npm, Yeoman and the generator-node-typescript generator to scaffold a TypeScript project for the worker.
  • Install node-fetch and its type declarations to simulate fetch, Request, Response and Headers in Node.js.
  • Keep the request handling logic in a separate module, so it can be unit tested without the worker runtime.
  • Bundle the TypeScript code into a single JavaScript file with webpack, because a worker must be a single script.
  • Deploy the bundled script through the Cloudflare dashboard or the Cloudflare API, and configure the route in the dashboard.

The approach

The worker runtime gives us the Service Worker API: the fetch event and the standard fetch, Request, Response and Headers classes. Node.js doesn’t have these out of the box. So, our approach is,

  1. Write the request handling logic as a plain function: it takes a Request and returns a Response.
  2. Keep the worker-specific part (the fetch event listener) in a very small entry file.
  3. In the unit tests, provide fetch, Request, Response and Headers from the node-fetch package, so the same handler runs in Node.js.
  4. Bundle the code into a single script with webpack and deploy it.

This way, almost all of the code is tested on our machines before it reaches the edge.

Prerequisites

  • Node.js - Install the latest stable (LTS) version from nodejs.org.
  • npm - Install the latest version. Normally, it is installed as part of Node.js.
  • A Cloudflare account with a zone (domain), and Workers enabled for the zone.

Just to pulse check, type the following commands. Both should print a version number.

node -v
npm -v

Steps to set up the project

Follow the following instructions to set up the worker project.

  1. Install the Yeoman package with the following command. Yeoman is a scaffolding tool which creates a project from a template (called a generator).

    npm install yo -g
  2. Create a directory with any name. For demonstration, I will name it myfirstworker.

    mkdir myfirstworker
    cd myfirstworker
  3. Install the TypeScript generator for Node.js with the following command.

    npm install generator-node-typescript -g
  4. Create the project with Yeoman. It asks a few questions (like the project name and description); answer them and it creates the project in the current directory.

    yo node-typescript

    The generator scaffolds a TypeScript project with a src folder for the code, a test folder for the unit tests, a tsconfig.json file and the npm scripts to build and test the project. Open the generated package.json to see the scripts and the test framework it uses.

  5. Install the node-fetch package and its type declarations. node-fetch brings the browser fetch API to Node.js, and we use it to simulate the worker environment in the unit tests.

    npm install node-fetch --save-dev
    npm install @types/node-fetch --save-dev
  6. If the generated project doesn’t include Mocha and Chai, install them for the unit tests.

    npm install mocha chai @types/mocha @types/chai ts-node --save-dev
  7. Install webpack and the TypeScript loader to bundle the worker into a single script.

    npm install webpack webpack-cli ts-loader --save-dev

Steps to write the worker

  1. Make sure the lib setting in tsconfig.json includes dom, so TypeScript knows the types of fetch, Request, Response, Headers and URL.

    \{
      "compilerOptions": \{
        "target": "es2017",
        "module": "commonjs",
        "lib": ["es2017", "dom"],
        "strict": true
      }
    }
  2. Create the request handler in src/handler.ts. This is where all the logic lives.

    export async function handleRequest(request: Request): Promise<Response> \{
      const url = new URL(request.url);
    
      if (url.pathname === '/hello') \{
        return new Response('Hello from the edge!', \{
          headers: \{ 'content-type': 'text/plain' }
        });
      }
    
      // All other requests go to the origin as they are
      return fetch(request);
    }
  3. Create the worker entry file in src/index.ts. It only connects the fetch event to the handler.

    import \{ handleRequest } from './handler';
    
    declare const addEventListener: (type: 'fetch', handler: (event: any) => void) => void;
    
    addEventListener('fetch', event => \{
      event.respondWith(handleRequest(event.request));
    });

Steps to unit test the worker

  1. Create test/setup.ts to simulate the worker environment. It puts the node-fetch classes on the Node.js global object, where the worker code expects them.

    import fetch, \{ Headers, Request, Response } from 'node-fetch';
    import \{ URL } from 'url';
    
    const g = global as any;
    g.fetch = fetch;
    g.Headers = Headers;
    g.Request = Request;
    g.Response = Response;
    g.URL = URL;
  2. Create the unit test in test/handler.spec.ts.

    import './setup';
    import \{ expect } from 'chai';
    import \{ handleRequest } from '../src/handler';
    
    describe('handleRequest', () => \{
      it('should respond to /hello at the edge', async () => \{
        // Arrange
        const request = new Request('https://www.example.com/hello');
    
        // Act
        const response = await handleRequest(request);
    
        // Assert
        expect(response.status).to.equal(200);
        expect(await response.text()).to.equal('Hello from the edge!');
      });
    });
  3. Run the tests with the test script of the generated project, or directly with Mocha.

    npx mocha -r ts-node/register test/**/*.spec.ts

For the requests which go to the origin, don’t call the real origin from unit tests. Replace global.fetch with a fake function in the test, and assert what the handler sent to it. We will use this technique in the next article.

Steps to bundle the worker

A worker must be a single JavaScript file; it can’t load modules with require or import at runtime. So, we bundle the code with webpack.

  1. Create webpack.config.js in the project root.

    const path = require('path');
    
    module.exports = \{
      entry: './src/index.ts',
      target: 'webworker',
      mode: 'production',
      module: \{
        rules: [\{ test: /\.ts$/, use: 'ts-loader', exclude: /node_modules/ }]
      },
      resolve: \{ extensions: ['.ts', '.js'] },
      output: \{
        filename: 'worker.js',
        path: path.resolve(__dirname, 'dist')
      }
    };
  2. Bundle the worker. It creates dist/worker.js, and this is the file we deploy.

    npx webpack

Note: Don’t bundle node-fetch or any other Node.js-only package into the worker. The worker runtime already has fetch, Request and Response; node-fetch is only for the tests.

Steps to deploy the worker

Option 1: Cloudflare dashboard

  1. Login to the Cloudflare dashboard and select your zone.
  2. Open the Workers app and launch the editor.
  3. Replace the script with the content of dist/worker.js.
  4. Use the preview and testing panels in the editor to send a test request to /hello.
  5. Save and deploy the script.
  6. Add a route for the worker, for example www.example.com/hello*. Start with a narrow route, and widen it once you are confident.

Option 2: Cloudflare API

For automated deployments (for example, from a build pipeline), upload the script with the Cloudflare API. Replace the input place holders with actual values.

curl -X PUT "https://api.cloudflare.com/client/v4/zones/<zone id>/workers/script" \
  -H "X-Auth-Email: <cloudflare account email>" \
  -H "X-Auth-Key: <cloudflare api key>" \
  -H "Content-Type: application/javascript" \
  --data-binary "@dist/worker.js"

Configure the route in the dashboard once, as described in Option 1.

Must Do: Never commit the Cloudflare API key to the repository. Keep it in the secret variables of your build pipeline. The key gives full access to your Cloudflare account.

Pulse check

Just to pulse check, type the following command. You should see the “Hello from the edge!” response, served by the worker without touching your origin.

curl -i https://www.example.com/hello

Wrap up

In this article, we have looked at how to set up a local development environment for Cloudflare Workers with Node.js, Yeoman and TypeScript, how to simulate the worker environment with node-fetch and unit test the handler, and how to bundle the worker with webpack and deploy it through the dashboard or the API. I really appreciate that you took the time to read this article. In the next article, I will walk you through the common worker patterns with examples, like modifying requests and responses, redirects, routing and URL normalization for caching.

Related Posts