Cloudflare Workers: top-level `import { MongoClient }` fails at startup (v7)

XMLWordPrintableJSON

    • Type: Bug
    • Resolution: Fixed
    • Priority: Critical - P2
    • bson-7.3.2
    • Affects Version/s: None
    • Component/s: None
    • None
    • 2
    • 3
    • Not Needed
    • None
    • Hide

      Create a copy of the Kickoff Template with the issue key (NODE-XXX) in the filename and share a link to the new doc via this field.

      Show
      Create a copy of the Kickoff Template with the issue key (NODE-XXX) in the filename and share a link to the new doc via this field.
    • Not Needed
    • None
    • None
    • None
    • None
    • None
    • None

      See original user post on Reddit:

      https://www.reddit.com/r/mongodb/comments/1urz0zl/cloudflare_workers_toplevel_import_mongoclient/ 

       


      If I try to import and initialize my client in a CF worker like this:

      import { MongoClient } from 'mongodb';
      

      I get an error:

      Uncaught Error: Disallowed operation called within global scope.
      Asynchronous I/O (ex: fetch() or connect()), setting a timeout, and generating random values are not allowed within global scope.
      

      Workers intentionally disallow generating random values during module evaluation. The crash happens before any request runs.

      This wasn't an issue with v6, it started in v7.

      The workaround is to do a dynamic import of the 'mongodb' library, but I have other packages that do top-level imports so this isn't really viable.

      I.e.

      const { MongoClient } = await import('mongodb');
      

      Repro: https://github.com/ozzyonfire/mongodb-worker-example (mongodb@7.5.0 → bson@7.3.1)

      Cause: In bson, ObjectId calls ByteUtils.randomBytes(5) in a static {} block during module load (process-unique bytes / startup-snapshot reset). Workers forbid random at global scope, so any package with a top-level mongodb import is blocked.

      Would the bson team consider lazy-init of that state on first use instead? Not sure how it worked in v6...

      P.S.

      This feels strange to post on reddit, but I couldn't find a recommended way to submit these types of requests. The official community forums pointed me here. And there was no way to log an issue on mongodb/js-bson.

            Assignee:
            Pavel Safronov
            Reporter:
            Raschid Jimenez
            Sergey Zelenov
            Votes:
            1 Vote for this issue
            Watchers:
            6 Start watching this issue

              Created:
              Updated:
              Resolved: