Most people advise against using global variables. If you want the same logger class in different modules you can do this

logger.js

  module.exports = new logger(customConfig);

foobar.js

  var logger = require('./logger');
  logger('barfoo');

If you do want a global variable you can do:

global.logger = new logger(customConfig);
Answer from Pickels on Stack Overflow
🌐
Node.js
nodejs.org › api › globals.html
Global objects | Node.js v25.8.1 Documentation
You can figure out which version of undici is bundled in your Node.js process reading the process.versions.undici property. You can use a custom dispatcher to dispatch requests passing it in fetch's options object. The dispatcher must be compatible with undici's Dispatcher class. ... It is possible to change the global dispatcher in Node.js by installing undici and using the setGlobalDispatcher() method.
Discussions

Why are global variables considered bad practice? (node.js)
I'm currently face with a problem where I have two modules that I call that need to be able to modify the same variable. I decided to create a global variable called global.APP_NAME = {} and store ... More on stackoverflow.com
🌐 stackoverflow.com
Node.js global variables - javascript
I asked here: Does Node.js require inheritance? And I was told that I can set variables to the global scope by leaving out the variable. This does not work for me. That is, the following does not m... More on stackoverflow.com
🌐 stackoverflow.com
How to deal with global variables when modularizing a node.js app?
As much as possible, anything that a function changes should be returned from it rather than modified in place. The purer a function is, the easier it is to test, to reason about, and to compose. Your second best bet if that's impractical is to turn the globals into data attached to the "this" object that your functions are being called as methods on. This still improves your ability to reason about data because it is scoped to a set of functions rather than the whole program. I would caution you against having a giant "context" object that holds all of the mutable globals that you pass around to every function. This is the easiest thing to do when refactoring from a program with lots of globals, but it doesn't actually buy you much over the globals. You're still left with a lot of implicit state that you need to set up before calling each function. More on reddit.com
🌐 r/node
4
1
May 7, 2016
Best Practice: Where do I store global objects in Node.js apps?

I generally would do a separate file. Remember, exports are application singletons, so you can import in an index.js file, modify it, and any other file that imports the object gets the same modified object when they import from it.

You just have to make sure the other files use the modified version only after the index file modifies the object. Trying to make a connection before your index file registers the credentials is a common async mistake.

More on reddit.com
🌐 r/node
16
15
December 1, 2014
People also ask

How are global objects in Node js different from local variables?
Global objects in Node js are accessible throughout the entire application, regardless of scope or module. In contrast, local variables are confined to the block or function in which they are defined. Global objects, like process or global, are available everywhere, making them useful for application-wide configuration management. On the other hand, local variables maintain modularity by limiting scope, which helps ensure encapsulation.
🌐
knowledgehut.com
knowledgehut.com › home › blog › software development › global objects in node js: how they can make or break your code?
Don't Ship Code Without Knowing Global Objects in Node js!
How can the global object be used for debugging in Node.js?
The global object can be leveraged to define properties or functions that are accessible across the application, which assists with debugging. For example, custom loggers or state inspectors can be attached to global to help trace issues. This makes it possible to inspect or modify variables without importing them into every module. However, caution is necessary, as this can introduce side effects.
🌐
knowledgehut.com
knowledgehut.com › home › blog › software development › global objects in node js: how they can make or break your code?
Don't Ship Code Without Knowing Global Objects in Node js!
How do global objects in Node js contribute to error handling?
Global objects, like process, play a key role in error handling in Node.js applications. For example, process.on('uncaughtException') allows you to catch unhandled exceptions, preventing the application from crashing. By listening for specific error events, you can log or handle errors more gracefully. Additionally, process.exit() can be used to shut down the application cleanly after handling critical errors.
🌐
knowledgehut.com
knowledgehut.com › home › blog › software development › global objects in node js: how they can make or break your code?
Don't Ship Code Without Knowing Global Objects in Node js!
🌐
Stack Abuse
stackabuse.com › using-global-variables-in-node-js
Using Global Variables in Node.js
July 8, 2024 - Now that we have a better understanding of what a global variable in Node is, let's talk about how we actually set up and use a global variable. To set up a global variable, we need to create it on the global object. The global object is what gives us the scope of the entire project, rather ...
Top answer
1 of 2
18

