Dev.to WebDev 🛠 Dev 👁 0 📖 7 min read

Hebrew short links in Next.js: what the server receives and how to read it

A short link like kip.li/מבצע-חורף ("winter sale") is what people type and what they read on a poster. The server never sees those letters. This article follows one Next.js 16 App Router codebase through the path a Hebre

A short link like kip.li/מבצע-חורף ("winter sale") is what people type and what they read on a poster. The server never sees those letters. This article follows one Next.js 16 App Router codebase through the path a Hebrew back-half takes, from the request line to the database key and back to the screen. Every excerpt is taken from the repo.

What actually arrives

A URI is ASCII. Anything else travels as percent-encoded bytes, and the convention for text, codified for IRIs in RFC 3987 and in the WHATWG URL Standard, is to encode it as UTF-8 first and then write each byte as %XX. Hebrew letters are two bytes each in UTF-8, so מ (U+05DE) becomes %D7%9E, and the request looks like this:

GET /%D7%9E%D7%91%D7%A6%D7%A2-%D7%97%D7%95%D7%A8%D7%A3 HTTP/1.1
Host: kip.li

Browsers do the encoding before the request leaves, and most display the decoded form in the address bar. Punycode has no part in this: IDNA and Punycode (RFC 5891, RFC 3492) apply to domain labels only. A Hebrew host becomes xn--...; a Hebrew path becomes percent escapes. The same codebase does both: its destination normaliser converts Hebrew hosts to punycode, while the back-half stays UTF-8 in the path.

Inside a route handler, req.nextUrl is built on the WHATWG parser, so pathname is already the encoded form. new URL("https://kip.li/מבצע-חורף+").pathname returns /%D7%9E%D7%91%D7%A6%D7%A2-%D7%97%D7%95%D7%A8%D7%A3+. The + survives as a literal: it is a sub-delimiter allowed in a path (RFC 3986, section 3.3). It means "space" only in form-encoded query strings.

There is a third shape. A comment in the parser notes that some apps double-encode Hebrew, turning each % into %25, and the test suite holds such a case: %25D7%2597%25D7%25A0%25D7%2595%25D7%25AA must resolve to חנות.

One function owns decoding

The redirect route, src/app/[slug]/route.ts, ignores its own slug parameter. It reads the path and hands the raw string to a shared engine:

function backHalf(req: NextRequest): string {
  return req.nextUrl.pathname.replace(/^\/+/, "");
}

Next decodes dynamic route parameters before the handler runs. If the framework decodes for some routes and your code decodes for others, you lose track of how many times a string has been decoded, and double-encoded input becomes ambiguous. Taking the raw path keeps decoding in one place. The same engine also serves customer domains through a catch-all route whose segments arrive already decoded, so the parser accepts both forms; text without a %XX sequence passes through unchanged.

That parser is parseBackHalf in src/lib/redirect/parse.ts:

export function parseBackHalf(raw: string | null | undefined): BackHalf | null {
  if (raw == null) return null;
  let value = safeDecode(String(raw)).normalize("NFKC").trim();
  value = value.replace(/^\/+/, "").replace(/\/+$/, "");
  if (!value || value.includes("/")) return null;

  let preview = false;
  if (value.endsWith("+")) {
    preview = true;
    value = value.replace(/\++$/, "");
  }
  if (!value || value.length > 200) return null;
  // Same alphabet as validateSlug (letters in any script, digits, combining marks, "-" and "_").
  if (!/^[\p{L}\p{N}][\p{L}\p{N}\p{M}_-]*$/u.test(value)) return null;
  return { slug: value, preview };
}

safeDecode wraps decodeURIComponent so it never throws, and repeats it while a %XX sequence remains, at most twice. That is a deliberate exception to the usual rule of decoding exactly once. It is safe here only because of the last line: the decoded value has to match a strict allow-list of letters, digits, combining marks, _ and -. Anything that decodes into /, %, . or whitespace is rejected rather than interpreted, so a second pass cannot smuggle a path separator in through %252F. Without an allow-list after it, a second decode is a bug.

Order matters too. Normalisation runs after decoding, because there is nothing to normalise in %D7%9E. Trimming and the slash checks run after normalisation, so a full-width slash (U+FF0F), which NFKC folds to /, is caught like a plain one.

Normalising into a lookup key

Each link stores two strings: the back-half as its creator typed it, and a lookup key with a unique constraint per domain. The key comes from src/lib/links/slug.ts:

const SLUG_PATTERN = /^[\p{L}\p{N}][\p{L}\p{N}\p{M}_-]*$/u;

/** Lookup key: Unicode-normalised and lower-cased, so KIP.li/Sale and kip.li/sale are the same link. */
export function slugKey(slug: string): string {
  return slug.normalize("NFKC").toLowerCase();
}

Every read goes through slugKey: the redirect, the preview page, the availability check and the reserved-word check. What NFKC does for Hebrew is narrow but real. The presentation forms block (U+FB1D to U+FB4F) folds back to ordinary letters: the wide alef U+FB21 becomes א, and precomposed pointed letters such as U+FB2B split into a base letter plus a combining point. Full-width Latin folds too, so sale becomes sale. NFKC does not remove niqqud, so שלום and שָׁלוֹם are two different keys. toLowerCase() does nothing to Hebrew, which has no case; it exists for Latin back-halves.

The pattern also defines some edges worth knowing:

  • The first character must be a letter or digit, so a back-half cannot start with a bare vowel point.
  • Only the ASCII hyphen-minus is allowed. The Hebrew maqaf (U+05BE) and gershayim (U+05F4, as in צה״ל) are punctuation in Unicode, so back-halves containing them are refused at creation and never match at redirect.
  • Length is checked in code points by validateSlug ([...slug].length, between 2 and 60). Niqqud counts: שָׁלוֹם is seven code points. The parser's 200-unit cap is a cheap guard before the regex, not the real limit.
  • Reserved words cover the app's own paths and a few Hebrew ones (אודות, מחירים, בלוג and others), compared through slugKey, so case and width variants are caught as well.

The proxy (src/proxy.ts) handles the case question for the site's own pages: /Pricing gets a 308 to /pricing. When it lower-cases a path it skips percent escapes, so the hex digits of an encoded Hebrew segment keep their spelling.

The "+" preview

Appending + to a short link shows where it leads without going there. The parser strips any run of trailing + and sets preview. Because decoding happens first, abc%2B is a preview request too, and + on its own is rejected. The engine then redirects to the preview page and encodes the back-half again on the way out:

if (parsed.preview) return redirectTo(appPage(`/link/preview/${encodeURIComponent(parsed.slug)}`));

Broken escapes

A link copied with its last character cut off can end mid-letter: /%D7%A7%D7 has a complete ק and then the first byte of another letter. decodeURIComponent throws URIError on it. Because Next decodes route parameters before the route runs, a comment in the code reports that such a request ended as the framework's bare 500 screen on Vercel and a bare 400 on its own server, before any application code could answer.

The proxy runs first. repairBrokenEscapes tries to decode each path segment and replaces any segment that fails with ~, a character no back-half can start with, then answers with a 307 to the repaired path. There the route treats it like any unknown link. The code uses a redirect, not a rewrite, because after a rewrite Next still reads route parameters from the address the visitor asked for.

Showing it back

Display is a bidi problem (Unicode Standard Annex #9). A Latin host followed by a Hebrew path, with digits and dashes in between, will reorder in ways nobody typed. The project's .url class sets direction: ltr and unicode-bidi: isolate. That was not enough: inside a left-to-right box the bidi algorithm still groups digits and dashes with a neighbouring Hebrew run, and מבצע-2026-קיץ showed its words swapped. The short-link component now wraps each Hebrew run in its own <bdi dir="rtl"> and leaves everything between them left to right.

Headers need the opposite treatment. HTTP field values are bytes, and the Headers class in Node accepts only characters up to U+00FF. new Headers({ Location: "https://kip.li/מבצע" }) throws a TypeError. Any Location built from a Hebrew back-half has to be percent-encoded first, as the preview redirect above does.

Summary

  • Read the raw path and decode it in one function, a bounded number of times.
  • Normalise after decoding and compare on a stored key.
  • Validate the decoded value against an allow-list, not a deny-list.
  • Turn broken escapes into ordinary dead links before the framework sees them.
  • Encode again on the way out, and isolate Hebrew runs when you display a URL.

I build KIP, a Hebrew-first link shortener at kip.li, and the code above comes from its repository.

References

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.