geoffwilliams@home:~$

Deploy your own Cloudflare Workers

Lets make a Cloudflare Worker with Typescript.

Step 1: Setup Workstation

Install nodejs, then:

npm install -g wrangler
wrangler login

Step 2: Create a project

Create a new project in interactive mode, the template to use for typescript template is listed under resources and pointed to this github directory at time of writing:

npm create cloudflare@latest

Follow the prompts and a project directory will be created. From here:

  • run local: npm run start
  • deploy to cloudflare: npm run deploy

After deploying, the cloudflare worker ID will be shown in the terminal, so you can test with browser or curl. That’s it - your in business with typescript.

Bonus 1: Environment variables

  • dotenv won’t work
  • Environment variables are received as the env argument to fetch() - the entry point
  • Define your variables in wrangler.toml and they will be made available after npm run deploy. Neat!

Bonus 2: Secrets

  • Don’t put secrets in wrangler.toml
  • Secrets needed for dev can be put in .dev.vars. It’s already in .gitignore
  • Secrets won’t be deployed with npm run deploy, you need to deploy the secret separately, like this:
npx wrangler secret put SOME_SECRET_API_TOKEN

You will then be prompted in the terminal to enter the secret. More info

Conclusion

Cloudflare have come up with a seriously slick, easy to use AWS lambda-like experience with no cold starts and low/no costs. The wrangler tooling is impressive and gives you infrastructure-as-code out of the box.

Happy coding.

Post comment

Markdown is allowed, HTML is not. All comments are moderated.