Global variables are considered an anti-pattern in almost any programming language because they make it very hard to follow and debug code.

  • When you browse the code, you never know which function sets or uses a global variable. When all variables are either local or passed to a function, you can be sure that the side-effects of the function are limited.
  • Global variables work at a distance. Screwing with the value of a global could have unexpected effects in a completely different part of the application. When you debug an error caused by that, you will have a very hard time finding out where the variable was changed to a wrong value.
  • Global variables share a namespace, so you can inadvertently reuse them although you don't intend to do so.
  • It's hard to tell how important a global variable is. You never know if it's used by just two functions or if its value is important all over the place.
  • ...and many more reasons...

When you have two modules which share data, you should create an object with that data and explicitly pass it to each function which needs it (and only those which actually do).

2 of 2
1

You can read from most of the comments and the other answers why is having a global considered bad practice. However, node.js apps are usually ran from a central point, like "app.js", "server.js" or something similar.

In that case, you can keep some sort of "config" (you said you need APP_NAME.users) as a config option to that file. So in "app.js" you have:

var config = {
  myVar: 100
}

If you need to access this variable in some of the modules, pass it as a parameter. Ie. in global file call it as:

var module = require('./lib/myModule.js').init(config);

Now your module can have it's init function exported, so that it sets its own local copy of config. Example:

var localConfig = null;
exports.init = function(config) {
  // merge the two config objects here
  localConfig.myVar = config.myVar;
}

Finally, you can have your local code affect the global object with it's private value. Something like this in your module:

exports.modifyGlobalConfig = function() {
  global.myVar = myLocalValue;
}

Your global app.js would then use that method to modify it's global value.

🌐
Medium
medium.com › @a.kago1988 › global-objects-variables-and-methods-in-javascript-and-node-js-f6bffc74e792
Built-In Objects, Variables, and Methods. What the Node.js Runtime Provides | by Andreas 🎧 Kagoshima | Medium
2 weeks ago - In this article, we’ll explore the key global objects, variables, and methods in both JavaScript and Node.js, highlight how their design differs across environments, and explain how to build your own global objects.
Find elsewhere
🌐
Strapi
strapi.io › blog › global-variable-in-javascript
What Is a Global Variable in JavaScript?
November 25, 2025 - Learn how JavaScript global variables work across browsers and Node.js, how scope controls access, and modern patterns to prevent naming conflicts.
Top answer
1 of 7
242

You can use global like so:

global._ = require('underscore')
2 of 7
221

In Node.js, you can set global variables via the "global" or "GLOBAL" object:

GLOBAL._ = require('underscore'); // But you "shouldn't" do this! (see note below)

or more usefully...

GLOBAL.window = GLOBAL;  // Like in the browser

From the Node.js source, you can see that these are aliased to each other:

node-v0.6.6/src/node.js:
28:     global = this;
128:    global.GLOBAL = global;

In the code above, "this" is the global context. With the CommonJS module system (which Node.js uses), the "this" object inside of a module (i.e., "your code") is not the global context. For proof of this, see below where I spew the "this" object and then the giant "GLOBAL" object.

console.log("\nTHIS:");
console.log(this);
console.log("\nGLOBAL:");
console.log(global);

