Skip to content
← cd ../posts
[Developer Tools]5 min read

Large JSON IDs: Stop JavaScript From Rounding Database Keys

Keep large database IDs exact across JSON APIs with string contracts, boundary validation, and runnable JavaScript precision tests.

Two distinct identifier cards pass through a precise string-preserving channel while a lossy numeric funnel merges another pair.

Quick answer

If an identifier can exceed JavaScript's safe integer range, send it as a JSON string and keep it a string through the client. Validate the field at the API boundary. Converting an already-rounded Number to a string or BigInt cannot recover the original digits. Fix the earliest conversion that lost precision, not just the component displaying the ID.

A support dashboard opens the wrong order. The database row looks correct, the API returns valid JSON, and the frontend reports no parsing error. The clue is a final digit that changed somewhere between the response and the route parameter. This is an identity bug: two records can become indistinguishable before your lookup code runs.

Valid JSON does not guarantee an exact JavaScript number

JSON permits numeric tokens whose precision exceeds what a particular implementation preserves. RFC 8259, section 6 describes the interoperable integer range for implementations using binary64 numbers. JSON syntax validation alone does not establish that an identifier will survive every consumer.

JavaScript's safe integers run from -(2 ** 53 - 1) through 2 ** 53 - 1, or plus/minus 9,007,199,254,740,991. Some integers beyond that range are representable, but adjacent integers are no longer all distinguishable. Number.isInteger() only tests whether a Number is integral; use Number.isSafeInteger() when validating a numeric integer contract. See MDN's safe-integer reference.

An ID is usually a label used for equality, routing, or joins. You do not need floating-point arithmetic to carry it from the API to an order page. A string contract avoids forcing that label through an unnecessary numeric conversion.

Reproduce the failure with the original response text

Save the following as json-id-lab.mjs and run node json-id-lab.mjs using a supported Node.js installation. It uses the built-in assertion module and makes no network requests. The JSON fixture is a string on purpose: placing the long ID in a JavaScript numeric literal would lose information before JSON.parse even entered the picture.

javascript
import assert from 'node:assert/strict'

// Keep the original JSON as text so the test fixture is not rounded first.
const raw = '{"id":9007199254740993}'
const rounded = JSON.parse(raw).id
assert.equal(String(rounded), '9007199254740992')
assert.equal(Number.isInteger(rounded), true)
assert.equal(Number.isSafeInteger(rounded), false)

// Distinct JSON IDs have collapsed to the same JavaScript Number.
const neighbor = JSON.parse('{"id":9007199254740992}').id
assert.equal(rounded, neighbor)
assert.equal(BigInt(rounded), 9007199254740992n)

// This API contract uses positive decimal IDs with at most 20 digits.
// The exact range must also be enforced by the real database/domain layer.
function readId(value) {
  if (typeof value !== 'string' || !/^[1-9][0-9]{0,19}$/.test(value)) {
    throw new TypeError('ID must be a positive decimal string of 1-20 digits')
  }
  return value
}

function readOrder(json) {
  const value = JSON.parse(json)
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
    throw new TypeError('Expected an order object')
  }
  return { id: readId(value.id) }
}

const exact = readOrder('{"id":"9007199254740993"}')
assert.equal(exact.id, '9007199254740993')
assert.equal(JSON.stringify(exact), '{"id":"9007199254740993"}')
assert.notEqual(exact.id, readOrder('{"id":"9007199254740992"}').id)
assert.equal(BigInt(exact.id) + 1n, 9007199254740994n)
assert.throws(() => JSON.stringify({ id: BigInt(exact.id) }), TypeError)

for (const value of [9007199254740992, 42, null, '', '0012', '0', '-1', '1e3', ' 12 ', '9'.repeat(21)]) {
  assert.throws(() => readId(value), TypeError)
}
assert.equal(readId('42'), '42')
assert.equal(readId('9'.repeat(20)), '9'.repeat(20))
assert.equal(Number.isSafeInteger(Number.MAX_SAFE_INTEGER), true)
assert.equal(Number.isSafeInteger(Number.MAX_SAFE_INTEGER + 1), false)
for (const rawOrder of ['null', '[]', '{}', '{"id":42}']) {
  assert.throws(() => readOrder(rawOrder), TypeError)
}

console.log(`Rounded numeric ID: ${rounded}`)
console.log(`Exact string ID: ${exact.id}`)
console.log('All precision, round-trip, and validation checks passed.')

