-
Type:
Bug
-
Resolution: Fixed
-
Priority:
Critical - P2
-
Affects Version/s: None
-
Component/s: 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.