Explain Codes LogoExplain Codes Logo

Node.js global variables

javascript
global-variables
node-js
dependency-injection
Nikita BarsukovbyNikita Barsukov·Jan 25, 2025
TLDR

To define a global variable in Node.js, use the global object:

global.sharedVar = 'Shared Value'; // Setting a global variable

Access this value in any other module in your application:

console.log(global.sharedVar); // Prints 'Shared Value' to the console

Warning: Be careful, overusing global variables can lead to numerous conflicts and potential maintenance nightmares down the road.

Making use of global variables

Despite the cautionary note, there are situations where globals come in handy. For example, if you've got a library like underscore.js and you want it accessible across your app:

global._ = require('underscore'); // POOF! Underscore.js is now accessible globally!

Just remember to always namespace your global variables, preventing possible clashes:

global.MYAPI = {}; // MYAPI is your new playground. Don't worry - it's global!

Controlled usage of global variables

Always remember, global variables are like a toilet in an open office, very convenient but can cause trouble if not handled properly. Use them judiciously:

// globals.js module.exports = { sharedConfig: 'Config Value', // Functioning like the office jukebox playing your favorite song }; // In another module const globals = require('./globals.js'); console.log(globals.sharedConfig); // Prints 'Config Value' to the console

Beyond Global Variables

If you constantly find yourself reaching for globals, it may be a sign that your code needs refactoring or better organization. A possible solution to keep your code manageable and sane is dependency injection:

// Make sure to keep your friends(close modules) closer const db = require('./db'); function serviceA(dbInstance) { // Operate using dbInstance // "Hello, dependency injection here for you!" } serviceA(db);

Use with caution: this in node.js

In Node.js, this can be a tricky proposition - don't assume it's the global object:

console.log(this === global); // This will log: false. Plot twist, isn't it!

The config.js way

If you’re dealing with configurations or settings, a neat way of dealing with this is to create a single config.js (or similarly named) file that exports an object with all your configurations:

// config.js module.exports = { appName: 'SharedApp', version: '1.0.0', }; // In any other module const config = require('./config'); console.log(config.appName); // SharedApp - Isn't JS lovely?