cloudflare worker polyfill for net, tls, and dns for making mongodb connections work in workerd
npm install cf-mongodb-polyfillsmongodb npm package in a cloudflare worker. It does this by polyfilling the net and tls modules in the mongodb package to use the cf-mongodb-polyfills package instead.
mongodb package to connect to mongodb. This is due to the fact that net.createConnection and tls.connect arent
nodejs_compat or nodejs_compat_v2 compatiblity flags enabled.
module aliasing feature in wrangler.toml, we can replace the net and tls modules in the mongodb package with polyfills in this package. This package provides polyfills for the net and tls modules which will use cloudflare:sockets npm package to create a tcp connection to the mongodb server.
sh
npm install cf-mongodb-polyfills
`
$3
To use the packageĀ in a cloudflare worker app, you must create module aliases in the wrangler.toml to point to the polyfills that are in this package.
`toml
wrangler.toml
...
[alias]
"net" = "@jchoi2x/cf-mongodb-polyfills/net"
"dns" = "@jchoi2x/cf-mongodb-polyfills/dns"
"tls" = "@jchoi2x/cf-mongodb-polyfills/tls"
`
Usage
With these changes in place, you can now use the mongodb package in your cloudflare worker app.
`typescript
import { MongoClient } from 'mongodb';
export default {
async fetch(request, env, ctx): Promise {
// connect to atlas mongodb
const tlsClient = new MongoClient('mongodb+srv://sharedddas:sdfaqwevccfjkjde9ei@dvi.kevpg.mongodb.net/?retryWrites=true&w=majority&appName=dev');
await tlsClient.connect();
// connect to mongo running locally
const client = new MongoClient('mongodb://localhost:27017');
await client.connect();
const db = tlsClient.db('test');
const users = await db.collection('users').find({}).toArray().limit(10);
return Response.json({
users
})
},
} satisfies ExportedHandler;
``