Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What's wrong with writing to a global variable In production mode?

I looked at the sample code for connecting mongodb and saw a sentence that I did not understand.

Why is it safe to use global variables in the case of development ?
And why is not in production ?

You don’t need to understand the code. Please see only the comments section.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import { MongoClient } from 'mongodb'

let client
let clientPromise

if (process.env.NODE_ENV === 'development') {
  // In development mode, use a global variable so that the value
  // is preserved across module reloads caused by HMR (Hot Module Replacement).
  if (!global._mongoClientPromise) {
    client = new MongoClient(uri, options)
    global._mongoClientPromise = client.connect()
  }
  clientPromise = global._mongoClientPromise
} else {
  // In production mode, it's best to not use a global variable.
  client = new MongoClient(uri, options)
  clientPromise = client.connect()
}

// Export a module-scoped MongoClient promise. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise

If this was just about good quality code, it would be better not to use global variables in the development environment as well.

I’m not sure what’s wrong with writing to a global variable In production env.

>Solution :

It has to do with using "Hot Module Replacement" in development for improving development productivity. Not something you would do in a production environment.

In hot module replacement, module-level variables like client and clientPromise would get replaced when the module was "hot replaced", but globals would be preserved.

It’s a development "trick", not something to do in production.

Personally, I wouldn’t even do it in development either because I’d rather be running code that is as close to production as possible when in development except for things that must be different.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading