TutorialPart 613 min read

Cloudflare Workers KV: build a redirect service

Build a small Hono redirect service with Workers KV. Test it locally, understand stale reads and expiration, and learn when to choose KV, D1, or Durable Objects.

View as Markdown

You put a link in a newsletter. A month later, the page moves. You can fix your website, but you cannot edit the copies sitting in people’s inboxes.

A link you control, such as /go/cloudflare-d1, gives you a stable address to share. The service looks up its current destination and sends the browser there. When the article moves, you update the stored address.

Workers KV suits this kind of lookup: we know the key, need one small value, and expect far more visits than edits. It also comes with a condition we need to accept: after an update, some readers may temporarily reach the previous destination.

In part five, we used D1 to save drafts and protect them from conflicting edits. Here we’ll build a separate Hono service and manage its links with Wrangler. You can follow along without the earlier project.

When KV fits

For this service, a record is just two strings:

Key:    link:cloudflare-d1
Value:  https://omaralbeik.com/en/blog/series/cloudflare/understanding-cloudflare-d1

A namespace is a collection of these pairs. A binding gives the Worker access to that namespace as env.LINKS. The link: prefix is our naming convention; it is not a folder or a permissions boundary.

KV caches values across Cloudflare’s network as they are accessed. Frequently requested values can be served from a nearby cache. A lookup without a cached value—a cold read—may need to reach storage farther away. Calling put() does not immediately place a copy in every location.

That makes KV useful for lookup tables and application settings where a delay in seeing updates is acceptable. A bank balance, inventory reservation, or access decision that must reflect the latest change needs stronger guarantees. Cloudflare describes this behavior in How KV works.

For a few fixed redirects, rules in your site configuration may be enough. Here we want to change destinations independently of the Worker’s code. We’ll maintain a directory of article links ourselves; visitors will only be able to follow them.

FOLLOW ONE REQUEST

From short link to article

Follow a request to /go/cloudflare-d1 from the first lookup to the article.

  1. 01 · Reader → WorkerGET /go/cloudflare-d1

    Hono matches the route and validates the slug.

  2. 02 · Worker → KVget("link:cloudflare-d1")

    KV returns the destination for this key, or null if the lookup finds nothing.

  3. 03 · Worker → Reader302 + Location

    The Worker validates the destination and sends a temporary redirect with Cache-Control: no-store.

  4. 04 · Reader → DestinationGET /en/blog/…

    The browser follows the Location header and requests the article.

A missing key returns 404. An invalid destination or a failed lookup returns 503.

KV supplies the destination. The browser makes a separate request to open it; the Worker does not fetch the article on the reader's behalf.

Start with a local namespace

Use a Node.js version supported by Wrangler. In a new directory:

mkdir link-router
cd link-router
npm init -y
npm install hono@4
npm install -D wrangler@4 typescript
mkdir src

We’ll keep using Wrangler, as in the earlier articles. Create this configuration:

{
  "$schema": "node_modules/wrangler/config-schema.json",
  "name": "link-router",
  "main": "src/index.ts",
  "compatibility_date": "2026-11-30",
  "compatibility_flags": ["nodejs_compat"],
  "upload_source_maps": true,
  "observability": { "enabled": true },
  "kv_namespaces": [
    {
      "binding": "LINKS",
      "id": "00000000000000000000000000000000"
    }
  ]
}

The all-zero ID is a placeholder for local development. We haven’t created a remote namespace. With local bindings, Wrangler keeps the data under .wrangler/state; restarting the server preserves it. Add node_modules/, .wrangler/, and .dev.vars* to .gitignore.

Generate the binding types:

npx wrangler types

Add a TypeScript configuration so the editor and compiler can find them:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "lib": ["ES2022"],
    "types": ["./worker-configuration.d.ts"],
    "strict": true,
    "skipLibCheck": true,
    "noEmit": true
  },
  "include": ["src/**/*.ts", "worker-configuration.d.ts"]
}

Read one key and return a redirect

The route accepts a slug such as cloudflare-d1, reads its destination, and returns a 302. We allow lowercase letters, numbers, and hyphens between them, up to 64 characters. Destinations must be HTTPS blog pages on this site. Replace the origin and allowed paths when adapting the example for your own site.

import { Hono } from "hono";

const app = new Hono<{ Bindings: Env }>();
const slugPattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;

