Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
Which is the most elegant way to extend a native object in a NodeJS project?

I have a NodeJS project that uses BigInt for its model's ids. I also have a WebSocket where I sent serialized objects to a client. The problem with BigInt is that it is not serializable like other objects (Boolean, Number, etc). Therefore I use MDN recommendation to define a global handler function the BigInt object.

BigInt.prototype.toJSON = function() { return this.toString()  }

I will use this in the entire app scope from now on.

The question is where do I place this code so it is elegant and respects SOLID principles?

I am looking for a good solution for kind of issue.

Currently it is placed in index.js like this:

import 'dotenv/config';
import cors from 'cors';
import express from 'express';
import logger from './middleware/logger';

const main = async () => {
  // where should I modularise BigInt extension
  BigInt.prototype.toJSON = function () {
    return this.toString();
  };

  app.use(cors());

  app.get('/', (req, res) => {
    res.send('Hello World!');
  });

  app.listen(3000, () => console.log(`Example app listening on port 3000!`));
};

main().catch((err) => {
  logger.error(err);
});
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The best practice for this kind of extension is to use the solution for this question.

I've refactored the code like this.

utils.ts

(BigInt.prototype as any).toJSON = function () {
  return this.toString();
};

index.ts

import 'dotenv/config';
import cors from 'cors';
import express from 'express';
import logger from './middleware/logger';
import "utils.ts" // <== this code gets executed, therefore BigInt extenstion is in the scope of project from now on

const main = async () => {
  app.use(cors());

  app.get('/', (req, res) => {
    res.send('Hello World!');
  });

  app.listen(3000, () => console.log(`Example app listening on port 3000!`));
};

main().catch((err) => {
  logger.error(err);
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!