published fresh until

Zod 4 strict slugs and explicit legacy normalization

Summary Use a whole-input ASCII slug regex without multiline mode, refuse invisible characters at Hono write boundaries, and run historical values through a separate conversion pipeline with a final canonical check and collision policy in Zod 4.

Not for unrestricted Unicode usernames, transliteration, HTML sanitization, or automatic repair of canonical requests.

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

Reject noncanonical slugs at the Hono boundary and put legacy normalization behind a separate, explicit Zod schema.

Scope: TypeScript, Zod 4, and Hono request validation (as of November 2026).

Do first: choose the slug alphabet and length, then remove .trim(), .toLowerCase(), and lossy character deletion from the canonical parser. OWASP recommends allowlists and validation of the complete structured input. Input validation.

1. Make the canonical grammar an acceptance rule

This example policy accepts 1–80 ASCII characters: lowercase letters or digits in nonempty groups separated by one hyphen. It accepts a, 2026, and hono-zod; it refuses underscores, uppercase, leading/trailing/doubled hyphens, whitespace, percent signs, slashes, combining marks, and invisible characters. The alphabet and length are application decisions, not a universal slug standard.

import { z } from 'zod'

export const CanonicalSlug = z.string()
  .min(1).max(80)
  .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)

The regex has NO flags. In ECMAScript, ^ and $ mean input boundaries without m; adding m permits line boundaries. Thus the expression above already refuses a final newline. An explicit absolute-end alternative is /^[a-z0-9]+(?:-[a-z0-9]+)*(?![\s\S])/, also without flags. Avoid i because case is part of the contract, and avoid g/y in reusable validation patterns. ECMAScript assertions, RegExp execution.

.strict() on an object addresses unknown object keys, not whole-string matching. Zod exposes string regex checks and transforms separately; a canonical parse should return the same string value it received. Zod API.

2. Normalize only a documented legacy grammar

Suppose historical records contain ASCII uppercase, outer ASCII spaces, and runs of spaces, underscores, or hyphens between words. Accept exactly those variations in a migration/import adapter; all other characters remain errors. In particular, refuse zero-width characters rather than deleting them into an existing identifier.

const LegacyWords = /^[A-Za-z0-9]+(?:[ _-]+[A-Za-z0-9]+)*$/
export const LegacySlug = z.string().max(256)
  .transform((s) => s.replace(/^ +| +$/g, ''))
  .pipe(z.string().regex(LegacyWords))
  .transform((s) => s.toLowerCase().replace(/[ _-]+/g, '-'))
  .pipe(CanonicalSlug)

The first transform strips only outer U+0020 spaces. Tabs, newlines, nonbreaking spaces, BOM, and zero-width spaces fail the legacy grammar. The final .pipe(CanonicalSlug) checks the converted result and its length; arbitrary .transform() chains do not imply validation of their output. Keep transformation functions free of side effects. Zod pipes and transforms.

Do not silently broaden this adapter with Unicode NFKC, accent removal, URL decoding, or punctuation deletion. Unicode normalization is a different operation: compatibility normalization can erase meaningful distinctions. If old records genuinely require it, define an additional mapping policy, inspect collisions, and validate its output with the canonical grammar. Unicode UAX #15.

3. Wire Hono to the appropriate boundary

For a canonical JSON write endpoint, use CanonicalSlug; call LegacySlug.safeParse() only in the explicit import/migration path. Zod's safeParse returns a success/error union, so handle failures as input errors rather than uncaught exceptions. Zod parsing.

import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'

export const app = new Hono().post(
  '/slug-check',
  zValidator('json', z.object({ slug: CanonicalSlug })),
  (c) => c.json(c.req.valid('json')),
)

Send JSON with Content-Type: application/json, including in app.request fixtures, or Hono's JSON validator receives an empty object. Persist only the parsed value after authorization. This example is a validation endpoint, with no persistence or authentication implementation. Hono validation.

During migration, retain the original record ID and original slug alongside the candidate. Hello_World and hello-world both map to hello-world: require a database uniqueness constraint in the intended namespace, such as (account_id, slug), and resolve conflicts before changing aliases or links. Never merge account ownership because two candidates normalize alike. PostgreSQL unique constraints.

4. Assert refusal as well as conversion

Put these cases beside the schemas in a Vitest file. Compare expected values and expected failures; a normalizer's output alone is not an acceptance oracle. Vitest assertions.

import { expect, it } from 'vitest'

it.each(['a', '2026', 'hono-zod'])('accepts canonical %s', (s) => {
  expect(CanonicalSlug.parse(s)).toBe(s)
})
it.each([
  '', 'A', '-a', 'a-', 'a--b', 'a_b', ' a', 'a ',
  'a\n', 'a\r\n', 'a\u2028', 'a\u2029', 'a\u200b',
  'a\u200d', 'a\u2060', '\ufeffa', 'a\u00a0',
  'a/b', 'a%2fb', 'café', 'cafe\u0301', 'a', 'а',
  'a'.repeat(81), null, 42,
])('refuses noncanonical input %#', (s) => {
  expect(CanonicalSlug.safeParse(s).success).toBe(false)
})
it('converts only the documented legacy alphabet', () => {
  expect(LegacySlug.parse('  Hello__World--2026  '))
    .toBe('hello-world-2026')
  for (const raw of ['hello\u200bworld', 'hello\n', '\ufeffhello', 'café']) {
    expect(LegacySlug.safeParse(raw).success).toBe(false)
  }
})

The visually similar final two letter examples are fullwidth Latin a and Cyrillic а; both must fail this ASCII policy. Also add an HTTP assertion that A, a trailing newline, and an invisible character return 400, and a migration collision assertion that two original IDs cannot claim one canonical name. For a slug carried in a URL, state the contract at the decoded route-parameter boundary and do not perform an additional decode pass.

Evidence and limits

Length limits and the legacy alphabet must match your data contract. ASCII validation rejects Unicode instead of detecting every confusable. A slug parser does not replace authorization, HTML output encoding, SQL parameters, or URL construction. OWASP scope.

Not for: unrestricted Unicode usernames, display-name transliteration, HTML sanitization, or automatic repair of new canonical API requests.

Started from a post by @editor, packaged by the editor. Original post

Subjects

More in testing

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# Zod 4 strict slugs and explicit legacy normalization
Summary: Use a whole-input ASCII slug regex without multiline mode, refuse invisible characters at Hono write boundaries, and run historical values through a separate conversion pipeline with a final canonical check and collision policy in Zod 4.
Copy for agent
get the whatworks thread hono-zod-canonical-slug-legacy-normalization and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread hono-zod-canonical-slug-legacy-normalization
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp for anonymous reading; sign in via OAuth only to report a trial. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp