DEV Community

Jitsumi
Jitsumi

Posted on

JavaScript String Length Won’t Enforce a UTF-8 Byte Limit

An API accepts a 100-byte label. Your JavaScript form allows it because label.length <= 100. The server rejects a label containing emoji, even though the user typed fewer than 100 visible characters.

Both checks can be behaving correctly while enforcing different units. JavaScript's length counts UTF-16 code units. A UTF-8 byte limit concerns encoded bytes. A character counter for people may need grapheme clusters instead.

Before changing the limit, name the unit. “100 characters” is too vague for an API contract that is enforced in bytes.

Four short strings expose the difference

Save this as string-units.mjs and run node string-units.mjs on a current Node.js release:

import assert from 'node:assert/strict';

const encoder = new TextEncoder();
const cases = [
  ['A', 1, 1, 1],
  ['é', 1, 1, 2],
  ['😀', 2, 1, 4],
  ['e\u0301', 2, 2, 3]
];

for (const [text, units, points, bytes] of cases) {
  assert.equal(text.length, units);
  assert.equal([...text].length, points);
  assert.equal(encoder.encode(text).byteLength, bytes);
  console.log(JSON.stringify(text), units, points, bytes);
}

const json = JSON.stringify({ label: '😀' });
assert.equal(json.length, 14);
assert.equal(encoder.encode(json).byteLength, 16);
console.log('JSON units and bytes:', json.length, encoder.encode(json).byteLength);
Enter fullscreen mode Exit fullscreen mode

The three numeric columns are the sample's expected values, checked by assertions. e\u0301 is the letter e followed by a combining acute accent, not the single precomposed é used in the earlier row.

Mozilla documents String.length as a code-unit count. TextEncoder produces UTF-8 bytes, so the resulting typed array's byte length is the relevant measure for this encoding.

The spread expression counts code points, which fixes one mismatch but not all of them. It still counts the combining sequence as two. For a visible-character counter, consider Intl.Segmenter with grapheme granularity, and verify that its segmentation rules fit the product.

Measure the boundary the service actually enforces

A limit can apply to a field, the complete JSON document, an uncompressed payload or a transmitted body after another encoding. Those are different objects.

For a UTF-8 limit on one label, measure encoder.encode(label).byteLength. For a UTF-8 limit on the JSON body, serialise the complete body first, then measure those bytes. The braces, property names, quotes and escapes are part of that document too.

The sample's JSON expression makes this distinction concrete. Measuring the emoji alone gives four bytes. Measuring the JSON carrying it gives sixteen. Neither number describes an entire HTTP request with its headers and transport overhead.

Content-Length is also expressed in bytes, but let the HTTP client set it where it manages framing. A browser form counter is not a reason to manually set transport headers.

Keep the server's validation authoritative. A browser check improves feedback; callers can bypass it, and another client may normalise or serialise differently.

Rejecting is often clearer than silently cutting

Do not repair a byte overrun with text.slice(0, limit). Its limit is in code units, not UTF-8 bytes, and it can split a surrogate pair. Iterating by code point avoids that split but can still separate a base letter from its combining mark or break an emoji sequence.

If truncation is a product requirement, define whether the result must preserve grapheme clusters and whether an ellipsis counts towards the budget. Normalisation is another explicit choice: the two accented examples can be made canonically equivalent, but normalising every opaque identifier or signed value can change its meaning.

This is one example of a broader interface rule: preserve the representation until you understand the consuming system. Jitsumi's large JSON identifier guide demonstrates a different failure at that boundary, where converting an identifier to a JavaScript number loses digits before the request is even built.

Write tests containing ASCII, accented text, supplementary characters and combining sequences. Then label the counter honestly: bytes for a storage contract, graphemes for a user-facing character allowance, and code units only when that is truly the intended constraint.

This article was prepared with AI assistance.

Top comments (0)