Corrigiendo el error de serialización de BigInt en Node.js + Express (Una explicación amigable para principiantes)

Corrige el error de serialización de BigInt en Node.js y Express con esta guía paso a paso. Aprende a solucionar este problema de forma sencilla y eficaz.

18 nov 2025 • 3 min read • Q2BSTUDIO Team

Corrección de error de serialización de BigInt en Node.js + Express

Corrigiendo el error de serialización de BigInt en Node.js + Express (Una explicación amigable para principiantes)

Si trabajas en backend con Node.js y has migrado de MongoDB a bases SQL como MySQL o PostgreSQL, seguro te habrás topado con columnas id o timestamps en tipo BIGINT. Al recuperar registros y devolverlos con res.status(200).json(data) Node puede lanzar el error TypeError: Do not know how to serialize a BigInt y la respuesta no se envía.

¿Por qué JSON no acepta BigInt? JSON solo soporta string number boolean null object array. BigInt no está incluido, así que cuando Express ejecuta internamente JSON.stringify sobre un objeto que contiene BigInt falla, por ejemplo JSON.stringify({ id: 123n }) provoca un error.

Soluciones iniciales suelen pasar por convertir manualmente todos los BigInt a string recorriendo objetos, pero eso es engorroso, propenso a errores con objetos anidados y añade procesamiento extra en cada endpoint. La solución más limpia es habilitar una serialización global para BigInt.

La solución práctica y sencilla que funcionó es sobrescribir el método toJSON de BigInt para que devuelva su representación en texto. Un ejemplo de utilitario es el siguiente:

const setupBigIntSerialization = () => { BigInt.prototype.toJSON = function () { return this.toString(); }; };

Al ejecutar setupBigIntSerialization() al arrancar la aplicación, JSON.stringify detecta que BigInt tiene un método toJSON y usa su valor de retorno, por lo que JSON.stringify({ id: 123n }) devuelve { id: 123 } en formato texto y no lanza excepción. De esta forma todas las respuestas res.json() de Express serializan BigInt de forma segura y automática.

¿Dónde poner esto en tu proyecto? Paso a paso práctico: crea un archivo utils/bigintSerialization.js con la función setupBigIntSerialization, luego en tu entry file server.js o app.js importa y ejecuta setupBigIntSerialization(); antes de montar las rutas. Ejemplo de uso en la práctica: import setupBigIntSerialization from ./utils/bigintSerialization.js setupBigIntSerialization();

¿Por qué no convertir BigInt a Number? Porque perderías precisión con valores grandes. Number(123456789012345678901n) produce pérdida de precisión al usar doble precisión flotante. La conversión segura es BigInt a string, no a number.

Explicación breve del mecanismo: JSON.stringify comprueba si el valor tiene un método toJSON y usa su retorno. Al definir BigInt.prototype.toJSON estamos diciendo cómo debe convertirse cualquier BigInt en JSON, la misma técnica que usa JavaScript para Date u otras clases con toJSON personalizado.

En Q2BSTUDIO, empresa especializada en desarrollo de software y aplicaciones a medida, aplicamos soluciones sencillas y robustas como esta para garantizar APIs estables y seguras. Si tu proyecto requiere aplicaciones a medida o integración con servicios avanzados de inteligencia artificial podemos ayudarte a diseñar una arquitectura que incluya buenas prácticas de serialización, seguridad y rendimiento. También trabajamos en ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio, ia para empresas, agentes IA y power bi para ofrecer soluciones completas.

Resumen rápido: 1) Evita convertir BigInt a Number por pérdida de precisión. 2) Implementa globalmente BigInt.prototype.toJSON para devolver this.toString(). 3) Llama a la configuración al inicio de tu servidor para que todas las respuestas JSON sean compatibles. Esta pequeña mejora elimina errores, simplifica tu código y protege tus endpoints ante valores grandes en ids o timestamps.

Si quieres, en Q2BSTUDIO podemos acompañarte en la implementación, revisar tu stack y ofrecer soluciones integrales que incluyen software a medida, seguridad y despliegue en la nube, optimizando tanto el backend como la experiencia del usuario.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat