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.
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:
- What is Cloudflare Worker and why do we need it?
- How to set up a local development environment for Cloudflare Workers? (this article)
- How to write Cloudflare Workers? Common patterns with examples
- Cloudflare Workers use cases and lessons learned
TL;DR Summary
- Use Node.js, npm, Yeoman and the
generator-node-typescriptgenerator to scaffold a TypeScript project for the worker. - Install
node-fetchand its type declarations to simulatefetch,Request,ResponseandHeadersin 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,
- Write the request handling logic as a plain function: it takes a
Requestand returns aResponse. - Keep the worker-specific part (the
fetchevent listener) in a very small entry file. - In the unit tests, provide
fetch,Request,ResponseandHeadersfrom thenode-fetchpackage, so the same handler runs in Node.js. - 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.
-
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 -
Create a directory with any name. For demonstration, I will name it
myfirstworker.mkdir myfirstworker cd myfirstworker -
Install the TypeScript generator for Node.js with the following command.
npm install generator-node-typescript -g -
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-typescriptThe generator scaffolds a TypeScript project with a
srcfolder for the code, atestfolder for the unit tests, atsconfig.jsonfile and the npm scripts to build and test the project. Open the generatedpackage.jsonto see the scripts and the test framework it uses. -
Install the
node-fetchpackage and its type declarations.node-fetchbrings the browserfetchAPI 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 -
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 -
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
-
Make sure the
libsetting intsconfig.jsonincludesdom, so TypeScript knows the types offetch,Request,Response,HeadersandURL.\{ "compilerOptions": \{ "target": "es2017", "module": "commonjs", "lib": ["es2017", "dom"], "strict": true } } -
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); } -
Create the worker entry file in
src/index.ts. It only connects thefetchevent 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
-
Create
test/setup.tsto simulate the worker environment. It puts thenode-fetchclasses 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; -
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!'); }); }); -
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.
-
Create
webpack.config.jsin 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') } }; -
Bundle the worker. It creates
dist/worker.js, and this is the file we deploy.npx webpack
Note: Don’t bundle
node-fetchor any other Node.js-only package into the worker. The worker runtime already hasfetch,RequestandResponse;node-fetchis only for the tests.
Steps to deploy the worker
Option 1: Cloudflare dashboard
- Login to the Cloudflare dashboard and select your zone.
- Open the Workers app and launch the editor.
- Replace the script with the content of
dist/worker.js. - Use the preview and testing panels in the editor to send a test request to
/hello. - Save and deploy the script.
- 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
Cloudflare Workers use cases and lessons learned - Part 4
Where Cloudflare Workers fit best, how a worker cut our origin requests by about 84%, and the lessons we learned running it in production.
How to write Cloudflare Workers? Common patterns with examples - Part 3
Common Cloudflare Worker patterns with examples: modify requests and responses, redirect and block at the edge, route to back-ends and handle origin failures.
What is Cloudflare Worker and why do we need it? - Part 1
Cloudflare Workers run our JavaScript at the edge. See what a worker is, how it works with routes, how it compares with page rules and when to use it.