function allowedDestination(value: string): string | null {
  try {
    const url = new URL(value);
    const isBlog =
      url.pathname.startsWith("/en/blog/") ||
      url.pathname.startsWith("/ar/blog/");

    if (
      url.origin !== "https://omaralbeik.com" ||
      url.username ||
      url.password ||
      !isBlog
    ) {
      return null;
    }

    return url.href;
  } catch {
    return null;
  }
}

app.use("*", async (c, next) => {
  c.header("Cache-Control", "no-store");
  await next();
});

app.get("/health", (c) => c.json({ ok: true }));

app.get("/go/:slug", async (c) => {
  const slug = c.req.param("slug");
  if (slug.length > 64 || !slugPattern.test(slug)) {
    return c.text("Link not found", 404);
  }

  const value = await c.env.LINKS.get(`link:${slug}`);
  if (value === null) return c.text("Link not found", 404);

  const destination = allowedDestination(value);
  if (destination === null) {
    console.error({ event: "invalid_link_destination", slug });
    return c.text("Link temporarily unavailable", 503);
  }

  return c.redirect(destination, 302);
});

app.all("/go/:slug", (c) => {
  c.header("Allow", "GET, HEAD");
  return c.text("Method not allowed", 405);
});

app.onError((error, c) => {
  console.error({ event: "link_lookup_failed", message: error.message });
  c.header("Cache-Control", "no-store");
  return c.text("Link temporarily unavailable", 503);
});

export default app;

get() returns text by default and returns null for a missing key. A storage error is different: it reaches onError, which returns 503 rather than telling the reader the link does not exist. /health only checks that the Worker responds; it does not test access to KV.

The destination check rejects malformed URLs, other origins, embedded credentials, and paths outside the blog. Comparing the parsed origin—scheme, hostname, and port—rejects lookalike domains such as omaralbeik.com.example.net. Visitors cannot set a destination through a query parameter or a write request.

The path check also rejects direct links back to /go/. It does not follow the destination to inspect any redirects that page might return.

We use a temporary redirect because destinations can change. Cache-Control: no-store asks browsers and shared HTTP caches not to retain the response. It does not bypass KV’s internal cache.

Save a destination into the local namespace, then start the Worker:

npx wrangler kv key put "link:cloudflare-d1" \
  "https://omaralbeik.com/en/blog/series/cloudflare/understanding-cloudflare-d1" \
  --binding LINKS --local

npx tsc
npx wrangler dev --local

In a second terminal, inspect the response without following it:

curl -i http://localhost:8787/go/cloudflare-d1

Expect a 302 with these headers; capitalization and order may differ:

Location: https://omaralbeik.com/en/blog/series/cloudflare/understanding-cloudflare-d1
Cache-Control: no-store

Open that same localhost URL in a browser to follow the redirect. Then try /go/not-created: it should return 404. A POST to an existing short link should return 405. Hono also handles HEAD through the GET route and omits the response body, so curl -I works too.

To change the destination, write the same key again. This time, send the reader to the Arabic article:

npx wrangler kv key put "link:cloudflare-d1" \
  "https://omaralbeik.com/ar/blog/series/cloudflare/understanding-cloudflare-d1" \
  --binding LINKS --local

Repeat the curl request. You should now see the Arabic article’s address. Keep all commands in the same project directory so they use the same configuration and local state.

Local testing verifies our routing, validation, and storage operations. It does not reproduce KV’s global cache behavior. Seeing a new value immediately on your machine does not tell you when a reader in another region will see it.

Suppose requests from Amsterdam and Singapore have both read the English article’s address. You change the destination to the Arabic article. A later lookup from one location may return the new address while the other still returns the old one.

The write succeeded, but the readers received different cached versions. With eventual consistency, reads converge on the updated value after writes stop. Until then, even a read at the location that performed a write may return an older value. Cloudflare documents delays of 60 seconds or more, depending on cached values and their lifetime. That is not a fixed deadline by which every reader will see the update.

STEP THROUGH AN UPDATE

One key, two possible answers

