Skip to main content

Web frameworks · Intermediate · 22 min

Build a small API with Hono that runs on Node, Bun and edge runtimes

By Padding · Updated 18 Nov 2026
Node.js 26.13 (node:26 image) · Hono 4.13.19 · @hono/node-server 2.1.9 · Zod 4.6.7 · TypeScript 7.0.2

You will build a link-shortener API with Hono 4.13 on Node.js 26, with Zod validation, logging, CORS, a bearer token, a typed client and tests, and know which one file to change to run it on Bun, Deno or Cloudflare Workers.

On this page

Hono is a small web framework built on the web-standard Request and Response objects. Your app is one object with a fetch method, and every JavaScript runtime that speaks those standards can call it: Node.js through a thin adapter, Bun, Deno and Cloudflare Workers directly. Write the routes once and only the file that starts the server changes.

You will build a link shortener. It stores a long URL under a short slug, redirects visitors from /<slug> to the long URL and counts the visits. Writes need a bearer token, request bodies are checked with Zod, a browser app on one named origin is allowed in through CORS, and a TypeScript client gets its types straight from your routes. Short links are worth having where people share links in SMS and chat messages on small screens and prepaid data: a 25-character link costs less space than a 200-character one, and the redirect itself is one tiny response.

The links live in memory, so restarting the server empties them. That keeps the tutorial about Hono. The last step says what to swap in when you deploy.

Node.js 26 runs .ts files directly by stripping the types, so there is no build step. TypeScript is installed only to check the types.

Step 1 · Create the project

Make a throwaway folder, write a package.json with exact versions, and install. "type": "module" lets you use import and top-level await:

Bash
mkdir -p ~/hono-links-demo
cd ~/hono-links-demo
cat > package.json <<'JSON'
{
  "name": "hono-links",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "node --env-file-if-exists=.env --watch src/server.ts",
    "start": "node --env-file-if-exists=.env src/server.ts",
    "client": "node --env-file=.env src/client.ts",
    "test": "node --test src/app.test.ts",
    "typecheck": "tsc"
  },
  "dependencies": {
    "@hono/node-server": "2.1.9",
    "@hono/zod-validator": "0.9.1",
    "hono": "4.13.19",
    "zod": "4.6.7"
  },
  "devDependencies": {
    "@types/node": "26.6.6",
    "typescript": "7.0.2"
  }
}
JSON
npm install

Add a tsconfig.json that matches what Node can run. allowImportingTsExtensions lets you write ./links.ts in imports, which Node needs, and erasableSyntaxOnly makes TypeScript reject syntax such as enum that Node cannot strip:

Bash
cat > tsconfig.json <<'JSON'
{
  "compilerOptions": {
    "target": "esnext",
    "module": "nodenext",
    "strict": true,
    "noEmit": true,
    "allowImportingTsExtensions": true,
    "erasableSyntaxOnly": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true,
    "types": ["node"]
  },
  "include": ["src"]
}
JSON
mkdir -p src
printf 'node_modules\n.env\nauth-header.txt\n' > .gitignore

Hono 5 is in release candidates on npm's next tag. This tutorial pins 4.13, the current stable line.

Check it worked

Bash
npm ls hono @hono/node-server zod

The tree lists hono@4.13.19, @hono/node-server@2.1.9 and zod@4.6.7, with no UNMET or invalid warnings.

Step 2 · Write the routes and run them on Node

First the store. src/links.ts keeps links in a Map and makes random slugs with crypto.getRandomValues, a web-standard function that every runtime here has. The alphabet leaves out l, o, 0 and 1, which people misread when they copy a link by hand:

Bash
cat > src/links.ts <<'TS'
export type Link = { slug: string; url: string; visits: number; createdAt: string };

const links = new Map<string, Link>();
const alphabet = "abcdefghijkmnpqrstuvwxyz23456789";

function randomSlug(length = 6): string {
  const bytes = crypto.getRandomValues(new Uint8Array(length));
  return Array.from(bytes, (b) => alphabet[b % alphabet.length]).join("");
}

export function listLinks(): Link[] {
  return [...links.values()];
}

export function getLink(slug: string): Link | undefined {
  return links.get(slug);
}

export function addLink(url: string, slug?: string): Link | undefined {
  const key = slug ?? randomSlug();
  if (links.has(key)) return undefined;
  const link = { slug: key, url, visits: 0, createdAt: new Date().toISOString() };
  links.set(key, link);
  return link;
}

