🔨
Deploying a CloudFlare Worker

Tools to install

First, install nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash
Then, install npm with nvm. If you don't do this, will be really hard to install the other tools
nvm install node
Afterwards, install wrangler
sudo -H npm i @cloudflare/wrangler -g
Next, login to Cloudflare to authenticate with wrangler
wrangler login

Creating a worker

Initiating the worker

First, initiate a worker. The command below creates a new directory and initiates a dummy project
wrangler generate $NAME [$TEMPLATE] [--type=$TYPE] [--site]
$NAME is the name of the workers project. Both the name of the directory and the name property in the wrangler.toml config file
 

Adding data to your KV namespace

First, create a namespace through the web view.
 
When you have the id of the namespace, add it to the wrangler.toml file in the format below
kv-namespaces = [
  {binding = "BINDING_1", id = "ID_1"},
  {binding = "BINDING_2", id = "ID_2"},
  ...
]
 
Also create a preview namespace, so you can test it out on local dev
wrangler kv:namespace create "BINDING_1" --preview
 
And then add the generated PREVIEW_ID to wrangler.toml too
kv-namespaces = [
  {binding = "BINDING_1", preview_id = "PREVIEW_ID_1", id = "ID_1"},
  {binding = "BINDING_2", preview_id = "PREVIEW_ID", id = "ID_2"},
  ...
]
 
To do a bulk upload of data, use the following
wrangler kv:bulk put --binding=BINDING_NAME FILENAME
Where FILENAME is a JSON file that contains the data in the [{key: value}, {key: value}, ... ] format
 
And to put the same file in the preview namespace
wrangler kv:bulk put --binding=BINDING_NAME --preview FILENAME

Testing out the code

wrangler dev #starts a local server
To test out whether it works, run the following codeblock in python
import requests
url = 'http://127.0.0.1:8787'
r = requests.get(url, json=JSON_PAYLOAD)
r.content #shows the value returned. Can also run r.json()

Publishing the code in production

wrangler publish

Looking at production logs

You can use wrangler tail to look at logs in real-time. But before that, cloudflared must be installed. To install it, just run
curl https://bin.equinox.io/c/VdrWdbjqyF/cloudflared-stable-darwin-amd64.tgz | tar xzC /usr/local/bin