valfz

Workers from first principles

Configuration and bindings

Declare text, JSON and secret bindings in cloudflare.config.ts, protect link creation with a token, and vary values by mode.

lesson
04 of 08
read
11 min

The code from lesson 3 has its settings baked in, and anyone who can reach the Worker can create links. A Worker receives configuration through env, and every property on env is a binding declared in cloudflare.config.ts. This lesson declares a text value, a JSON value and a secret, uses the secret to protect POST /api/links, and then makes one value depend on the mode the Worker is built in.

Declare the bindings

Replace the env block in the configuration. The whole file is now:

cloudflare.config.ts
import { bindings, defineConfig } from "cf/config";
import * as entrypoint from "./src/index.ts" with { type: "cf-worker" };

export default defineConfig({
	worker: {
		name: "shortlinks",
		compatibilityDate: "2026-11-23",
		entrypoint,
		env: {
			PUBLIC_ORIGIN: bindings.text("http://localhost:8791"),
			LIMITS: bindings.json({ codeLength: 6, maxUrlLength: 2048 }),
			ADMIN_TOKEN: bindings.secret(),
		},
	},
});

Each key becomes a property on env, and the builder decides its type. For resources such as the KV namespace in the next lesson, the binding is an object with methods. No hostname or API key for that resource appears in your code, and the Worker can reach only what its configuration lists.

bindings.text() is a string. PUBLIC_ORIGIN is the origin used in short URLs. Lesson 3 derived it from the request, which means whatever hostname the client happened to use. A deployed Worker can be reachable under more than one hostname, and the links it hands out should always use the same one.

bindings.json() is any JSON value and arrives already parsed.

bindings.secret() declares that a secret with this name must exist. The value is not in the file.

Text and JSON values sit in your repository and in the build output in plain text, so they must never hold anything sensitive. The limits page allows 64 variables per Worker on the Free plan and 128 on Paid, each up to 5 KB.

If the dev server is running when you save, it restarts and prints a warning about the secret:

Missing required secrets for Worker "shortlinks": ADMIN_TOKEN. Add them to one of `.dev.vars.development`, `.dev.vars`, `.env.development.local`, `.env.development`, `.env.local`, or `.env`. Alternatively, set them as environment variables.

Leave it for a moment.

Check the token

src/auth.ts
import { HttpError } from "./http.ts";

export async function requireToken(request: Request, expected: string): Promise<void> {
	// An unset secret is undefined at runtime, whatever the types say. Fail closed.
	if (!expected) throw new Error("ADMIN_TOKEN is not configured");

	const header = request.headers.get("Authorization") ?? "";
	const presented = header.startsWith("Bearer ") ? header.slice("Bearer ".length) : "";
	if (!(await sameSecret(presented, expected))) {
		throw new HttpError(401, "missing or invalid token", { "WWW-Authenticate": "Bearer" });
	}
}

// Hash both values first so the buffers have equal length, then compare them
// in constant time. A plain === returns at the first differing character.
async function sameSecret(a: string, b: string): Promise<boolean> {
	const encoder = new TextEncoder();
	const [digestA, digestB] = await Promise.all([
		crypto.subtle.digest("SHA-256", encoder.encode(a)),
		crypto.subtle.digest("SHA-256", encoder.encode(b)),
	]);
	return crypto.subtle.timingSafeEqual(digestA, digestB);
}

The client sends Authorization: Bearer <token>. A missing or wrong token gets a 401 with a WWW-Authenticate header naming the scheme.

Comparing secrets with === stops at the first differing character, so response times can reveal how much of a guess was right. crypto.subtle.timingSafeEqual() is a Workers addition to Web Crypto that compares two buffers of equal length in constant time. Hashing both strings first guarantees the equal length whatever the client sent. Cloudflare’s timingSafeEqual example shows another way to handle the length.

The guard at the top of requireToken matters more than it looks. The generated type of env.ADMIN_TOKEN is string, but when no value has been provided the property is undefined at runtime. Without the guard, both sides of the comparison would be the hash of an empty input, and a request with no Authorization header at all would be accepted. During testing of this lesson that request returned 201. An authentication check must fail closed when its own configuration is missing.

Use the bindings

src/index.ts
@@ -1,3 +1,4 @@
+import { requireToken } from "./auth.ts";
 import { HttpError, readJsonObject } from "./http.ts";
 import { getLink, newCode, saveLink } from "./links.ts";
 
@@ -46,16 +47,17 @@
 	throw new HttpError(404, "not found");
 }
 
-async function postLink({ request }: RouteArgs): Promise<Response> {
+async function postLink({ request, env }: RouteArgs): Promise<Response> {
+	await requireToken(request, env.ADMIN_TOKEN);
 	const body = await readJsonObject(request);
-	const target = parseTarget(body.url);
+	const target = parseTarget(body.url, env.LIMITS.maxUrlLength);
 
-	const code = newCode();
+	const code = newCode(env.LIMITS.codeLength);
 	const link = { url: target.href, createdAt: new Date().toISOString() };
 	saveLink(code, link);
 
 	return Response.json(
-		{ code, ...link, short: new URL(`/${code}`, request.url).href },
+		{ code, ...link, short: new URL(`/${code}`, env.PUBLIC_ORIGIN).href },
 		{ status: 201, headers: { Location: `/api/links/${code}` } },
 	);
 }
@@ -73,10 +75,13 @@
 	return Response.redirect(link.url, 302);
 }
 