The output is three lines: Rounded numeric ID: 9007199254740992, Exact string ID: 9007199254740993, and All precision, round-trip, and validation checks passed. The first assertion captures the bad behavior instead of assuming it. The remaining assertions verify the proposed contract, reject malformed IDs, and test both sides of the safe-integer boundary.

Our sample permits positive decimal strings with one to twenty digits and no leading zeros. That is an example application contract, not a universal definition of an ID. Twenty digits do not automatically fit a signed or unsigned 64-bit database column; enforce the actual domain range separately. Systems with prefixed identifiers, zero-valued keys, or meaningful leading zeros need a different validator.

Trace the first lossy conversion

Start with a harmless failing fixture and preserve the raw response body before prettifying or reserializing it. A tool that parses JSON into JavaScript Numbers and then prints it may already have changed an unquoted large integer. Keep the original bytes as evidence, and use the JSON troubleshooting workflow to separate malformed syntax from a value that changed after parsing.

Follow one identifier through the pipeline: database driver result, server object, serialized response, browser parse, state store, route parameter, and outbound request. At each point record its type and exact representation. Use a synthetic ID in logs or a redacted fixture when actual identifiers are sensitive. If the server object is already rounded, adding quotes in the frontend merely preserves the wrong value.

Search the conversion boundaries for Number(id), unary plus, parseInt, automatic schema coercion, and numeric input handling. A schema declaration that calls a value an integer does not control how every runtime represents it. Check the actual driver and serializer configuration in your application before assuming the database-to-API hop is exact.

For example, a route built from the string "9007199254740993" keeps that spelling. A route built after Number() receives 9007199254740992 in this fixture. If the request reaches the wrong endpoint, the URL query debugging checklist helps inspect what was sent, but it cannot restore an ID that was rounded earlier.

Convert to BigInt only when the operation needs it

BigInt can represent the exact integer when constructed from the preserved decimal string. It cannot infer lost digits from an unsafe Number. In the example, BigInt(rounded) retains the wrong value, while BigInt(exact.id) starts from the original digits. Keep opaque IDs as strings unless the domain actually requires integer operations.

JSON.stringify does not serialize a BigInt by default. The test deliberately expects a TypeError. At an API boundary, explicitly convert the known ID field back to its agreed decimal-string representation. Avoid silently changing unrelated fields through a global prototype patch or an indiscriminate replacer. MDN's BigInt JSON guidance explains the serialization tradeoffs.

An ordinary JSON.parse reviver receives a numeric value after parsing, so wrapping that value in BigInt is too late. Runtimes supporting the reviver's context.source can expose the original numeric token for a field-aware conversion; verify support in every target runtime before relying on it. A dedicated lossless parser is another option when you cannot change a numeric wire contract. MDN's JSON.parse reference documents the source-text mechanism. Neither approach repairs a token that the producer already rounded.

Migrate the contract without hiding mixed types

For a new API, make the ID field a string from the start, including small values such as "42". A field that changes from number to string only when it grows large makes consumers handle two representations. Document the spelling, length, leading-zero policy, and whether comparison is textual or numeric.

For an existing API, treat a field-type change as a compatibility change. Inventory consumers, introduce a versioned response or a clearly named string field where needed, and test the transition. If a temporary adapter accepts numeric IDs, reject unsafe or non-integral Numbers rather than calling String on everything. This only checks the Number you received; it is not proof that every upstream transformation was lossless.

Add adjacent large IDs to regression fixtures. A test using only 1, 2, and 3 will miss this failure. Confirm that cache keys, map keys, selections, links, and requests keep the two fixtures distinct. A numeric sort and a lexicographic string sort can also produce different orders; select an ordering rule intentionally rather than coercing the IDs to Number.

A precision checklist before shipping

  • Preserve a raw failing payload before using a parser or formatter.
  • Check every ID field's wire type and the receiving runtime's representation.
  • Find the earliest Number conversion, including driver and serializer boundaries.
  • Use one consistent string contract for opaque IDs, with explicit validation.
  • Test adjacent values around the safe-integer boundary and one realistic large ID.
  • Assert exact parse/serialize round trips and distinct cache or selection keys.
  • Reject unsafe numeric input instead of turning a rounded value into a string.
  • Keep database range checks and consumer compatibility tests separate from JSON syntax checks.

The useful end state is a small, executable fixture that fails at the old conversion and passes under the explicit contract. When a key identifies a record, preserving every digit is part of correctness, even if the JSON itself was always valid.

Related Posts

Useful Tools For This Topic

explore_all →