export function recordVisit(slug: string): Link | undefined {
  const link = links.get(slug);
  if (link) link.visits += 1;
  return link;
}

export function deleteLink(slug: string): boolean {
  return links.delete(slug);
}
TS

Now the API routes, in their own small Hono app. Each handler gets a context, c. c.req.param() reads a path segment, c.req.json() reads the body, and c.json(), c.body() and c.redirect() build the response. The routes are chained (new Hono().get(...).post(...)) rather than written as separate statements, because the chain carries every route's types, which the typed client uses later:

Bash
cat > src/api.ts <<'TS'
import { Hono } from "hono";
import { addLink, deleteLink, getLink, listLinks } from "./links.ts";

export const api = new Hono()
  .get("/links", (c) => c.json({ links: listLinks() }))
  .get("/links/:slug", (c) => {
    const link = getLink(c.req.param("slug"));
    if (!link) return c.json({ error: "No link with that slug" }, 404);
    return c.json(link, 200);
  })
  .post("/links", async (c) => {
    const { url, slug } = await c.req.json<{ url: string; slug?: string }>();
    const link = addLink(url, slug);
    if (!link) return c.json({ error: "That slug is taken" }, 409);
    return c.json(link, 201, { Location: `/api/links/${link.slug}` });
  })
  .delete("/links/:slug", (c) => {
    if (!deleteLink(c.req.param("slug"))) return c.json({ error: "No link with that slug" }, 404);
    return c.body(null, 204);
  });
TS

src/app.ts is the root app. It mounts the API under /api, answers a health check, and turns /<slug> into a redirect. app.route() returns the app with the API's route types attached, and exporting that type as AppType is what the client imports:

Bash
cat > src/app.ts <<'TS'
import { Hono } from "hono";
import { api } from "./api.ts";
import { recordVisit } from "./links.ts";

const app = new Hono();

app.get("/health", (c) => c.text("ok"));

const routes = app.route("/api", api);

app.get("/:slug", (c) => {
  const link = recordVisit(c.req.param("slug"));
  if (!link) return c.notFound();
  return c.redirect(link.url, 302);
});

export type AppType = typeof routes;
export default app;
TS

Hono matches routes in the order you register them, so /health wins over /:slug.

The last file is the only one that knows it runs on Node. serve() from @hono/node-server turns Node's HTTP server events into Request objects and hands them to app.fetch:

Bash
cat > src/server.ts <<'TS'
import { serve } from "@hono/node-server";
import app from "./app.ts";

const port = Number(process.env.PORT ?? 8787);

serve({ fetch: app.fetch, port }, (info) => {
  console.log(`Short links API on http://localhost:${info.port}`);
});
TS

Start it in a second terminal, from ~/hono-links-demo. --watch restarts it whenever you save a file:

Bash
npm run dev

Back in the first terminal, create a link, read it back, and follow the short link:

Bash
curl -s -X POST http://localhost:8787/api/links -H 'Content-Type: application/json' -d '{"url":"https://hono.dev/docs/","slug":"docs"}'
echo
curl -s http://localhost:8787/api/links
echo
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' http://localhost:8787/docs
curl -s http://localhost:8787/api/links/docs
echo

Check it worked

The terminal running npm run dev prints Short links API on http://localhost:8787. The POST answers with the new link and "visits":0, the list holds that one link, the redirect line reads 302 https://hono.dev/docs/, and the last call shows "visits":1. Open http://localhost:8787/docs in a browser and it lands on the Hono docs.

Step 3 · Validate request bodies with Zod

The POST route trusts whatever arrives. Send it something that is not a web address:

Bash
curl -s -o /dev/null -w '%{http_code}\n' -X POST http://localhost:8787/api/links -H 'Content-Type: application/json' -d '{"url":"javascript:alert(1)"}'

It answers 201. The API now stores a script URL and will redirect visitors to it. Describe what a valid body looks like with a Zod schema, and let zValidator check it before your handler runs. Replace src/api.ts:

Bash
cat > src/api.ts <<'TS'
import { Hono } from "hono";
import { zValidator } from "@hono/zod-validator";
import { z } from "zod";
import { addLink, deleteLink, getLink, listLinks } from "./links.ts";

const newLink = z.object({
  url: z.url({ protocol: /^https?$/ }),
  slug: z
    .string()
    .regex(/^[a-z0-9-]{3,32}$/, "use 3 to 32 lowercase letters, digits or hyphens")
    .optional(),
});

