Skip to content
jshacks.dev
Patterns

How to Use Awilix for Dependency Injection in Node.js

Learn Awilix dependency injection in Node.js: the container, PROXY and CLASSIC modes, lifetimes, request scopes, disposal and tests with plain objects.

8 min read
Summarize in AI
Flat illustration of a service container binding interfaces to classes, with the Node.js, JavaScript, Vite and TypeScript logos.

Awilix is a dependency injection container for Node.js that does not need decorators, type metadata or compiler settings. You register things by name in a container, and the container passes each one the other registrations it asks for, either as properties of one object or, in classic mode, by matching parameter names. This guide covers Awilix with Node.js 24 and works in plain JavaScript and in TypeScript: the container and its injection modes, registering classes, functions and values, lifetimes, request scopes with createScope, disposal and tests. The examples use JavaScript so they run directly with Node.js.

Why Awilix suits Node.js

Container libraries that rely on decorators ask you to configure the compiler and import a metadata polyfill, and they do not work with plain JavaScript. Awilix instead asks each class or function to receive its dependencies in a predictable way, so it works anywhere. Because the dependencies are named, a service says what it needs by writing those names in its constructor, and there are no tokens to define or symbols to import. The price is that wiring is by string name, which you must keep consistent, and that mistakes appear when resolving and not at compile time.

Install

installShell
npm install awilix

The package ships its own type definitions, so TypeScript users need nothing extra.

Step 1: register and resolve

Create a container, register things by name and resolve one.

basic.mjsJavaScript
import { asClass, asValue, createContainer, InjectionMode } from "awilix";

class UserRepository {
  #users = new Map([[1, "Ada"], [2, "Lin"]]);

  findName(id) {
    return this.#users.get(id);
  }
}

class UserService {
  constructor({ logger, userRepository }) {
    this.logger = logger;
    this.userRepository = userRepository;
  }

  greet(id) {
    const name = this.userRepository.findName(id) ?? "stranger";
    this.logger.info(`greeting ${name}`);
    return `Hello, ${name}`;
  }
}

const container = createContainer({ injectionMode: InjectionMode.PROXY });

container.register({
  logger: asValue({ info: (message) => console.log(`[log] ${message}`) }),
  userRepository: asClass(UserRepository),
  userService: asClass(UserService),
});

const service = container.resolve("userService");
console.log(service.greet(1));
console.log(service.greet(9));
Text
[log] greeting Ada
Hello, Ada
[log] greeting stranger
Hello, stranger

container.resolve("userService") constructed UserService, handing it one argument: an object whose properties are the container's registrations, looked up by name when the constructor reads them. The constructor destructures logger and userRepository, which triggers the resolution of those two. asValue registers an existing object, and asClass registers a class for the container to instantiate.

Injection modes

Awilix offers two ways to hand dependencies over.

PROXY mode, the default, passes a single object called the cradle. It is a proxy: reading a property resolves that registration at that moment. Constructors and factory functions take one parameter and destructure it, as above. Names are explicit in the code, they survive minification, and a service only resolves what it actually reads.

CLASSIC mode reads the parameter names of the constructor or function and resolves matching registrations, passing them as ordinary positional arguments.

classic.mjsJavaScript
import { asClass, asValue, createContainer, InjectionMode } from "awilix";

class Mailer {
  constructor(smtpHost, logger) {
    this.smtpHost = smtpHost;
    this.logger = logger;
  }
  send(to) {
    this.logger.info(`mail to ${to} via ${this.smtpHost}`);
  }
}

const container = createContainer({ injectionMode: InjectionMode.CLASSIC });
container.register({
  smtpHost: asValue("smtp.example.com"),
  logger: asValue({ info: (message) => console.log(message) }),
  mailer: asClass(Mailer),
});

container.resolve("mailer").send("[email protected]");
Text
mail to [email protected] via smtp.example.com

The container parsed the constructor's source text to find the parameter names smtpHost and logger, and matched them to registrations. That reading is fragile. A minifier renames parameters, and then nothing matches. Classic mode is fine for Node.js services that are not minified, and PROXY mode is the safer default. You can set the mode per container, or per registration with .inject() for explicit lists.

Registration helpers

HelperRegisters
asValue(x)An existing value, such as configuration or a constant
asClass(C)A class, constructed by the container with new
asFunction(fn)A factory function, called with the dependencies, whose return value is the registration

Factory functions are a good fit when you prefer functions to classes.

factory.mjsJavaScript
import { asFunction, asValue, createContainer } from "awilix";

function makeGreeter({ greeting, logger }) {
  return {
    greet(name) {
      logger.info(`greeting ${name}`);
      return `${greeting}, ${name}`;
    },
  };
}

const container = createContainer();
container.register({
  greeting: asValue("Hi"),
  logger: asValue({ info: (message) => console.log(message) }),
  greeter: asFunction(makeGreeter),
});

console.log(container.resolve("greeter").greet("Ada"));
Text
greeting Ada
Hi, Ada

Registering by name means any registration can be overridden by registering something else under the same name, which is how tests substitute fakes.

Lifetimes

A registration's lifetime decides how often the container builds it. The default is transient: a new instance on every resolve. Singletons live for the container's life, and scoped registrations live for one scope, covered next.

lifetimes.mjsJavaScript
import { asClass, createContainer } from "awilix";

class Counter {
  static created = 0;
  id = ++Counter.created;
}

const container = createContainer();
container.register({
  transient: asClass(Counter),
  shared: asClass(Counter).singleton(),
});