Switch the link from the English article to the Arabic article, then see what two locations might read.

  1. 1. Before the changeBoth locations have the English destination
    Stored destinationEnglish article
    AmsterdamEnglish article
    SingaporeEnglish article

    Earlier requests left a cached address for the English article in both locations.

  2. 2. The write succeedsThe stored link now points to the Arabic article
    Stored destinationArabic article
    AmsterdamEnglish article (cached)
    SingaporeEnglish article (cached)

    The write has completed. Either location may still read the previous destination.

  3. 3. Two later readsAmsterdam reads the new address; Singapore reads the old one
    Stored destinationArabic article
    AmsterdamArabic article
    SingaporeEnglish article

    In this example, a read from Amsterdam gets the updated address. A read from Singapore gets the cached English destination. Either location could have received the update first.

  4. 4. Later, after refreshBoth reads return the Arabic destination
    Stored destinationArabic article
    AmsterdamArabic article
    SingaporeArabic article

    Both locations now return the updated address. The steps are not equally spaced in time, and other sequences are possible.

The result “key not found” can be cached too. Someone who requested a link before it existed may still receive that result after you create it.

Step through one possible sequence. The locations are illustrative, and the steps have no fixed duration; this is not a measurement of Cloudflare's network.

The result “key not found” is cached too. If someone requests /go/new-article before you create it, that location may continue seeing a missing key after the write succeeds. Create links before sharing them and check the deployed route. A successful check confirms that request worked; other locations may still return an older result.

Keep the old destination working while the update becomes visible. For an urgent takedown, do not assume deleting a KV key stops all readers immediately: deletion also takes time to become visible. If your service must disable a link immediately, KV alone cannot enforce that requirement.

Separate caching from expiration

TTL means time to live, but the important question is what expires: a cached lookup, the stored key, or an HTTP response.

THREE DIFFERENT LIFETIMES

What each setting controls

Choose the setting for the layer you want to change: KV lookup, stored key, or HTTP response.

  1. KV lookup cachecacheTtl

    Set on get(). Controls how long a lookup result is cached in a network location. It does not delete the stored key.

  2. Stored keyexpirationTtl

    Set on put(); --ttl in Wrangler. Deletes the key after the chosen lifetime. Key expiration takes precedence over the KV cache lifetime.

  3. HTTP responseCache-Control

    Set on the response. Our no-store header asks browsers and shared HTTP caches not to store the redirect. It does not control KV's cache.

Our route uses the default KV cache lifetime, keeps ordinary links until we delete them, and sends no-store on HTTP responses.

A cached lookup, a stored key, and an HTTP response have different lifetimes. Setting one does not set the others.

Our get() uses the default 60-second KV cache lifetime. You can supply cacheTtl on a read; its documented minimum is 30 seconds. A longer lifetime can reduce trips to central storage, at the cost of potentially serving older values for longer. Setting it to 0 is not a supported way to bypass the cache.

For a link that should disappear after an hour, set expiration when writing:

npx wrangler kv key put "link:weekend-reading" \
  "https://omaralbeik.com/en/blog/series/cloudflare/understanding-cloudflare-d1" \
  --binding LINKS --local --ttl 3600

Wrangler calls this flag --ttl; the binding API calls the equivalent option expirationTtl. Absolute expiration uses a Unix timestamp in seconds, not JavaScript’s milliseconds. Both forms require an expiration at least 60 seconds in the future. An expired key reads as missing, so this service returns 404.

Key expiration takes precedence over KV’s cache lifetime. It cannot undo a redirect the browser has already followed. When updating an expiring link, include its expiration in the new write too.

Maintain the directory without an admin API

For a small directory, the Wrangler commands are enough:

npx wrangler kv key get "link:cloudflare-d1" --binding LINKS --local
npx wrangler kv key list --prefix "link:" --binding LINKS --local
npx wrangler kv key delete "link:weekend-reading" --binding LINKS --local

get is useful for checking what you stored. list finds keys with the prefix; it does not give you SQL filters over their values. If you later use the binding’s list() API, follow its cursor until list_complete is true. An empty page alone does not prove the listing is finished.

Wrangler uses your Cloudflare credentials for remote writes; the public Worker exposes only reads. In a team, review changes and give automation an API token with only the permissions it needs. If you add a dashboard for editors, verify who they are, check which links they may change, and record their edits.

KV does not offer an atomic “create only if absent” operation through get() followed by put(). Two writers can both see a missing key, then overwrite each other. We can keep this directory manageable by publishing changes through one process. If several editors need to reserve names concurrently, use a unique constraint in D1 or coordinate requests through a Durable Object.

For the same reason, don’t add a click counter by reading a number, incrementing it, and writing it back to KV. Concurrent requests can lose increments, and KV limits writes to the same key to one per second. Use an analytics system for traffic reporting, or storage designed for the counting guarantees you need.

Give the deployed Worker its own namespace

