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

Time:06-11

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.

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.

CodePudding user response:

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.

  • Related