Pretty sure you can use globalThis to alleviate these problems… check out this repo I just whipped up to test… https://github.com/mrlynn/globalThisExampleNext
The secret sauce:
if (process.env.NODE_ENV === 'development') {
if (!globalThis._mongoClientPromise) {
console.log(`🌱 [${clientId}] Creating NEW MongoClient instance (dev)`);
client = new MongoClient(uri, options);
globalThis._mongoClientPromise = client.connect();
globalThis._mongoClientId = clientId;
} else {
console.log(`♻️ Reusing MongoClient [${globalThis._mongoClientId}] (dev)`);
}
clientPromise = globalThis._mongoClientPromise;
} else {
// Production/serverless
console.log(`🚀 [${clientId}] Creating MongoClient instance (prod/serverless)`);
client = new MongoClient(uri, options);
clientPromise = client.connect();
}
I think this should work… try it and let me know.
Regards,
Mike