/* Outputs ...

THIS:
{}

GLOBAL:
{ ArrayBuffer: [Function: ArrayBuffer],
  Int8Array: { [Function] BYTES_PER_ELEMENT: 1 },
  Uint8Array: { [Function] BYTES_PER_ELEMENT: 1 },
  Int16Array: { [Function] BYTES_PER_ELEMENT: 2 },
  Uint16Array: { [Function] BYTES_PER_ELEMENT: 2 },
  Int32Array: { [Function] BYTES_PER_ELEMENT: 4 },
  Uint32Array: { [Function] BYTES_PER_ELEMENT: 4 },
  Float32Array: { [Function] BYTES_PER_ELEMENT: 4 },
  Float64Array: { [Function] BYTES_PER_ELEMENT: 8 },
  DataView: [Function: DataView],
  global: [Circular],
  process:
   { EventEmitter: [Function: EventEmitter],
     title: 'node',
     assert: [Function],
     version: 'v0.6.5',
     _tickCallback: [Function],
     moduleLoadList:
      [ 'Binding evals',
        'Binding natives',
        'NativeModule events',
        'NativeModule buffer',
        'Binding buffer',
        'NativeModule assert',
        'NativeModule util',
        'NativeModule path',
        'NativeModule module',
        'NativeModule fs',
        'Binding fs',
        'Binding constants',
        'NativeModule stream',
        'NativeModule console',
        'Binding tty_wrap',
        'NativeModule tty',
        'NativeModule net',
        'NativeModule timers',
        'Binding timer_wrap',
        'NativeModule _linklist' ],
     versions:
      { node: '0.6.5',
        v8: '3.6.6.11',
        ares: '1.7.5-DEV',
        uv: '0.6',
        openssl: '0.9.8n' },
     nextTick: [Function],
     stdout: [Getter],
     arch: 'x64',
     stderr: [Getter],
     platform: 'darwin',
     argv: [ 'node', '/workspace/zd/zgap/darwin-js/index.js' ],
     stdin: [Getter],
     env:
      { TERM_PROGRAM: 'iTerm.app',
        'COM_GOOGLE_CHROME_FRAMEWORK_SERVICE_PROCESS/USERS/DDOPSON/LIBRARY/APPLICATION_SUPPORT/GOOGLE/CHROME_SOCKET': '/tmp/launch-nNl1vo/ServiceProcessSocket',
        TERM: 'xterm',
        SHELL: '/bin/bash',
        TMPDIR: '/var/folders/2h/2hQmtmXlFT4yVGtr5DBpdl9LAiQ/-Tmp-/',
        Apple_PubSub_Socket_Render: '/tmp/launch-9Ga0PT/Render',
        USER: 'ddopson',
        COMMAND_MODE: 'unix2003',
        SSH_AUTH_SOCK: '/tmp/launch-sD905b/Listeners',
        __CF_USER_TEXT_ENCODING: '0x12D732E7:0:0',
        PATH: '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:~/bin:/usr/X11/bin',
        PWD: '/workspace/zd/zgap/darwin-js',
        LANG: 'en_US.UTF-8',
        ITERM_PROFILE: 'Default',
        SHLVL: '1',
        COLORFGBG: '7;0',
        HOME: '/Users/ddopson',
        ITERM_SESSION_ID: 'w0t0p0',
        LOGNAME: 'ddopson',
        DISPLAY: '/tmp/launch-l9RQXI/org.x:0',
        OLDPWD: '/workspace/zd/zgap/darwin-js/external',
        _: './index.js' },
     openStdin: [Function],
     exit: [Function],
     pid: 10321,
     features:
      { debug: false,
        uv: true,
        ipv6: true,
        tls_npn: false,
        tls_sni: true,
        tls: true },
     kill: [Function],
     execPath: '/usr/local/bin/node',
     addListener: [Function],
     _needTickCallback: [Function],
     on: [Function],
     removeListener: [Function],
     reallyExit: [Function],
     chdir: [Function],
     debug: [Function],
     error: [Function],
     cwd: [Function],
     watchFile: [Function],
     umask: [Function],
     getuid: [Function],
     unwatchFile: [Function],
     mixin: [Function],
     setuid: [Function],
     setgid: [Function],
     createChildProcess: [Function],
     getgid: [Function],
     inherits: [Function],
     _kill: [Function],
     _byteLength: [Function],
     mainModule:
      { id: '.',
        exports: {},
        parent: null,
        filename: '/workspace/zd/zgap/darwin-js/index.js',
        loaded: false,
        exited: false,
        children: [],
        paths: [Object] },
     _debugProcess: [Function],
     dlopen: [Function],
     uptime: [Function],
     memoryUsage: [Function],
     uvCounters: [Function],
     binding: [Function] },
  GLOBAL: [Circular],
  root: [Circular],
  Buffer:
   { [Function: Buffer]
     poolSize: 8192,
     isBuffer: [Function: isBuffer],
     byteLength: [Function],
     _charsWritten: 8 },
  setTimeout: [Function],
  setInterval: [Function],
  clearTimeout: [Function],
  clearInterval: [Function],
  console: [Getter],
  window: [Circular],
  navigator: {} }
*/

