[Fixed] Prisma: TypeError: Do not know how to serialize a BigInt – Prisma

by
Ali Hasan
libmysqlclient nestjs node.js prisma

Quick Fix: Add this code to the beginning of your code to resolve the error:

BigInt.prototype.toJSON = function () {
  const int = Number.parseInt(this.toString());
  return int ?? this.toString();
};

The Problem:

"When fetching data from a database using Prisma, a TypeError is encountered when encountering a specific character (?", specifically ‘?’, in the data. The error message is ‘TypeError: Do not know how to serialize a?’ and is related to JSON serialization. The data in question is a model property with a name that contains the character ‘?’, such as ‘uniq_users?". The goal is to find a way to handle this character during data serialization to prevent the error and successfully fetch the data."
}

The Solutions:

Solution 1: Avoid `JSON.stringify`

To avoid encountering this error, prevent your entity id from being included in a JSON.stringify function. For example, if Prisma returns the following data:

const user = prisma.user.create({ data: { id: 1, name: "user"} })

JSON.stringify(user) will raise an error if the user id is of type BigInt.

To resolve this, convert the BigInt id to a string before stringifying the data:

JSON.stringify({...user, id: user.id.toString()})

Solution 3: **Custom function**

This solution involves creating a custom function to convert BigInt values to strings before serializing them to JSON. Here’s how it works:

  1. Create a helper function:

    Create a function that takes a value as a parameter and converts all BigInts in that value to strings. For example:

    const bigIntToString = (param) => {
      return JSON.stringify(
        param,
        (key, value) => (typeof value === "bigint" ? value.toString() : value) // return everything else unchanged
      );
    };
    
  2. Use the custom function:

    When you need to serialize data from Prisma to JSON, use the custom function you created. For instance:

    const users = await prisma.user.findMany({
      take: 15,
    });
    res.status(200).type('json').send(bigIntToString(users));
    

This custom function ensures that BigInt values are properly converted to strings before serialization, resolving the error you encountered.

Solution

\n
” and the solution provided as:

Q&A

I’m trying to fetch data from database and this is my Prisma model:

It worked for me. Add this code to the beginning of script.

The error is because JSON.stringify doesn’t know how to handle BigInt types.

Create a custom serialiser for BigInt fields before sending them as a response to the client.

This is the most simple and secure way!!! Modifying the Prototype is likely to cause problems later.

Just copy and paste the simple function below.

Video Explanation:

The following video, titled "”How", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

”…

OPTION … UNHANDLED RUNTIME ERROR TYPEERROR: DO NOT KNOW HOW TO SERIALIZE A BIGINT …”]