export const api = new Hono()
  .get("/links", (c) => c.json({ links: listLinks() }))
  .get("/links/:slug", (c) => {
    const link = getLink(c.req.param("slug"));
    if (!link) return c.json({ error: "No link with that slug" }, 404);
    return c.json(link, 200);
  })
  .post(
    "/links",
    zValidator("json", newLink, (result, c) => {
      if (!result.success) {
        const issues = result.error.issues.map((i) => ({ field: i.path.join("."), message: i.message }));
        return c.json({ error: "Invalid link", issues }, 400);
      }
    }),
    (c) => {
      const { url, slug } = c.req.valid("json");
      const link = addLink(url, slug);
      if (!link) return c.json({ error: "That slug is taken" }, 409);
      return c.json(link, 201, { Location: `/api/links/${link.slug}` });
    },
  )
  .delete("/links/:slug", (c) => {
    if (!deleteLink(c.req.param("slug"))) return c.json({ error: "No link with that slug" }, 404);
    return c.body(null, 204);
  });
TS

z.url({ protocol: /^https?$/ }) accepts only http and https addresses. The third argument to zValidator is a hook: without it, a failed check returns Zod's whole error object, and with it you choose a short shape that a client can show next to the right field. Inside the handler, c.req.valid("json") returns the checked body with its TypeScript type, and keys the schema does not list are dropped.

--watch restarted the server when you saved, which also emptied the store. Try a bad address, a bad slug and a good link:

Bash
curl -s -X POST http://localhost:8787/api/links -H 'Content-Type: application/json' -d '{"url":"javascript:alert(1)"}'
echo
curl -s -X POST http://localhost:8787/api/links -H 'Content-Type: application/json' -d '{"url":"https://example.com","slug":"No Spaces"}'
echo
curl -s -o /dev/null -w '%{http_code}\n' -X POST http://localhost:8787/api/links -H 'Content-Type: application/json' -d '{"url":"https://example.com/long/path?ref=sms"}'

Check it worked

The first call answers {"error":"Invalid link","issues":[{"field":"url",...}]} and the second names "field":"slug" with your message about lowercase letters. The third prints 201, and the link it stored has a random six-character slug.

Step 4 · Add logging, CORS and a bearer token

Middleware is a function that runs before your handler and can stop the request or pass it on with await next(). Hono ships the three you need. Use logger to print each request, cors to tell browsers which other origin may call the API, and bearerAuth to reject writes without the right token.

Settings go in a .env file, not in code. Generate a long random token and write it to .env, and also to auth-header.txt so curl can send it without the token appearing on your command line. The subshell sets umask 077, so both files are created readable only by you:

Bash
cd ~/hono-links-demo
(
  umask 077
  token=$(node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))")
  printf 'API_TOKEN=%s\nCORS_ORIGIN=http://localhost:5173\n' "$token" > .env
  printf 'Authorization: Bearer %s\n' "$token" > auth-header.txt
)
ls -l .env auth-header.txt

CORS_ORIGIN is the address of the browser app you allow, here a Vite dev server on port 5173. Replace it with your front end's origin.

Replace src/app.ts. The settings are read with env(c) from hono/adapter on each request, not from process.env at start-up, because env(c) knows where each runtime keeps them:

Bash
cat > src/app.ts <<'TS'
import { Hono } from "hono";
import type { MiddlewareHandler } from "hono";
import { env } from "hono/adapter";
import { bearerAuth } from "hono/bearer-auth";
import { cors } from "hono/cors";
import { HTTPException } from "hono/http-exception";
import { logger } from "hono/logger";
import { api } from "./api.ts";
import { recordVisit } from "./links.ts";

type Settings = { API_TOKEN?: string; CORS_ORIGIN?: string };

// Reads are public. Every other method under /api needs the token.
const requireTokenForWrites: MiddlewareHandler = async (c, next) => {
  if (c.req.method === "GET" || c.req.method === "HEAD") return next();
  const token = env<Settings>(c).API_TOKEN;
  if (!token) throw new HTTPException(500, { message: "API_TOKEN is not set" });
  return bearerAuth({ token })(c, next);
};

const app = new Hono();

app.use(logger());
app.use(
  "/api/*",
  cors({
    origin: (origin, c) => (origin === env<Settings>(c).CORS_ORIGIN ? origin : null),
    allowHeaders: ["Authorization", "Content-Type"],
    allowMethods: ["GET", "POST", "DELETE"],
  }),
);
app.use("/api/*", requireTokenForWrites);

app.get("/health", (c) => c.text("ok"));

const routes = app.route("/api", api);

app.get("/:slug", (c) => {
  const link = recordVisit(c.req.param("slug"));
  if (!link) return c.notFound();
  return c.redirect(link.url, 302);
});

export type AppType = typeof routes;
export default app;
TS

Order matters. cors comes before the token check, so a browser's preflight OPTIONS request, which never carries the token, gets its CORS answer and stops there. If API_TOKEN is missing, writes fail with a 500 rather than letting everyone in.

Node reads .env only when it starts, so stop the dev server with Ctrl+C and run npm run dev again.

Now try a write without the token, the same write with it, and a preflight from the allowed origin and from another one. -H @auth-header.txt makes curl read the header from the file:

Bash
curl -s -o /dev/null -w '%{http_code}\n' -X POST http://localhost:8787/api/links -H 'Content-Type: application/json' -d '{"url":"https://example.com/a","slug":"try-a"}'
curl -s -o /dev/null -w '%{http_code}\n' -X POST http://localhost:8787/api/links -H @auth-header.txt -H 'Content-Type: application/json' -d '{"url":"https://example.com/a","slug":"try-a"}'
curl -s -i -X OPTIONS http://localhost:8787/api/links -H 'Origin: http://localhost:5173' -H 'Access-Control-Request-Method: POST' | grep -i '^access-control-allow-origin' || echo "no allow-origin header"
curl -s -i -X OPTIONS http://localhost:8787/api/links -H 'Origin: https://elsewhere.example' -H 'Access-Control-Request-Method: POST' | grep -i '^access-control-allow-origin' || echo "no allow-origin header"

Check it worked

The status lines are 401 then 201. The allowed origin gets access-control-allow-origin: http://localhost:5173, and the other origin prints no allow-origin header, so a browser on that site cannot read your responses. The dev server's terminal now logs each request as a <-- line on the way in and a --> line with the status and time on the way out.

Step 5 · Call the API from a typed client

hc from hono/client builds a client from the AppType you exported. It has no code generation step: the types come from your route definitions, including the Zod schema. Write src/client.ts:

Bash
cat > src/client.ts <<'TS'
import { hc } from "hono/client";
import type { AppType } from "./app.ts";

const client = hc<AppType>("http://localhost:8787", {
  headers: { Authorization: `Bearer ${process.env.API_TOKEN}` },
});

const created = await client.api.links.$post({
  json: { url: "https://padding.tech/tutorials", slug: "learn" },
});

if (created.status === 201) {
  const link = await created.json();
  console.log("created", link.slug, "->", link.url);
} else {
  console.log("not created:", created.status, await created.text());
  process.exitCode = 1;
}

const res = await client.api.links[":slug"].$get({ param: { slug: "learn" } });
if (res.ok) {
  const link = await res.json();
  console.log("visits so far:", link.visits);
}
TS
npm run client

import type is removed when Node strips the types, so the client does not load your server code. It only borrows its types. npm run client loads the token from .env with --env-file. If the link is not created, for example because the token is wrong, the client prints the status and exits with code 1, so a script that runs it notices the failure.

Now see what the types buy you. Run the type checker over the whole project:

Bash
npm run typecheck

Then open src/client.ts, change url: in the $post call to link:, and run npm run typecheck again. It fails with an error that 'link' does not exist in type '{ url: string; slug?: string | undefined; }'. Change it back.

Check it worked

npm run client prints created learn -> https://padding.tech/tutorials and visits so far: 0. npm run typecheck prints no errors with the correct field name and fails with the misspelt one. In your editor, hovering over link after await created.json() shows the Link fields.

Step 6 · Test the app without a server

app.request() sends a request straight to your app's fetch method and returns the Response. There is no port and no running server, so tests are fast and can run anywhere. Write src/app.test.ts with Node's built-in test runner:

Bash
cat > src/app.test.ts <<'TS'
import assert from "node:assert/strict";
import { test } from "node:test";
import app from "./app.ts";

// The app reads settings on each request, so setting them here is enough.
process.env.API_TOKEN = "test-token-only";
process.env.CORS_ORIGIN = "http://localhost:5173";

const auth = { Authorization: "Bearer test-token-only", "Content-Type": "application/json" };

