Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 133 ยท Modules and Packages

Module Design Patterns

Design Node.js modules well - singleton modules, factory functions, dependency injection by parameter, barrel file costs, circular dependency traps and project layout.

You already know how to import and export. The harder question is what to put in a module and how modules should depend on each other. Two programs can use exactly the same syntax and still differ wildly: one is easy to test and change, the other is a tangle where touching one file breaks five others.

This lesson collects the patterns that experienced Node.js developers reach for again and again: modules as singletons, factory functions, passing dependencies in as parameters, the real cost of "barrel" files, how circular imports go wrong, and how to lay out a project. Because our editor runs a single file, the examples write small module files to a temporary folder and import them, so you can see a multi-file layout working. Read ES Modules and CommonJS Modules first if import is still new to you.

A module is evaluated once

The most important fact about modules is easy to miss: the first time a file is imported, Node runs its top-level code and caches the result. Every later import of the same file gets the same module instance, without running the code again. The cache is keyed by the file's resolved URL.

Node.js Modules run once and are shared

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The message from the top level appears exactly once, even though we imported twice. Both variables point at the same namespace object, so an increment through one is visible through the other. CommonJS behaves the same way with require, using require.cache.

The singleton module

Because of that caching, a module is the simplest singleton in JavaScript. You do not need a getInstance() method or a class with a private constructor: you export the thing you want to share, and everyone who imports it gets the same one.

JavaScript
// config.js - evaluated once, shared by every importer
export const config = Object.freeze({
  port: Number(process.env.PORT ?? 3000),
  logLevel: process.env.LOG_LEVEL ?? 'info',
});

Good uses: configuration, a logger, a connection pool, a cache. They are things you genuinely want exactly one of.

Singleton modules are hidden global state. Any file can import and mutate them, and tests that run in the same process leak state into each other. A "database" singleton that connects when the file loads also makes every importer pay for (and fail on) that connection, even a test that never touches the database. Use singletons for stable, read-mostly things, and prefer the factory pattern below for anything with behaviour you will want to replace.

Another subtle point: the "once" guarantee is per module instance. If the same package ends up installed twice in node_modules at different versions, or the same file is reached through two different URLs (for example ./a.mjs and ./a.mjs?x=1), you get two instances and two "singletons".

Factory functions

A factory is a function that builds and returns an object. Compared with a module-level singleton, a factory gives each caller its own state, makes configuration explicit, and lets you create a fresh instance per test.

Node.js A counter factory with private state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Closures give genuine privacy without #private fields, and there is no this to lose when a method is passed around as a callback. Classes are equally valid; choose a factory when you want simple objects with a few methods and no inheritance, and a class when you want many instances to share methods, instanceof checks, or private fields via #.

Dependency injection by parameter

Dependency injection sounds like a framework concept, but in JavaScript it is just this: instead of a module reaching out and importing the things it needs, you pass them in. A function that needs a clock, a logger or a database receives them as arguments.

Compare two versions of a function that creates a greeting log line with a timestamp.

Node.js Hard-wired versus injected dependencies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first line of output differs every time you run the program, which is exactly the problem: tests cannot assert on it. The injected version has no hidden dependencies, so the test supplies a frozen clock and captures output in an array. You will use this idea heavily in Mocks, Spies and Fake Timers.

A neat convention is a single composition root: one place, usually the program's entry file, where you create every real dependency and wire them together. Everything else receives what it needs and never imports a concrete database or logger itself.

JavaScript
// main.js - the composition root
import { createLogger } from './logger.js';
import { createDb } from './db.js';
import { createUserService } from './user-service.js';

const logger = createLogger({ level: 'info' });
const db = createDb({ file: 'app.db' });
const users = createUserService({ db, logger });

Putting the patterns together

Here is a small three-file layout written to disk and loaded for real: a pure math module, a store factory that takes a clock, and an app entry that composes them.

Node.js A small multi-file layout, composed in one place

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

money.mjs knows nothing about anyone else, so it is trivially testable. ledger.mjs imports money.mjs (a plain pure dependency) but receives the clock from outside. main.mjs decides which clock to use. Dependencies point one way, from entry file towards leaves, which is the single most useful rule of thumb for keeping a codebase healthy.

Barrel files and what they cost

A barrel file is an index.js that re-exports everything from a folder so callers can write one import line:

JavaScript
// utils/index.js - a barrel
export * from './strings.js';
export * from './dates.js';
export * from './numbers.js';
JavaScript
// caller
import { slugify } from './utils/index.js';

It looks tidy, but it has real costs in Node:

  • Startup time. Importing slugify from the barrel loads every file the barrel re-exports, and everything those files import. In a big app that can mean hundreds of unneeded files parsed at startup, which hurts CLIs and serverless functions most.
  • Circular imports. Barrels make it easy for utils/dates.js to import something through utils/index.js, which re-exports dates.js itself. You will meet the consequences in the next section.
  • Tree shaking. Bundlers can often remove unused exports, but plain Node does not; it evaluates every module.
  • Name clashes. export * from two modules that export the same name silently makes that name ambiguous.

