Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

196
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda