contact

Handling BigInt in JavaScript

The BigInt serialization error I ran into while working on a Node.js backend

What is BigInt?

Type Size Range Roughly Note
number 4 bytes $-2^{31}$ ~ $2^{31}-1$ about 2 billion
BigInt 8 bytes $-2^{63}$ ~ $2^{63}-1$ about 9.2 quintillion Added in ES2020

BigInt is a type that showed up in 2020, and it can pretty much hold any number you'd ever need in real life. The catch is that if you call JSON.stringify() on an object that has a BigInt in it, you get this:

TypeError: Do not know how to serialize a BigInt

Why it happens

On the backend, you usually hit this when talking to the client. It goes something like this:

1. The DB ORM hands you a value as a `BigInt` (usually an id)

2. That value ends up in the object you're about to return, still as a `BigInt`

3. Right before the API response goes out, `JSON.stringify()` runs and blows up

JSON.stringify() knows how to handle the 6 types that exist in the JSON spec: number, string, object, array, boolean and null. For anything else, it looks for a toJSON() function on the type's prototype and uses that.

The problem is that BigInt came in with ES2020 and nobody defined BigInt.prototype.toJSON(), so there's just no way for it to be serialized.

Date is in the same spot, but it's been around since the early days of JavaScript. When ES5 landed in 2009 it got Date.prototype.toJSON(), so it doesn't throw like BigInt does.

How to fix it

After some digging I found that MDN lists 3 ways to avoid the TypeError.

  1. Don't use BigInt at all and just use number

    Number(value);
  2. Pass your own serialization logic to JSON.stringify() so it turns BigInt into a string or number

    JSON.stringify(data, (key, value) => (typeof value === "bigint" ? String(value) : value));
  3. Define BigInt.prototype.toJSON() yourself

    declare global {
        interface BigInt {
            toJSON: () => string;
        }
    }
    
    BigInt.prototype.toJSON = function () {
        return this.toString();
    };

Option 1 kind of defeats the point of using BigInt. Option 3 changes how JSON.stringify() behaves everywhere, including inside all the libraries you depend on, so it could break things in ways you won't see coming. So I went with option 2.

From what I could tell, turning BigInt into a string is the usual way to go, since the big number stays exactly as it is. That means every time JSON.stringify() runs, all the BigInt values in the object need to become strings first.

Doing it in NestJS

NestJS has Interceptors, which let you process data right before the response goes out. That makes it easy to apply this globally.

Steps

  1. Use String instead of BigInt in your DTOs (the value comes in as a string in the request body)

  2. Convert the string to BigInt right before talking to the ORM and use it in the DB query

  3. Set up an Interceptor that turns BigInt into string right before the response is built

// src/common/interceptors/bigint-to-string.interceptor.ts

import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from "@nestjs/common";
import { Observable } from "rxjs";
import { map } from "rxjs/operators";

@Injectable()
export class BigIntToStringInterceptor<T = unknown> implements NestInterceptor<T, unknown> {
    intercept(context: ExecutionContext, next: CallHandler<T>): Observable<unknown> {
        return next.handle().pipe(map((data) => this.transform(data)));
    }

    // Finds only the BigInt values inside the object and turns them into strings
    // Arrays go through map
    // Objects get handled recursively
    // Everything else is left alone for JSON.stringify() to deal with
    private transform(data: unknown): unknown {
        if (data === null || data === undefined) {
            return data;
        }

        if (typeof data === "bigint") {
            return data.toString();
        }

        if (Array.isArray(data)) {
            return data.map((item) => this.transform(item));
        }

        if (typeof data === "object" && data !== null) {
            const transformedObject: Record<string, unknown> = {};
            for (const [key, value] of Object.entries(data)) {
                transformedObject[key] = this.transform(value);
            }
            return transformedObject;
        }

        return data;
    }
}
// src/main.ts

import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import { BigIntToStringInterceptor } from "./common/interceptors/bigint-to-string.interceptor";

async function bootstrap() {
    const app = await NestFactory.create(AppModule);

    // Register the interceptor globally
    app.useGlobalInterceptors(new BigIntToStringInterceptor());

    await app.listen(3000);
}

bootstrap();

References

MDN - TypeError: BigInt value can't be serialized in JSON

Stack Overflow - Serialize BigInt in JSON

← blog