A Cloudflare Workers-based serverless demo.
This project is implemented in TypeScript and uses Cloudflare Wrangler (via npm).
To understand the behavior, see the code in 👉src/index.ts.
Node.js Development Setup
We'll install a recent version of Node.js using nvm.
-
Install nvm using Git:
cd ~/ git clone https://github.com/nvm-sh/nvm.git .nvm cd ~/.nvm git checkout v0.39.7
-
Add the following at the end of your
~/.bashrc
:### # nvm # source: https://github.com/nvm-sh/nvm#git-install ### export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion
-
Restart your terminal. Verify nvm works (should print something like
0.39.7
):nvm -v
-
Install the latest Node.js 20:
nvm install 20.*
-
Verify Node.js is installed and active (should print something like
v20.10.0
):node -v
-
Upgrade the bundled npm:
npm --global install npm
-
Check the installed npm version:
npm -v
That's all!
First, install the dependencies using npm:
npm install
Then, you can run the worker locally using:
npm run dev
There is one variable (build-time definition) MODE
that affects the worker execution.
It can be set in wrangler.toml
and also using CLI flags (which take precedence):
npm run dev -- --define --define "MODE:'development'"
This section describes the available commands that you can use during the development process.
Refer to the package.json scripts section to see the underlying commands.
In order to pass additional arguments to the scripts invoked using npm run
, an extra --
is needed, otherwise,
npm won't pass the arguments correctly.
If you want to pass different arguments, you can use the command directly (but you might need to use the full name for
the Node.js executables, e.g. wrangler
-> ./node_modules/.bin/wrangler
or use npx
).
See also the documentation for the Wrangler commands.
-
npm run dev
- This runs the worker locally usingwrangler dev
. It auto-restarts anytime you make a change in the source code or config. This way you can test your changes in real-time. -
npm run deploy
- Once you're satisfied with your changes, you can deploy them to the live environment. This command uses thewrangler deploy
to publish your Cloudflare Worker. -
npm run format
- Formats the code using Prettier (prettier . --write
). -
npm run check-format
- Checks if all the code is correctly formatted with Prettier (prettier . --check
). -
npm run lint
– Runs ESLint. Outputs errors to console. See the ESLint config. -
npm run test
- Runs the tests written in Jest (jest
). -
npm run tsc
- Runs the TypeScript compiler (tsc
) that check the types and outputs any type errors to console.
❗️Make sure, that the Cloudflare account you're deploying to has access to the custom domain defined
in the routes
field in the wrangler.toml
.
npm run deploy
See the documentation for wrangler deploy
.