Barrels earn their place at a package boundary, as the public entry point of a library, where you want a small, stable surface. Inside an application, import from the specific file. If a folder is large and you still want a front door, the exports field in package.json can expose a few deliberate entry points.

Circular dependencies

A circular dependency exists when module A imports B and B imports A, directly or through a longer chain. Node does not forbid it, but the outcome depends on the order of evaluation, and the bugs it causes look bizarre.

With ES modules, imports are live bindings that exist before the module has run. If A starts first and imports B, B runs before A finishes. If B touches an export of A at its top level, that binding is still in its "temporal dead zone".

Node.js A circular import that fails at load time (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The real message is ReferenceError: Cannot access 'nameOfA' before initialization. The cycle itself is fine; the top-level use of a value from the cycle is the bug. If b.mjs only used nameOfA inside a function that is called later, after everything has loaded, nothing would break.

CommonJS is different and, in a way, sneakier. require returns whatever module.exports holds at that moment, so in a cycle the second module gets a half-filled (often empty) object, with no error at all, just undefined where you expected a function.

Node.js The CommonJS cycle that silently gives you an empty object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

B observed a.loaded as false because A had only run its first line. No error, only a half-initialised view, which is why cycles in CommonJS are so hard to debug.

How to fix a cycle, in order of preference:

  1. Move the shared piece out. If A and B both need formatCents, put it in a third module C that imports neither. Most cycles disappear this way.
  2. Pass it in. Let one side receive the other as a parameter (dependency injection again).
  3. Delay the access. Use the imported value only inside functions, not at the top level.
  4. Merge the two modules if they are really one thing.

Tools such as madge or ESLint's import/no-cycle rule can find cycles automatically in a real project.

Organising a project

There is no single correct layout, but a few habits keep projects readable:

  • Keep a thin entry file. main.js (or server.js) builds the dependencies and starts things. Business logic lives elsewhere.
  • Group by feature, not by type, once the app grows: users/, orders/ and billing/, each with its own routes, logic and tests, rather than one giant controllers/ and one giant models/.
  • Separate pure logic from I/O. Functions that take data and return data (parsers, formatters, calculations) go in modules with no side effects; the thin layer that touches files, databases and the network sits on the edge.
  • One responsibility per module, named after what it does. If a file is called helpers.js or utils.js and keeps growing, it is hiding several modules.
  • Prefer named exports. They make renaming safe, give editors good autocomplete, and make accidental default-versus-named mistakes impossible. Keep export default for cases where a file really has one main thing, or where a framework expects it.
  • Avoid side effects at import time beyond cheap definitions. A module that starts a server or opens a connection the moment it is imported is hard to test and impossible to import safely from another tool.

A typical small service might look like this:

TEXT
my-service/
  package.json
  src/
    main.js            composition root: wires and starts
    config.js          reads and validates environment
    users/
      user-service.js  business logic (factory, takes db + logger)
      user-routes.js   HTTP layer
      user-service.test.js
    shared/
      errors.js
      money.js         pure helpers

When in doubt, make the dependency arrows point in one direction only: entry file to features to shared helpers. If you ever need an arrow the other way, that is the signal to extract a new module or inject the dependency.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A module is imported from three different files. How many times does its top-level code run?

    Node evaluates a module on first import and caches it by resolved URL, so every importer shares the same instance.
  2. 2. What is the main benefit of passing a clock or logger into a function as a parameter?

    Dependency injection removes hidden dependencies, so a test can supply a fixed clock or capture output instead of using the real ones.
  3. 3. Why can a barrel file (index.js re-exporting a whole folder) hurt a Node.js program?

    Node evaluates all re-exported files, whether or not you use them. Barrels also make circular imports easier to create.
  4. 4. In an ES module cycle, what error appears if a module uses an export of its partner at the top level before that partner has run?

    ES module imports are live bindings that start uninitialised, so reading one too early throws a ReferenceError.
  5. 5. Which is usually the best first fix for a circular dependency?

    Extracting the shared piece breaks the cycle at its root. Injection, lazy access or merging are fallbacks.

Summary

  • A module runs once and is cached, so an exported object is shared by every importer; this makes modules natural singletons, but hidden global state.
  • Factory functions create independent instances with private state through closures; classes are the alternative when you want shared methods or instanceof.
  • Dependency injection means passing collaborators in as parameters; wire real ones in a single composition root.
  • Barrel files are good as a package's public front door and costly inside an app (startup time, cycles, ambiguous names).
  • Circular imports fail loudly in ES modules (ReferenceError on early use) and silently in CommonJS (half-filled exports); fix them by extracting shared code, injecting, or delaying access.
  • Keep entry files thin, group by feature, separate pure logic from I/O, prefer named exports, and avoid import-time side effects.

Next: The Event Loop