-function parseTarget(value: unknown): URL {
+function parseTarget(value: unknown, maxLength: number): URL {
 	if (typeof value !== "string" || !URL.canParse(value)) {
 		throw new HttpError(400, "url must be an absolute URL");
 	}
+	if (value.length > maxLength) {
+		throw new HttpError(400, `url must be at most ${maxLength} characters`);
+	}
 	const target = new URL(value);
 	if (target.protocol !== "http:" && target.protocol !== "https:") {
 		throw new HttpError(400, "url must use http or https");

postLink now destructures env from its argument. Nothing else in the route table changes, which is what the single-object signature was for.

Provide the secret locally

Try to create a link before the secret exists:

curl -i -X POST http://localhost:8791/api/links -d '{"url":"https://example.com/a"}'
HTTP/1.1 500 Internal Server Error
...

{"error":"internal error"}

The guard threw and the error boundary logged it. The client learns only that the request failed. Local values for secrets go in a file named .dev.vars next to the configuration, in dotenv syntax:

.dev.vars
ADMIN_TOKEN=local-dev-token

The generated .gitignore already excludes .dev.vars*. The dev server restarts when the file appears. The same request now gets a proper refusal:

HTTP/1.1 401 Unauthorized
...
www-authenticate: Bearer
...

{"error":"missing or invalid token"}

With the token it succeeds:

curl -X POST http://localhost:8791/api/links -H 'Authorization: Bearer local-dev-token' -d '{"url":"https://example.com/a"}'
{"code":"29x3tr","url":"https://example.com/a","createdAt":"2026-11-28T22:10:47.832Z","short":"http://localhost:8791/29x3tr"}

.dev.vars only exists on your machine. The production value is stored on the deployed Worker, which lesson 8 covers.

Types follow the configuration

env.LIMITS.codeLength type-checked without you writing an Env interface. The generated file .cloudflare/types/index.d.ts starts like this:

.cloudflare/types/index.d.ts
type __Config = import("cf/config").UnwrapConfig<typeof import("../../cloudflare.config").default>;
type __WorkerConfig = import("cf/config").UnwrapConfig<__Config["worker"]>;
type __Env = import("cf/config").InferEnv<__WorkerConfig>;

Env is computed from the type of your configuration’s default export. A binding you add is visible to the type checker as soon as the configuration is saved. cf workers types rewrites this file, which also contains the runtime’s own type definitions. Run it, or pnpm check, after changing the compatibility date or upgrading the tools.

Misspell a property to see the check work, for example env.LIMITS.codeLenght in postLink:

pnpm typecheck
...
x typescript(TS2551): Property 'codeLenght' does not exist on type '{ codeLength: number; maxUrlLength: number; }'. Did you mean 'codeLength'?
    ,-[src/index.ts:55:34]
 54 | 
 55 |     const code = newCode(env.LIMITS.codeLenght);
    :                                     ^^^^^^^^^^
 56 |     const link = { url: target.href, createdAt: new Date().toISOString() };
    `----
...

Fix the typo before moving on.

Modes

http://localhost:8791 is the wrong origin for a deployed Worker. defineConfig also accepts a function, which receives the mode the configuration is being evaluated for:

cloudflare.config.ts
import { bindings, defineConfig } from "cf/config";
import * as entrypoint from "./src/index.ts" with { type: "cf-worker" };

export default defineConfig(({ mode }) => ({
	worker: {
		name: "shortlinks",
		compatibilityDate: "2026-11-23",
		entrypoint,
		env: {
			PUBLIC_ORIGIN: bindings.text(
				mode === "production" ? "https://go.example.com" : "http://localhost:8791",
			),
			LIMITS: bindings.json({ codeLength: 6, maxUrlLength: 2048 }),
			ADMIN_TOKEN: bindings.secret(),
		},
	},
}));

The mode is development under cf dev, production under cf build and cf deploy, and test when the tests run. --mode overrides it. Stop the dev server and start it in production mode to see the other branch:

pnpm exec cf dev --mode production --port 8791
curl -X POST http://localhost:8791/api/links -H 'Authorization: Bearer local-dev-token' -d '{"url":"https://example.com/a"}'
{"code":"grzmch","url":"https://example.com/a","createdAt":"2026-11-28T22:10:58.588Z","short":"https://go.example.com/grzmch"}

go.example.com is a placeholder until lesson 8 attaches a real domain. Restart the dev server without --mode before continuing.

Two rules from the configuration reference are worth knowing now. The function must return one complete configuration for each mode, because nothing is merged or inherited between modes. And a mode deploys a separate Worker only if it returns a different name. For local secrets, a file named .dev.vars.<mode> replaces .dev.vars when it exists.

pnpm test still passes, because the route the test exercises does not ask for the token.

The project now has configuration, but its links still vanish with the isolate. Lesson 5 moves them into KV.

Exercises

  1. Add blockedHosts: ["localhost", "127.0.0.1"] to LIMITS and reject target URLs whose hostname is in the list. The result is correct when a POST with http://localhost/x returns 400 with a message of your choosing, other URLs still return 201, and pnpm check passes.
  2. Add a staging mode whose origin is https://staging.go.example.com. After pnpm exec cf dev --mode staging --port 8791, a created link’s short field should start with that origin, and the default mode should still produce http://localhost:8791.
  3. See the failure the guard prevents. Rename .dev.vars so the secret is missing, then send the POST without an Authorization header: you should get a 500. Now delete the guard line in src/auth.ts and repeat: the same request returns 201. Put both back.

keyboard

h
home
w c a
writing, courses, about
n p
next and previous lesson
j k
scroll down and up
g G
top and bottom of the page
t
switch light and dark
?
this help

shortcuts are