Cloud and deployment · Beginner · 20 min
Build, test and deploy a Cloudflare Worker with Wrangler
By Padding · Updated 18 Nov 2026
Node.js 26.13 · Wrangler 4.168.0
You will have a small TypeScript API running on Cloudflare Workers, with a protected route, a passing Vitest suite, a secret set through a prompt, live logs and a tested way to roll back.
On this page
A Cloudflare Worker is a small program that runs on Cloudflare's network and answers HTTP requests. You do not rent a server or pick a region: you upload code, and Cloudflare runs it close to whoever sends the request. The code uses the same Fetch API as a browser, so a handler takes a Request and returns a Response.
Wrangler is Cloudflare's command-line tool for Workers. It runs your Worker on your own machine with workerd, the same open source runtime Cloudflare uses in production, so you can build and test everything before you have an account. In this tutorial you write a three-route API in TypeScript, run it locally, test it with Vitest, and only then sign in, deploy it, watch its logs and practise a rollback.
Everything up to the deploy step works without a Cloudflare account and, once the packages are installed, without much of a connection. If you pay for data by the gigabyte, run the install on a good connection once; the local server and the tests then run from the files on disk.
Step 1 · Create the project and install Wrangler
Make a throwaway project folder and an npm project inside it. The scripts give you short names for the commands you will run most:
mkdir -p ~/worker-demo
cd ~/worker-demo
npm init -y
npm pkg set type=module
npm pkg set scripts.dev="wrangler dev" scripts.test="vitest run" scripts.check="tsc --noEmit" scripts.deploy="wrangler deploy"Install Wrangler, the test tools and the TypeScript compiler as development dependencies, at exact versions. --save-exact writes 4.168.0 and not ^4.168.0 into package.json, so everyone who clones the project gets the same tools:
npm install --save-dev --save-exact wrangler@4.168.0 vitest@4.1.12 @cloudflare/vitest-plugin@1.9.2 typescript@7.0.2
npx wrangler --versionCloudflare also has an interactive starter, npm create cloudflare@latest, which asks questions and writes a template. Writing the files by hand here means you know what each one does.
Add a .gitignore now, before any secret exists. .wrangler is where Wrangler keeps local state, and .dev.vars will hold a local secret:
cat > .gitignore <<'EOF'
node_modules/
.wrangler/
.dev.vars*
.env*
EOFCheck it worked
npx wrangler --version prints 4.168.0. package.json lists the four packages under devDependencies with no ^ in front of their versions.
Step 2 · Write the Worker and its configuration
Wrangler reads its settings from wrangler.jsonc, which is JSON that allows comments. Create it:
cat > wrangler.jsonc <<'EOF'
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "hello-worker",
"main": "src/index.ts",
// Pins runtime behaviour. Move it forward on purpose, after testing.
"compatibility_date": "2026-11-20",
"observability": { "enabled": true },
"vars": {
"GREETING": "Hello from a Cloudflare Worker"
}
}
EOFnamebecomes the Worker's name in your account and part of its address.mainis the entry file. Wrangler bundles it, so TypeScript needs no separate build step.compatibility_datefixes which version of the runtime's behaviour your code gets. Cloudflare changes defaults over time, and a pinned date means a change only reaches you when you move the date yourself.observabilityturns on Workers Logs, soconsole.logoutput is kept in the dashboard as well as shown live.varsare plain, non-secret settings. The code reads them fromenv.
Now the Worker. It has three routes: / returns the greeting as text, /api/hello greets a name from the query string, and /api/notes accepts JSON in a POST, but only with the right bearer token:
mkdir -p src
cat > src/index.ts <<'EOF'
const json = (data: unknown, status = 200, headers: HeadersInit = {}): Response =>
Response.json(data, { status, headers });
const methodNotAllowed = (allowed: string): Response =>
json({ error: "method not allowed" }, 405, { Allow: allowed });
// Compare in constant time, so the response time does not leak the token.
function hasToken(request: Request, token: string): boolean {
const encoder = new TextEncoder();
const given = encoder.encode(request.headers.get("Authorization") ?? "");
const expected = encoder.encode(`Bearer ${token}`);
if (given.byteLength !== expected.byteLength) return false;
return crypto.subtle.timingSafeEqual(given, expected);
}
export default {
async fetch(request, env): Promise<Response> {
const url = new URL(request.url);
if (url.pathname === "/") {
return new Response(`${env.GREETING}\n`, {
headers: { "Content-Type": "text/plain; charset=utf-8" },
});
}
if (url.pathname === "/api/hello") {
if (request.method !== "GET") return methodNotAllowed("GET");
const name = (url.searchParams.get("name") ?? "world").slice(0, 40);
return json({ message: `Hello, ${name}` });
}
if (url.pathname === "/api/notes") {
if (request.method !== "POST") return methodNotAllowed("POST");
if (!env.API_TOKEN) return json({ error: "server not configured" }, 500);
if (!hasToken(request, env.API_TOKEN)) return json({ error: "unauthorised" }, 401);
let body: unknown;
try {
body = await request.json();
} catch {
return json({ error: "send JSON" }, 400);
}
const text =
typeof body === "object" && body !== null && "text" in body && typeof body.text === "string"
? body.text
: null;
if (text === null) return json({ error: 'send {"text": "..."}' }, 400);
console.log("note received", { length: text.length });
return json({ received: text, length: text.length }, 201);
}
return json({ error: "not found" }, 404);
},
} satisfies ExportedHandler<Env>;
EOFA few details worth knowing:
satisfies ExportedHandler<Env>lets TypeScript check the handler's shape and infer the types ofrequestandenvwithout you writing them out.Response.json()serialises the data and setsContent-Type: application/jsonfor you.crypto.subtle.timingSafeEqualis a Workers addition to the standard Web Crypto API. A plain===comparison can return sooner the earlier the strings differ, which in theory lets an attacker guess a token one character at a time.- The handler never contains the token. It reads
env.API_TOKEN, which comes from a local file now and from Cloudflare's secret store after you deploy.
Check it worked
ls shows wrangler.jsonc, src/index.ts, package.json and node_modules. Your editor may underline Env and ExportedHandler as unknown names. The next step generates those types.
Step 3 · Add a local secret and generate types
For local development, Wrangler reads secrets from a .dev.vars file next to wrangler.jsonc. Generate a random token into it. The umask 077 inside the brackets makes the file readable only by you from the moment it is created:
(umask 077; node -e 'console.log("API_TOKEN=" + require("crypto").randomBytes(24).toString("hex"))' > .dev.vars)
ls -l .dev.varsCloudflare's documentation says to use either .dev.vars or a .env file, not both: when .dev.vars exists, .env values are not loaded. The .gitignore you wrote already excludes both.
Now ask Wrangler to write the type definitions. It reads wrangler.jsonc and .dev.vars, and writes worker-configuration.d.ts, which describes the runtime (Request, crypto and the rest, for your compatibility date) and an Env interface with GREETING and API_TOKEN:
npx wrangler typesTell the TypeScript compiler to check src against those types and nothing else:
cat > tsconfig.json <<'EOF'
{
"compilerOptions": {
"target": "es2024",
"lib": ["es2024"],
"module": "es2022",
"moduleResolution": "bundler",
"types": [],
"strict": true,
"noEmit": true,
"isolatedModules": true,
"skipLibCheck": true
},
"include": ["worker-configuration.d.ts", "src/**/*.ts"]
}
EOF
npm run check"types": [] stops TypeScript loading any Node.js type packages, because a Worker does not run in Node.js. Run npx wrangler types again whenever you add a variable, a secret or a binding.
Check it worked
ls -l .dev.vars shows -rw-------, and npm run check finishes with no errors. Open worker-configuration.d.ts and search for API_TOKEN: it is listed as a string.
Step 4 · Run the Worker locally
Start the local server in your second terminal, from ~/worker-demo, and leave it running:
npm run devWrangler prints the bindings it found (GREETING and API_TOKEN, with the secret's value hidden), then something like Ready on http://localhost:8787. It reloads the Worker each time you save a file. Back in your first terminal, call the two public routes:
curl -s http://localhost:8787/
curl -s -G --data-urlencode "name=Ṣadé" http://localhost:8787/api/hello--data-urlencode with -G puts the name in the query string, percent-encoded, so letters outside English such as the Yoruba Ṣ and é arrive intact. Try a name in your own language.
Now the protected route. The first call sends no token. The second reads the token from .dev.vars into a shell variable and passes the header to curl on standard input with -H @-, so the token does not appear in the command line that other users of the machine can see in a process list:
curl -s -o /dev/null -w '%{http_code}\n' -X POST http://localhost:8787/api/notes --data '{"text":"hi"}'
TOKEN="$(sed -n 's/^API_TOKEN=//p' .dev.vars)"
printf 'Authorization: Bearer %s\n' "$TOKEN" | curl -s -H @- -H 'Content-Type: application/json' --data '{"text":"Buy a data bundle"}' http://localhost:8787/api/notesCheck it worked
The first two commands print Hello from a Cloudflare Worker and {"message":"Hello, Ṣadé"}. The unauthenticated POST prints 401, and the one with the token prints {"received":"Buy a data bundle","length":17}. In the second terminal, Wrangler shows each request and the note received log line.
Troubleshooting
If curl says the connection was refused, the server is not running or is still starting: check the second terminal. If something else already uses port 8787, start Wrangler with npm run dev -- --port 8788 and change the port in the commands. If the token call returns 500 server not configured, .dev.vars is missing or the server started before you created it; stop it with Ctrl+C and start it again.
Step 5 · Test the Worker with Vitest
Manual curl calls prove it works today. Tests prove it still works after the next change. Cloudflare's Vitest plugin runs your tests inside workerd, so they see the same runtime and the same env as the real Worker. Configure it to read wrangler.jsonc, and give the tests their own token so they never depend on your .dev.vars:
cat > vitest.config.ts <<'EOF'
import { cloudflareTest } from "@cloudflare/vitest-plugin";
import { defineConfig } from "vitest/config";
export default defineConfig({
plugins: [
cloudflareTest({
wrangler: { configPath: "./wrangler.jsonc" },
miniflare: { bindings: { API_TOKEN: "test-token" } },
}),
],
});
EOFValues under miniflare override the ones from the Wrangler file, so inside the tests env.API_TOKEN is test-token. Now write the tests. Each one builds a Request, hands it to the Worker's fetch handler with the test env, and checks the Response:
mkdir -p test
cat > test/index.test.ts <<'EOF'
import { createExecutionContext, waitOnExecutionContext } from "cloudflare:test";
import { env } from "cloudflare:workers";
import { describe, expect, it } from "vitest";
import worker from "../src/index";
async function call(path: string, init?: RequestInit): Promise<Response> {
const request = new Request(`http://example.com${path}`, init);
const ctx = createExecutionContext();
const response = await worker.fetch(request, env, ctx);
await waitOnExecutionContext(ctx);
return response;
}
const post = (body: string, token?: string): RequestInit => ({
method: "POST",
headers: token ? { Authorization: `Bearer ${token}` } : {},
body,
});
describe("hello-worker", () => {
it("returns the greeting at /", async () => {
const response = await call("/");
expect(response.status).toBe(200);
expect(await response.text()).toBe("Hello from a Cloudflare Worker\n");
});
it("greets a name with non-English letters", async () => {
const response = await call(`/api/hello?name=${encodeURIComponent("Ṣadé")}`);
expect(await response.json()).toEqual({ message: "Hello, Ṣadé" });
});
it("rejects a note without a token", async () => {
const response = await call("/api/notes", post('{"text":"hi"}'));
expect(response.status).toBe(401);
});
it("rejects a note with the wrong token", async () => {
const response = await call("/api/notes", post('{"text":"hi"}', "wrong-token"));
expect(response.status).toBe(401);
});
it("accepts a note with the right token", async () => {
const response = await call("/api/notes", post('{"text":"Buy a data bundle"}', "test-token"));
expect(response.status).toBe(201);
expect(await response.json()).toEqual({ received: "Buy a data bundle", length: 17 });
});
it("answers 405 with an Allow header for the wrong method", async () => {
const response = await call("/api/notes");
expect(response.status).toBe(405);
expect(response.headers.get("Allow")).toBe("POST");
});
it("returns 404 for unknown paths", async () => {
const response = await call("/nope");
expect(response.status).toBe(404);
});
});
EOF
npm testcreateExecutionContext stands in for the ctx argument Cloudflare passes to every request, and waitOnExecutionContext waits for any background work started with ctx.waitUntil() before the checks run. This Worker starts none, but the pattern is the same when yours does.
Check it worked
Vitest lists seven tests under hello-worker and ends with 7 passed. To see a failure, change the expected greeting in the first test, run npm test again, read the difference Vitest prints, and change it back.
Step 6 · Sign in, deploy and set the production secret
Stop the local server in the second terminal with Ctrl+C. From here on you need a Cloudflare account. Sign in; this opens a browser where you allow Wrangler to use your account:
npx wrangler login
npx wrangler whoamiIn a CI job there is no browser. Use an API token in the CLOUDFLARE_API_TOKEN environment variable, stored in the CI system's secret store; the tutorial on deploying a Worker from GitHub Actions covers that.
Run the checks, then deploy:
npm run check
npm test
npm run deployWrangler uploads the bundle and prints the Worker's address, in the form https://hello-worker.<your-subdomain>.workers.dev. The .dev.vars file is not uploaded, so at this point /api/notes answers 500 server not configured. That is the safe failure the code was written for.
Make a new random token for production. Do not reuse the local one. Copy the output into your password manager:
node -e 'console.log(require("crypto").randomBytes(32).toString("hex"))'Then store it as a secret. Wrangler prompts for the value, so it never appears in your shell history; paste it at the prompt:
npx wrangler secret put API_TOKENSetting a secret creates a new version of the Worker and deploys it straight away. Secrets are encrypted and cannot be read back, from the dashboard or from Wrangler. Call the deployed Worker, replacing the address with the one deploy printed. read -rs asks for the token without showing it on screen, in both bash and zsh:
curl -s https://hello-worker.<your-subdomain>.workers.dev/
printf 'Token: '; read -rs TOKEN; echo
printf 'Authorization: Bearer %s\n' "$TOKEN" | curl -s -H @- --data '{"text":"from production"}' https://hello-worker.<your-subdomain>.workers.dev/api/notesCheck it worked
The first call prints the greeting, and the second prints {"received":"from production","length":15}. A call with no token, or with your local token, gets 401.
Step 7 · Watch live logs
wrangler tail streams logs from the deployed Worker to your terminal: each request, anything it writes with console.log, and uncaught exceptions. Start it in the second terminal:
npx wrangler tail hello-worker --format prettySend the authenticated POST from the previous step again in your first terminal. Stop the tail with Ctrl+C when you are done. On a busy Worker the tail can switch to sampling and drop some messages; --status error, --method POST or --search "note received" cut the volume down to what you need. Because observability is on, the same lines are also kept under the Worker's logs in the Cloudflare dashboard for a few days.
Check it worked
The tail shows a line for POST /api/notes with its status, then something like the note received log line with a length of 15. The token is not in the log, because the code never logs headers.
Step 8 · Deploy a change and roll it back
Every deploy and every secret change creates a version. Make a visible change, deploy it, and then undo it. Edit wrangler.jsonc and change the GREETING value to Hello from version two. Then:
npm run deploy
curl -s https://hello-worker.<your-subdomain>.workers.dev/
npx wrangler deployments listThe greeting is now Hello from version two, and the deployments list shows the most recent deployments, each with the version it serves. To go back:
npx wrangler rollbackWith no version ID, rollback picks the version uploaded before the latest one, here the one created by wrangler secret put. It asks you to confirm and for an optional message. To pick a different one, run npx wrangler versions list, copy its ID and pass it: npx wrangler rollback <version-id>. A rollback takes effect on every route at once and does not touch your local files, so change wrangler.jsonc back too, or your next deploy brings version two back.
Check it worked
curl on the address prints Hello from a Cloudflare Worker again, and npx wrangler deployments list shows a new deployment at the top for the rollback.
Step 9 · Know the limits and clean up
At the time of writing (checked November 2026), the Workers Free plan allows 100,000 requests a day across your account, reset at midnight UTC, and 10 milliseconds of CPU time per request. Over the daily limit, Cloudflare answers with Error 1027 until the reset. CPU time does not include time spent waiting on network calls, and most small APIs use far less than 10 ms. Read Cloudflare's limits and pricing pages before you depend on those numbers, as they change.
Delete the deployed Worker when you no longer need it. This removes it and its address permanently, so check the name first:
npx wrangler delete hello-worker
npx wrangler logoutThen remove the local project, including .dev.vars:
cd ~
rm -rf ~/worker-demoCheck it worked
ls ~/worker-demo reports that the folder does not exist, and the Worker no longer appears in your Cloudflare dashboard's list of Workers.
Next steps
- Store and serve uploads from this kind of Worker: store files in Cloudflare R2 from a Worker.
- Run code on a timer instead of on a request: run scheduled jobs with Cloudflare Workers cron triggers.
- Deploy on every push, with the tests as a gate: deploy a Cloudflare Worker from GitHub Actions.
- Serve a plain static site instead: host a static site on Cloudflare Pages.
Related tutorials
- Tag cloud resources so you know what costs whatYou will have a four-key tagging scheme applied to every AWS resource through Terraform default_tags, a script that lists resources missing a tag, a tag policy ready for your organisation and cost allocation tags that split the bill by project.
- Store and serve files with Cloudflare R2 from a WorkerYou will build a Worker that uploads, downloads and lists files in an R2 bucket, with a size limit, a content-type allowlist, ETag and range support and a bearer token, test it locally with Wrangler and Vitest, and reach the same bucket through R2's S3-compatible API.
- Store container images in Amazon ECR with scanning and lifecycle policiesYou will have a private Amazon ECR repository with immutable tags and scan on push, an nginx image copied into it with crane, its vulnerability findings read from the CLI, a lifecycle policy that keeps the ten newest tagged images, and pull access granted to a second AWS account.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials