Introduction about Workers

Before setup and running a worker, let's first understand what a worker is and is what speciality it holds in the current market of different cloud providers.

I always looked at Cloudflare as a company which provides some CDN service to companies and is abstract to generally public view. But boy, I was proven wrong when I came across the different cloud services offered by them. When we think of CLOUD the first company we think of is AWS and then Azure, GCP ect, now cloudflare has established itself as a developer friendly service with their focus on ease of usage. You will see what I meant by that when we deploy a worker in less that 5 min.

What exactly does Workers do?

Have you ever heard of AWS Lambda, yes it is exactly similar to Lambda but a lot better with developer friendly API, robust, fast (I mean really really fast).

Setup

The very first command you have to run in you console is

npm create cloudflare@latest

Not that the project has been created you can go ahead and open it in VS-Code or any other code editor.

image.png

The new structure will look like the above shown image. We will be mostly using src directory and wrangler.toml file.

index.js/ts

Currently Cloudflare Workers support Javascript, Typescript, and Python (beta). I suggest you use JS or TS until a stable version for Python is rolled out. This is the boilerplate code provided in index.ts

export default {
	async fetch(request, env, ctx): Promise<Response> {
		return new Response('Hello World!');
	},
} satisfies ExportedHandler<Env>;

Local vs Deploy

You can work with Workers in local as well until you develop and test you application/api.

Run locally

To run the Worker locally, just use the below command.

npm run dev