Whitespace bugs usually enter at the boundary: copied environment variables, CSV imports, form fields, and pasted identifiers. Trim data that has a grammar forbidding outer whitespace, but do not normalise every string in sight—names, passwords, and free text have different rules.
const email = input.email.trim().toLowerCase();
if (!email.includes('@')) throw new Error('Invalid email');
Give every field a policy
| Field | Boundary rule | Why |
|---|---|---|
| API key | Trim outer whitespace only if provider documents it | A trailing newline from a secret store is common |
| Trim outer whitespace; normalise domain carefully | Users paste addresses with spaces | |
| Password | Do not trim | Whitespace may be intentional entropy |
| Free-text comment | Preserve; normalise only for display/search policy | Formatting can carry meaning |
Diagnose invisible characters
console.log(JSON.stringify(value), [...value].map(c => c.codePointAt(0).toString(16)));
This reveals a non-breaking space (a0), zero-width character, or newline that ordinary logging hides. It is especially useful when two strings look identical but fail a map lookup or signature verification.
Normalisation must happen before the value becomes an identifier, cache key, or signature input. Changing it later can create two representations of the same logical record.
Document the rule beside validation and test leading, trailing, newline, and Unicode-space cases. “Just call trim()” is a good fix only after you know the field is meant to be trimmed.
