Handling JSON BigInt in Axios Responses

JavaScript handles numbers using the IEEE 754 double-precision standard, causing integer values larger than Number.MAX_SAFE_INTEGER (\(2^{53} - 1\)) to lose precision when parsed with the native JSON.parse() method. Because Axios uses JSON.parse() by default for response bodies, 64-bit integers (such as database IDs, snowflake IDs, or financial amounts) often get corrupted automatically. To resolve this issue, you must override the default transformation behavior of Axios using a specialized parsing library like json-bigint.

The Cause of the Precision Loss

When an API returns a JSON payload containing large integers (e.g., {"id": 9223372036854775807}), Axios automatically processes the string response using JSON.parse(). The native parser rounds the number to the nearest representable floating-point value, turning 9223372036854775807 into 9223372036854776000.

The Solution: Using json-bigint with Axios

The standard solution is to install json-bigint and configure Axios to use it via the transformResponse option.

Step 1: Install the Dependency

npm install json-bigint
# or
yarn add json-bigint

Step 2: Configure a Custom Axios Instance

Create an Axios instance and override transformResponse so that it intercepts raw text data before the default parser executes:

import axios from 'axios';
import JSONBigInt from 'json-bigint';

// Configure json-bigint
// Set `storeAsString: true` to convert large integers into strings,
// or `useNativeBigInt: true` to convert them into JavaScript BigInt primitives.
const JSONbig = JSONBigInt({ storeAsString: true });

const apiClient = axios.create({
  baseURL: 'https://api.example.com',
  // Disable automatic parsing by passing a custom transformResponse
  transformResponse: [
    function (data) {
      if (typeof data === 'string') {
        try {
          return JSONbig.parse(data);
        } catch (err) {
          return data; // Fallback if data is not valid JSON
        }
      }
      return data;
    },
  ],
});

export default apiClient;

Parsing Configuration Options

json-bigint provides two primary strategies for handling values exceeding safe limits:

  1. storeAsString: true: Recommended if your application passes IDs directly to UI elements or URL parameters without performing mathematical calculations. It keeps the values safe from unintended numeric conversions.
  2. useNativeBigInt: true: Recommended if your application performs arithmetic operations on the values using modern JavaScript environments supporting native BigInt.

Handling Outgoing Requests

If you need to send JavaScript BigInt types back to the server in request bodies, native JSON.stringify() will throw a TypeError: Do not know how to serialize a BigInt. To resolve this, configure transformRequest:

const apiClient = axios.create({
  baseURL: 'https://api.example.com',
  transformRequest: [
    function (data, headers) {
      if (typeof data === 'object' && data !== null) {
        headers['Content-Type'] = 'application/json';
        return JSONbig.stringify(data);
      }
      return data;
    },
  ],
  transformResponse: [
    function (data) {
      if (typeof data === 'string') {
        try {
          return JSONbig.parse(data);
        } catch (err) {
          return data;
        }
      }
      return data;
    },
  ],
});

By explicitly overriding both transformResponse and transformRequest, Axios safely handles high-precision numbers across full client-server communication cycles.