test("creates a link and redirects to it", async () => {
  const created = await app.request("/api/links", {
    method: "POST",
    headers: auth,
    body: JSON.stringify({ url: "https://example.com/a", slug: "test-a" }),
  });
  assert.equal(created.status, 201);
  assert.equal(created.headers.get("location"), "/api/links/test-a");

  const visit = await app.request("/test-a");
  assert.equal(visit.status, 302);
  assert.equal(visit.headers.get("location"), "https://example.com/a");
});

test("rejects writes without the token", async () => {
  const res = await app.request("/api/links", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ url: "https://example.com/b" }),
  });
  assert.equal(res.status, 401);
});

test("rejects a script URL with a 400 that names the field", async () => {
  const res = await app.request("/api/links", {
    method: "POST",
    headers: auth,
    body: JSON.stringify({ url: "javascript:alert(1)" }),
  });
  assert.equal(res.status, 400);
  const body = await res.json();
  assert.equal(body.issues[0].field, "url");
});

test("answers a CORS preflight only for the allowed origin", async () => {
  const preflight = (origin: string) =>
    app.request("/api/links", {
      method: "OPTIONS",
      headers: { Origin: origin, "Access-Control-Request-Method": "POST" },
    });
  const allowed = await preflight("http://localhost:5173");
  assert.equal(allowed.headers.get("access-control-allow-origin"), "http://localhost:5173");
  const other = await preflight("https://elsewhere.example");
  assert.equal(other.headers.get("access-control-allow-origin"), null);
});
TS
npm test

The token in the test is a fixed string that exists only in the test file. Your real token stays in .env.

Check it worked

The output ends with tests 4, pass 4 and fail 0. The <-- and --> lines mixed in come from the logger middleware. To see a failure, change 401 to 403 in the second test and run npm test again: that test is marked with a cross and the expected and actual values. Change it back.

Step 7 · Move the API to Bun, Deno or Cloudflare Workers

Look at which files mention Node:

Bash
grep -l "@hono/node-server" src/*.ts

Only src/server.ts does. links.ts, api.ts and app.ts use web standards and Hono, and env(c) reads process.env on Node and Bun, Deno.env on Deno and the Worker's bindings on Cloudflare. To move, you replace the entry file. The code below shows each one. It is not part of the Node project you have built.

On Bun, the entry file's default export is an object with a port and a fetch method. Bun runs TypeScript and reads .env itself, so bun run src/bun.ts starts it:

TypeScript
// src/bun.ts
import app from "./app.ts";

export default { port: 8787, fetch: app.fetch };

On Deno, pass app.fetch to Deno.serve. Add "hono": "npm:hono@4.13.19", "hono/": "npm:/hono@4.13.19/", "@hono/zod-validator": "npm:@hono/zod-validator@0.9.1" and "zod": "npm:zod@4.6.7" to the imports map in deno.json, then run deno run --allow-net --allow-env --env-file src/deno.ts. Deno asks for each permission, so the flags say exactly what the API may do:

TypeScript
// src/deno.ts
import app from "./app.ts";

Deno.serve({ port: 8787 }, app.fetch);

On Cloudflare Workers, the entry file exports the app itself. Wrangler also needs a config file, wrangler.jsonc (or wrangler.toml), with at least main set to "src/worker.ts" and a compatibility_date such as "2026-11-01". With that in place, npx wrangler dev runs the Worker locally on port 8787. Local settings go in .dev.vars, and for production you store the token with npx wrangler secret put API_TOKEN, which prompts for the value:

TypeScript
// src/worker.ts
import app from "./app.ts";

export default app;

One more change is needed on Workers and on any host that runs several copies of your code. The in-memory Map in links.ts is not shared between copies and vanishes when a copy stops. Keep the same five functions in links.ts, make them async, and back them with a real store: Workers KV or D1 on Cloudflare, or SQLite or Postgres on a Node, Bun or Deno server. The routes only need an await in front of each call.

Check it worked

The grep prints only src/server.ts. If you have Bun or Deno installed (see Hello World in Bun and Hello World in Deno), stop the Node server, add the matching entry file and start it. For Workers, add src/worker.ts and wrangler.jsonc, then run npx wrangler dev. In each case curl http://localhost:8787/health answers ok the same way it did on Node. These three runtimes are described here but were not run when this tutorial was checked.

Step 8 · Clean up

Stop the dev server with Ctrl+C in the second terminal, then remove the project. It deletes .env and auth-header.txt too, so the token goes with it:

Bash
cd ~
rm -rf ~/hono-links-demo

Check it worked

ls ~/hono-links-demo reports No such file or directory, and curl http://localhost:8787/health fails to connect.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.