const a = container.resolve("transient");
const b = container.resolve("transient");
const c = container.resolve("shared");
const d = container.resolve("shared");

console.log(a.id, b.id, c.id, d.id);
console.log(a === b, c === d);
Text
1 2 3 3
false true

.singleton() on a registration is shorthand for the singleton lifetime, and .transient() and .scoped() set the other two. The two transient resolutions created ids 1 and 2, and the singleton was created once, at the third construction. Pick singletons for services that hold no per-request state, such as database clients and loggers, and keep per-request data in scoped registrations.

A well-known trap is the captive dependency: a singleton that depends on a scoped or transient registration captures one instance at creation and keeps it forever, so it sees the first request's data in all later requests. Awilix can detect this: setting strict: true in the container options makes it throw when a longer-lived registration depends on a shorter-lived one.

Request scopes

A web application creates one scope per request. A scope is a child container: it can resolve everything the parent has, and its scoped registrations are instantiated once per scope.

scope.mjsJavaScript
import { asClass, asValue, createContainer } from "awilix";

class RequestLogger {
  constructor({ requestId, logger }) {
    this.requestId = requestId;
    this.logger = logger;
  }
  info(message) {
    this.logger.info(`[${this.requestId}] ${message}`);
  }
}

const container = createContainer();
container.register({
  logger: asValue({ info: (message) => console.log(message) }),
  requestLogger: asClass(RequestLogger).scoped(),
});

function handleRequest(requestId) {
  const scope = container.createScope();
  scope.register({ requestId: asValue(requestId) });
  const log = scope.resolve("requestLogger");
  log.info("handling");
  return scope.resolve("requestLogger") === log;
}

console.log(handleRequest("req-1"));
console.log(handleRequest("req-2"));
Text
[req-1] handling
true
[req-2] handling
true

Each request made a scope, registered its own requestId and resolved the logger there. Within one scope, the logger is created once, so the second resolve returned the same object, which is the true line. Across scopes the instances differ, and each carries its own id. With Express or Fastify, create the scope in a middleware or hook, attach it to the request, and resolve handlers' dependencies from it. The awilix-express and @fastify/awilix packages provide that glue.

Cleaning up with disposers

Resources such as database pools must be closed. A registration can declare a disposer, and dispose() on a container or a scope calls them.

dispose.mjsJavaScript
import { asFunction, createContainer } from "awilix";

const container = createContainer();
container.register({
  pool: asFunction(() => ({ closed: false, close() { this.closed = true; } }))
    .singleton()
    .disposer((pool) => pool.close()),
});

const pool = container.resolve("pool");
console.log(pool.closed);
await container.dispose();
console.log(pool.closed);
Text
false
true

Calling dispose at shutdown, or at the end of a scope, runs each disposer for the instances that were created, and it is async, so await it. A scope's dispose only handles the registrations scoped to it.

Tests

Because registrations are named, a test builds a container from the same registration code and overrides what it needs.

service.test.mjsJavaScript
import assert from "node:assert/strict";
import { test } from "node:test";
import { asClass, asValue, createContainer } from "awilix";

test("greet logs what it greets", () => {
  const lines = [];
  const container = createContainer();
  container.register({
    logger: asValue({ info: (message) => lines.push(message) }),
    userRepository: asValue({ findName: () => "Ada" }),
    userService: asClass(UserService),
  });

  assert.equal(container.resolve("userService").greet(1), "Hello, Ada");
  assert.deepEqual(lines, ["greeting Ada"]);
});
Text
✔ greet logs what it greets (1.1ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0

The test registers plain objects for the collaborators, with no mocking library and no decorators. For a larger test setup, export a registerServices(container) function and call it in both the application and the test, then override individual registrations afterward.

Pitfalls

Name mismatches. userRepository and userRepo are different registrations. A misspelled dependency is reported when resolved, with a message naming the missing registration and the resolution path, which is usually enough to find it. Keep names consistent, and use TypeScript's cradle interface to check them.

Circular dependencies. Awilix detects a cycle and throws an error listing the path. Break it by extracting shared logic.

Destructuring in the wrong place. In PROXY mode, destructuring the cradle in a constructor resolves everything at construction. Reading a dependency lazily, inside a method, delays its creation, which can help break a cycle or defer expensive setup, but it hides what the class needs.

Container leaking into services. Avoid registering the container itself and injecting it, because that hides dependencies. Services should list the specific things they need.

**Using loadModules blindly.** Awilix can scan files by glob and register them under names derived from file names. It is convenient for large applications and makes registrations implicit, so be sure the naming convention is documented.

TypeScript

Awilix's types let you declare the cradle's shape so that destructuring is checked.

cradle.tsTypeScript
import { asClass, asValue, createContainer } from "awilix";

interface Cradle {
  greeting: string;
  greeter: Greeter;
}

class Greeter {
  constructor(private readonly deps: Pick<Cradle, "greeting">) {}
  greet(name: string): string {
    return `${this.deps.greeting}, ${name}`;
  }
}

const container = createContainer<Cradle>();
container.register({
  greeting: asValue("Hello"),
  greeter: asClass(Greeter),
});

console.log(container.resolve("greeter").greet("Ada"));
Text
Hello, Ada

createContainer<Cradle>() makes resolve("greeter") return a Greeter, and a misspelled name a compile error. A constructor can take Pick<Cradle, ...> to state exactly which dependencies it uses.

Also inNode.js
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.