Postgres jsonb "unsupported Unicode escape sequence": remove NUL before the insert
Remove the NUL character from every string before you write to a jsonb column. Postgres can’t store U+0000 in jsonb, and one \u0000 anywhere in a document fails the whole insert:
ERROR: unsupported Unicode escape sequence
DETAIL: \u0000 cannot be converted to text.
SQLSTATE: 22P05
jsonb keeps strings as Postgres text, and Postgres text has no NUL. The JSON types page says so in its section on Unicode escapes. The JSON is valid, and JSON.stringify writes it without complaint, so nothing warns you before the database does.
How it showed up
An app of mine caches the answers of a third-party API in a jsonb column, so a repeated call costs nothing. One kind of answer carried a binary video manifest inside a string, NUL characters included. Every write of that kind failed. The failure was caught and logged, the call still returned its answer, and each repeat would have been paid for again.
A daily self-test found it on its first run against the real API: that one tool never came back from the cache.
The fix
Clean the value on its way in, strings and object keys both:
export function withoutNul<T>(v: T): T {
return clean(v) as T;
}
function clean(v: unknown): unknown {
if (typeof v === "string") return v.includes("\u0000") ? v.replaceAll("\u0000", "") : v;
if (Array.isArray(v)) return v.map(clean);
if (v && typeof v === "object" && !(v instanceof Date)) {
const out: Record<string, unknown> = {};
for (const [k, x] of Object.entries(v)) {
Object.defineProperty(out, k.replaceAll("\u0000", ""), {
value: clean(x), enumerable: true, writable: true, configurable: true,
});
}
return out;
}
return v;
}
Object.defineProperty is there for one key. A parsed JSON document can have a field named __proto__, and out["__proto__"] = x sets the copy’s prototype and drops the field. Defining the property keeps it as a plain field. A review caught that in my first version, which assigned.
Call it at every write of outside data, here the cache and the saved search results:
await db.insert(cache).values({ key, data: withoutNul(answer.data) });
What the other column types do
Checked on PostgreSQL 18.6, in PGlite:
| Column | With a NUL in a string |
|---|---|
jsonb |
Refused on insert, with 22P05. |
json |
Accepted, because json stores the text as sent. Reading the value with -> or ->> then fails with the same 22P05. |
text |
A raw NUL byte is refused with 22021, invalid byte sequence for encoding "UTF8": 0x00. |
So json moves the error from the write to a later read. If you need the bytes exactly, keep them out of JSON and store them as bytea.
Log the reason, not the row
The failed write was logged with the whole error object. A database driver’s error carries the query’s parameters, which here was the full API answer with people’s details in it. The log line now holds Postgres’s code and message and nothing from the data:
console.error(`cache: storing ${tool} failed: ${code} ${message}`);