Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

195
Views
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.

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!