Carrying a localized label in HTTP with RFC 9651 Display Strings
Encode a Turkish maintenance label as an RFC 9651 Display String. A local Node.js exercise checks quotes, percent signs and malformed UTF-8.
Archive retrospective · Topic year 2024
In this article
Define the field around its consumer
Imagine a service sending a short operator-facing label with an HTTP response. The label describes a cold room in a warehouse in Istanbul. If the console also treats the label as an asset identifier, changing language could change which asset an operation targets. Start with a stable machine identifier and a separate display value. RFC 9651, published in September 2024, updated the Structured Fields model for describing HTTP field values. Its Display String type can carry Unicode text intended for a person. The ordinary String type covers printable ASCII. This example assumes the service defines its own field for the label. The RFC defines a data type and wire form, without assigning a header name or product behavior to this application. Document what the sender and consumer have agreed to support before enabling the field.
Follow the bytes from text to the field
The wire item begins with a percent sign and a double quote. The encoder converts the supplied text to UTF-8. It percent-encodes percent signs, double quotes, control bytes and bytes outside printable ASCII, using lowercase hexadecimal digits. An ordinary space is transmitted directly. Turkish capital İ becomes two UTF-8 bytes, c4 and b0, and appears on the wire as %c4%b0. An emoji would similarly produce a separate escape for each UTF-8 byte. A percent-encoded Display String is not a URL component. Apply this decoding at the field parser boundary and avoid feeding the result into a URL decoder. The same rule protects a literal percent sign that an operator expects to see. A capture of the field value can make such representation differences visible during integration.
Run the test with Node.js
The sample includes an Istanbul location, double quotes and a literal percent sign. It encodes the string and checks that decoding reproduces the original value exactly. The quotes appear as %22 and the percent as %25. Other cases feed the parser uppercase hexadecimal digits, a broken UTF-8 sequence and extra characters after the closing quote. The local run rejects all three. The decoder uses a fatal UTF-8 mode so invalid input cannot silently turn into replacement characters. The test runs on a modern Node.js installation. The September 2024 RFC describes interoperable values independent of that runtime. This example accepts one bare Display String and applies the field's full-consumption check. A service accepting arbitrary parameters, lists or dictionaries needs a fuller implementation.
import assert from 'node:assert/strict';
function encodeDisplay(value) {
if (!value.isWellFormed()) throw new TypeError('Malformed Unicode');
let formatted = '%"';
for (const byte of new TextEncoder().encode(value)) {
const escaped = byte < 0x20 || byte >= 0x7f || byte === 0x22 || byte === 0x25;
formatted += escaped ? '%' + byte.toString(16).padStart(2,'0') : String.fromCharCode(byte);
}
return formatted + '"';
}
function decodeDisplayItem(field) {
if (!field.startsWith('%"') || !field.endsWith('"')) throw new Error('Invalid item boundary');
const body = field.slice(2,-1);
const bytes = [];
for (let index = 0; index < body.length; index++) {
const char = body[index];
if (char === '%') {
const hex = body.slice(index + 1,index + 3);
if (!/^[0-9a-f]{2}$/.test(hex)) throw new Error('Invalid escaped byte');
bytes.push(Number.parseInt(hex,16));
index += 2;
} else {
const literal = char.charCodeAt(0);
if (literal < 0x20 || literal >= 0x7f || char === '"') throw new Error('Invalid literal');
bytes.push(literal);
}
}
return new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(Uint8Array.from(bytes));
}
const label = 'İstanbul: "Soğuk Oda" %20';
const wire = encodeDisplay(label);
assert.equal(wire,'%"%c4%b0stanbul: %22So%c4%9fuk Oda%22 %2520"');
assert.equal(decodeDisplayItem(wire),label);
assert.throws(()=>decodeDisplayItem('%"%C4%b0"'));
assert.throws(()=>decodeDisplayItem('%"%c4"'));
assert.throws(()=>decodeDisplayItem('%"Deneme", "fazla"'));
console.log(JSON.stringify({wire,roundTrip:true,rejected:3}));
A human label does not announce its language
Display String is a text type. The value alone does not specify the language a consumer should use to pronounce, display or group it. An application may need to define a language parameter or carry the selected language elsewhere in its HTTP contract. If the response varies by language and passes through a shared cache, verify the cache key and relevant request headers. A stable machine identifier allows a catalog translation to change without rewriting asset records. Unicode normalization and characters that look similar across scripts are separate issues. Define search behavior where users look up names rather than trying to infer identity from the spelling of a label. Trace which part of the stack selects the language so an incorrect cached label can be reproduced.
Validate how the decoded text is used
A value that parses correctly can contain characters a product does not want to display. The wire encoding allows escaped bytes that can decode to control characters. When adding the label to HTML, use a text node or the framework's normal text escaping. A display policy can impose a length limit and decide which control characters the console accepts. Keep the parsing error distinct from a value rejected for its intended field. If a display-only field is unusable, the console may show a stable asset identifier and record the reason for the fallback. Integration tests can use invented asset names and known edge cases. No real account or operator information is needed to verify any of these behaviors.
Check compatibility at the boundary
An older Structured Fields library may implement the earlier specification. Test the actual client, proxy and application together before relying on the new item type. Build a fixture set with plain ASCII, Turkish letters, an emoji, a literal percent, an escaped quote and incomplete UTF-8. Maintain separate outcomes for the protocol parser and for the display policy. A valid transport value may still be inappropriate in a particular UI. RFC 9651 also added a Date type, which has a different wire prefix and a different purpose. A calendar timestamp would need its own field contract if operators later ask for it. End-to-end checks are easier to maintain when the wire type, application meaning and rendering rules each have their own expected result.
Reader discussion
What would you change first for maintainability and testing in your own project?
No comments yet. Be the first to contribute.
Write a comment