Everything so far has stayed on your machine. When you are ready to deploy your own service, log in and create its remote namespace:

npx wrangler login
npx wrangler kv namespace create LINKS

Use the returned namespace ID in wrangler.jsonc, replacing the all-zero placeholder. If Wrangler offers to update the file, inspect the resulting binding rather than adding a duplicate. The binding name must remain LINKS.

Add the link to the remote namespace before deploying:

npx wrangler kv key put "link:cloudflare-d1" \
  "https://omaralbeik.com/en/blog/series/cloudflare/understanding-cloudflare-d1" \
  --binding LINKS --remote

npx wrangler types
npx tsc
npx wrangler deploy

Local data is not uploaded by deploy. A namespace also lives independently of a Worker version: rolling back code does not undo a destination edit. Keep the link definitions in a versioned file, or maintain another copy you can restore.

Use the deployment URL Wrangler prints and append /go/cloudflare-d1. Check its status and Location header with curl -i, then follow it in a browser. Use npx wrangler tail to inspect the structured errors if a lookup returns 503.

Keep preview and production namespaces separate. Two Workers bound to the same namespace share data, regardless of their names or Git branches. Continue using explicit --local and --remote flags when maintaining links; they make the target visible in the command you’re about to run.

To use your own domain, attach a dedicated hostname such as go.your-domain.com, as covered in the hosting article. This example’s path would then be https://go.your-domain.com/go/cloudflare-d1. Serving /go/* on an existing website instead requires integrating the handler with that site’s routing.

What does a redirect cost?

Each GET or HEAD request with a valid slug makes one KV read, including a missing link. A warm KV cache can improve latency; it does not remove the billable read. Invalid slugs and unsupported methods are rejected before accessing KV.

These are the published KV allowances and rates, checked on November 30, 2026:

OperationFree planIncluded with Workers PaidAdditional usage on Paid
Read keys100,000/day10 million/month$0.50/million
Write keys1,000/day1 million/month$5/million
Delete keys1,000/day1 million/month$5/million
List requests1,000/day1 million/month$5/million
Stored data1 GB1 GB$0.50/GB-month

For example, 12 million KV reads in a month on Paid would add $1 in KV read charges after the 10 million included reads. That is not the total application bill: Workers plan and execution charges, other KV operations, and other applications sharing the allowance still matter. Free allowances reset daily at midnight UTC; exceeding one makes further operations of that type fail until the allowance resets.

The limits most relevant here are 512 bytes per key, 25 MiB per value, and one write per second to the same key. Our destinations are tiny; a busy editor or a bot requesting many nonexistent slugs is more likely to expose an operational problem than value size. Workers request and CPU limits also apply. Monitor usage and add rate limits where traffic warrants them.

Inspect the first response with curl -i, without -L, so you can see what the redirect Worker actually returned. Start with the status and Location header:

What you seeWhat to check
Local links work, but the deployed route returns 404Did you write the key to the remote namespace? Does its ID match the deployed binding? deploy does not copy local keys.
A newly created link returns 404Check spelling, the link: prefix, expiration, and the namespace. A previous missing-key lookup may also be cached.
The response has the old LocationCheck the namespace you updated, then consider KV’s cached value. Repeated writes do not force every location to refresh.
curl shows the new Location, but a browser opens an old pageInspect the browser’s network trace, including any further redirects. An earlier HTTP redirect, a service worker, or the destination itself may be involved.
The route returns 503Read the Worker logs. Our code distinguishes an invalid stored URL from a failed lookup, which can include a quota error.

One request only tells you what that request saw. Use it to narrow the problem, not to conclude that every location has the same value.

Choosing between KV, D1, and Durable Objects

Choose storage based on the operations you need and the delays or conflicts your application can tolerate:

RequirementA useful starting point
Resolve a known key; occasional older values are acceptableKV
Find drafts by owner, enforce unique slugs, or update several related rowsD1
Coordinate requests around shared state, such as a room or a live sessionDurable Objects

A Durable Object can coordinate writes to KV, but requests that read from KV can still receive older values. Coordinating writes does not change the guarantees of those reads.

KV fits this directory because edits are infrequent and the previous destination remains usable during an update. If you need immediate takedowns or coordinated editing, revisit the storage choice before adding more workarounds.

Have you debugged a link that kept sending readers to an old destination? I’d like to hear where the stale value turned out to be. If this guide helped, share it with someone choosing storage for a Worker.

Topics