** Note: regarding setting "GLOBAL._", in general you should just do var _ = require('underscore');. Yes, you do that in every single file that uses Underscore.js, just like how in Java you do import com.foo.bar;. This makes it easier to figure out what your code is doing because the linkages between files are 'explicit'. It is mildly annoying, but a good thing. .... That's the preaching.

There is an exception to every rule. I have had precisely exactly one instance where I needed to set "GLOBAL._". I was creating a system for defining "configuration" files which were basically JSON, but were "written in JavaScript" to allow a bit more flexibility. Such configuration files had no 'require' statements, but I wanted them to have access to Underscore.js (the entire system was predicated on Underscore.js and Underscore.js templates), so before evaluating the "configuration", I would set "GLOBAL._". So yeah, for every rule, there's an exception somewhere. But you had better have a darn good reason and not just "I get tired of typing 'require', so I want to break with the convention".

🌐
Medium
habtesoft.medium.com › global-variables-in-javascript-understanding-and-best-practices-dbd7dd6f1067
Global Variables in JavaScript: Understanding and Best Practices | by habtesoft | Medium
November 13, 2024 - let globalVar = 'I am a global variable'; function showGlobal() { console.log(globalVar); // Accessible inside functions } showGlobal(); // Output: "I am a global variable" console.log(globalVar); // Output: "I am a global variable" In the example above, globalVar is declared in the global scope, meaning it can be accessed anywhere in the program.
🌐
KnowledgeHut
knowledgehut.com › home › blog › software development › global objects in node js: how they can make or break your code?
Don't Ship Code Without Knowing Global Objects in Node js!
July 7, 2025 - It’s best practice to store sensitive data in environment variables or protected modules. process.argv is an array that holds the command-line arguments passed to a Node.js process.
🌐
Quora
quora.com › In-which-circumstances-is-it-dangerous-to-use-a-global-variable-in-Node-js
In which circumstances is it dangerous to use a global variable in Node.js? - Quora
Answer (1 of 2): In Node.js modules there isn’t anything you can properly call a Global Variable — that is, which is visible across the entire application. The variables that look like global variables in a module are local to that module, and are shared among the functions of that module.
🌐
Speakingjs
speakingjs.com › es5 › ch16.html
Chapter 16. Variables: Scopes, Environments, and Closures
This is the scope you are in when entering a script (be it a <script> tag in a web page or be it a .js file). Inside the global scope, you can create a nested scope by defining a function. Inside such a function, you can again nest scopes. Each scope has access to its own variables and to the variables in the scopes that surround it.
🌐
Byby
byby.dev › js-global-variables
How to use global variables in JavaScript
// globals.js export const PI = 3.14; // export a global constant export let counter = 0; // export a global variable // module1.js import { PI, counter } from "./globals.js"; // import the global variables console.log(PI); // use the global constant // will log 3.14 counter++; // modify the global variable // module2.js import { counter } from "./globals.js"; // import the global variable console.log(counter); // use the global variable // will log 1 · Or using CommonJS, which was originally designed for server-side JavaScript environments, specifically in the context of the Node.js runtime.
🌐
Reddit
reddit.com › r/node › how to deal with global variables when modularizing a node.js app?
r/node on Reddit: How to deal with global variables when modularizing a node.js app?
May 7, 2016 -

Hey all,

I have been working on an api for the last 2 months and my main index.js page has reached 2000 lines of code. I now need to modularize my application into submodules.

My main problem is I don't know how I will implement global variables into a modularized structure. For objects and arrays, I can just pass them down to my function has an argument since they are passed by reference but for every other datatype, I can't pass them as a reference.

What is the most common way to deal with modularizing a node.js app which has global variables?

EDIT: Specifically, how would you deal with global variables in Koa.js?

Top answer
1 of 2
3
As much as possible, anything that a function changes should be returned from it rather than modified in place. The purer a function is, the easier it is to test, to reason about, and to compose. Your second best bet if that's impractical is to turn the globals into data attached to the "this" object that your functions are being called as methods on. This still improves your ability to reason about data because it is scoped to a set of functions rather than the whole program. I would caution you against having a giant "context" object that holds all of the mutable globals that you pass around to every function. This is the easiest thing to do when refactoring from a program with lots of globals, but it doesn't actually buy you much over the globals. You're still left with a lot of implicit state that you need to set up before calling each function.
2 of 2
2
Generally speaking you should try to avoid globals, preferring to expose state only to those parts of a program that need it. One step towards this is using modules. For a simple fix you can just move all your global state into its own module, and require it wherever you need it. The value exported by a module is shared between any other modules that export it, so it's possible to share state that way. For example: // index.js var global_a = 5; var global_b = 6; function uses_a() { return global_a * 2; } function uses_b() { return global_b * 2; } console.log('' + uses_a() + uses_b()); becomes: index.js var uses_a = require('./uses_a'); var uses_b = require('./uses_b'); console.log('' + uses_a() + uses_b()); state.js module.exports = { global_a: 5, global_b: 6 }; uses_a.js var state = require('./state'): module.exports = function uses_a() { return state.global_a * 2; } uses_b.js var state = require('./state'); module.exports = function uses_b() { return global_b * 2; } There is also a global object global that can be used to share state between modules. Its use is discouraged though, as it is shared between all modules (including those from your node_modules directory). // accessible anywhere: global.global_a = 5;
🌐
GeeksforGeeks
geeksforgeeks.org › node.js › node-js-global-objects
NodeJS Global Objects - GeeksforGeeks
January 17, 2026 - Node.js provides a global scope mechanism that allows certain variables and functions to be available across the entire application without explicit imports.
🌐
Quora
quora.com › Are-global-variables-in-JavaScript-harmful-in-any-way-when-running-Node-js
Are global variables in JavaScript harmful in any way when running Node.js? - Quora
Answer: All Node.js modules (or files) are wrapped by a function. So when you declare a variable inside a Node.js file, it is not really a global variable as the only way any other file can access it is if you export the variable and import it in another file. To make a global variable, you'd ha...
🌐
EDUCBA
educba.com › home › software development › software development tutorials › javascript technology tutorial › node.js global variable
Node.js Global Variable | How Global Variable Work in Node.js?
March 29, 2023 - So in node js, we have one object called global. So whatever function we are using in nodejs without creating them is coming from this global object. One thing to note here, if we are declaring any variable in nodejs, then it is not added to its global scope.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
Sling Academy
slingacademy.com › article › create-use-global-variables-nodejs
How to Create and Use Global Variables in Node.js - Sling Academy
By adhering to best practices such as using environment variables, managing state with modules, namespacing, and avoiding state in asynchronous operations, you can use globals effectively without compromising the maintainability and reliability of your application.
🌐
Node.js
nodejs.org › download › release › v12.13.0 › docs › api › globals.html
Global Objects | Node.js v12.13.0 Documentation
The top-level scope is not the global scope; var something inside a Node.js module will be local to that module. This variable may appear to be global but is not.