Get to Know Cloudflare — Workers

What is Workers — enabling serverless functions to run as close as possible to the end user. In essence, the serverless code itself is ‘cached’ on the network.

Thanks all, you could found another topic of Cloudflare Workers from this referral: Get to Know Cloudflare — Workers Series

Cloudflare Workers Logo

Workers could be used by user interface via Cloudflare console, to be better implement workers. Then ‘Wrangler’ is workers cli that let us create, test, and deploy Workers to Cloudflare.

Setup Workers

  • Prerequisite
  • Install/Update Wrangler

Build Workers App

  • Create Project
  • Run Project
  • Write Code
  • Deploy Project
  • Write Tests

Setup Workers

Prerequisite

  • before going through Workers, required as a Node.js and npm must be installed.
# let's check node exists
node --version
v18.16.0
# let's check node exists
npm --version
9.5.1

Install/Update Wrangler

# with locally
npm install wrangler
npm update wrangler
...

# with globally
npm install -g wrangler
npm update -g wrangler
...

# let's check wrangler version
wrangler --version
⛅️ wrangler 3.1.0 (update available 3.1.2)
...

Let’s Build Worker App

Create Project

  • To create a new Javascript “Hello World” worker:
npm create cloudflare@latest hello-world -- --type hello-world --no-ts
  • To create a new Typescript “Hello World” worker:
    (I created this option)
npm create cloudflare@latest hello-world -- --type hello-world --ts
  • The project will look like

hello-world (project)
|-src/index.ts
|-wrangler.toml

Run Project

  • To run in localhost when already created a project with Wrangler command:
cd hello-world/
wrangler dev
  • Go to http://localhost:8787 to see your Worker running. Any changes you make to your code will trigger a rebuild, and reloading.

Write Code

  • Find the src/index.ts file will be put code below:
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
return new Response('Hello World!');
}
}

Go to http://localhost:8787, You’ll see.

Hello World!

This code block consists of four parts:

  1. The export statement: export default
    export default is JavaScript syntax required for defining JavaScript modulesOpen external link. Your Worker has to have a default export of an object, with properties corresponding to the events your Worker should handle.
  2. The event handler: async fetch(request)
    This event handler will be called when your Worker receives a fetch event. You can define additional event handlers in the exported object to respond to different types of events. For example, add an async scheduled(event) {} function definition to respond to scheduled events.
  3. Parameters: request, env, context
    The fetch event handler will always get three parameters passed into it: request, env, and context.
  4. The Response object: return new Response("Hello World!");
    The Workers runtime expects fetch events to return a Response object. In this example, you will return a new Response with the string "Hello World!".
  5. To review code changes in real-time, rewrite the "Hello World!" string to "Hello Worker!" and, with wrangler dev running, save your changes.
  6. Go to http://localhost:8787, You’ll see

Hello Worker!

Deploy Project

To deploy, wrangler will publish to set one up with Wrangler command:

wrangler deploy

hello-world.<your-site>.worker.dev

Write tests

One way to do this is with the unstable_dev API in Wrangler. unstable_dev is used for writing integration and end-to-end tests.

import { unstable_dev } from "wrangler";
describe("Worker", () => {
let worker: any; // Add the type for the worker variable
beforeAll(async () => {
worker = await unstable_dev("index.ts", {
experimental: { disableExperimentalWarning: true },
});
});
afterAll(async () => {
await worker.stop();
});
it("should return Hello World", async () => {
const resp = await worker.fetch();
if (resp) {
const text: string = await resp.text(); // Add the type for the text variable
expect(text).toMatchInlineSnapshot(`"Hello Worker!"`);
}
});
});

--

--

Chutipon Pongpanit (Aof)
EarthSeaTech - Software Engineering

Aoftionstyle idea here #idea is anything happen faster speed of light then captured in the chest. no ✔ no ✘ just Casually open chest beacause world need you