Skip to content
jshacks.dev
Patterns

The Registry Pattern in JavaScript Explained

A registry maps names to implementations so code can look them up at run time. Build one in JavaScript with validation, plugins and a safe way to test.

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

A registry is a central place where code registers things under a name, and other code looks them up by that name. It replaces long if and switch chains with a map, and lets new implementations join without editing the code that uses them. This post builds a registry on Node.js 24 for file format handlers, adds duplicate detection, lazy creation and namespacing, and explains the testing problem global registries cause and how to avoid it.

The problem: a switch that grows

A converter picks a handler from the file extension.

switch.mjsJavaScript
function convert(ext, text) {
  switch (ext) {
    case "json":
      return JSON.parse(text);
    case "csv":
      return text.split("\n").map((line) => line.split(","));
    default:
      throw new Error(`no handler for ${ext}`);
  }
}

console.log(convert("csv", "a,b\n1,2"));
Text
[ [ 'a', 'b' ], [ '1', '2' ] ]

Each new format means editing convert. A plugin that adds YAML support has no way to do it without changing this function.

A minimal registry

A registry is a Map with a small API around it.

registry.mjsJavaScript
function createRegistry() {
  const entries = new Map();
  return {
    register(name, value) {
      entries.set(name, value);
    },
    get(name) {
      if (!entries.has(name)) throw new Error(`nothing registered as "${name}"`);
      return entries.get(name);
    },
    has: (name) => entries.has(name),
    names: () => [...entries.keys()],
  };
}

const parsers = createRegistry();
parsers.register("json", (text) => JSON.parse(text));
parsers.register("csv", (text) => text.split("\n").map((l) => l.split(",")));

function convert(ext, text) {
  return parsers.get(ext)(text);
}

console.log(convert("json", '{"a":1}'));
console.log(parsers.names());
try {
  convert("yaml", "a: 1");
} catch (err) {
  console.log(err.message);
}
Text
{ a: 1 }
[ 'json', 'csv' ]
nothing registered as "yaml"

convert no longer changes when a format is added. A plugin calls parsers.register("yaml", ...) from its own module, and convert finds it. The error message names the missing key, which is far more useful than undefined is not a function.

Refusing duplicate names

A Map silently overwrites on set. In a registry fed by several plugins, two plugins claiming json is a conflict that should be loud.

duplicates.mjsJavaScript
function createStrictRegistry() {
  const entries = new Map();
  return {
    register(name, value) {
      if (entries.has(name)) {
        throw new Error(`"${name}" is already registered`);
      }
      entries.set(name, value);
    },
    replace(name, value) {
      if (!entries.has(name)) throw new Error(`"${name}" is not registered`);
      entries.set(name, value);
    },
    get(name) {
      if (!entries.has(name)) throw new Error(`nothing registered as "${name}"`);
      return entries.get(name);
    },
  };
}

const r = createStrictRegistry();
r.register("json", () => "first");
try {
  r.register("json", () => "second");
} catch (err) {
  console.log(err.message);
}
r.replace("json", () => "replaced");
console.log(r.get("json")());
Text
"json" is already registered
replaced

Splitting register from replace makes overriding an explicit act. A test that wants to swap an implementation calls replace, and an accidental clash between plugins still throws.

Lazy creation

Registering a handler does not have to create it. Registering a factory defers the cost until the first lookup, which keeps startup cheap when most entries are never used.

lazy.mjsJavaScript
function createLazyRegistry() {
  const factories = new Map();
  const instances = new Map();
  return {
    register(name, factory) {
      factories.set(name, factory);
    },
    get(name) {
      if (!instances.has(name)) {
        const factory = factories.get(name);
        if (!factory) throw new Error(`nothing registered as "${name}"`);
        instances.set(name, factory());
      }
      return instances.get(name);
    },
  };
}

const services = createLazyRegistry();
services.register("db", () => {
  console.log("connecting...");
  return { query: () => "rows" };
});

console.log("registered");
console.log(services.get("db").query());
console.log(services.get("db").query());
Text
registered
connecting...
rows
rows

The factory ran once, on first use. A registry that holds factories and caches their results is a small service locator, which leads to the next section.

Registry or service locator or injection

A registry that hands out services to any code that asks is a service locator. It is convenient and has a cost: dependencies are no longer visible in a function's parameters, because the function reaches into the registry from the inside.

hidden-dependency.mjsJavaScript
function sendWelcome(userId) {
  const mailer = services.get("mailer");
  return mailer.send(userId, "welcome");
}

function sendWelcomeInjected(userId, mailer) {
  return mailer.send(userId, "welcome");
}

The first function depends on mailer but its signature says nothing about it, so a reader must read the body, and a test must register a fake mailer in a shared registry. The second states its dependency and can be tested by passing a fake. A good split: use a registry at the edges, to find the handler for a name that arrives as data, and inject dependencies inside the code.

Namespacing

When many plugins register, names collide. A prefix keeps them apart.

namespace.mjsJavaScript
function namespaced(registry, prefix) {
  return {
    register: (name, value) => registry.register(`${prefix}:${name}`, value),
    get: (name) => registry.get(`${prefix}:${name}`),
  };
}

const registry = createStrictRegistry();
const markdownPlugin = namespaced(registry, "markdown");
const htmlPlugin = namespaced(registry, "html");

markdownPlugin.register("render", () => "md");
htmlPlugin.register("render", () => "html");

console.log(markdownPlugin.get("render")(), htmlPlugin.get("render")());
Text
md html

Each plugin sees a registry that looks private to it, while the underlying map holds markdown:render and html:render.

The testing problem with global registries

A module-level registry is shared state. A test that registers a fake leaks it into every later test in the same process.

leak.mjsJavaScript
// registry-instance.mjs
export const handlers = createStrictRegistry();

// test one registers a fake
handlers.register("pdf", () => "fake");

// test two, later in the same process, registers its own
try {
  handlers.register("pdf", () => "other fake");
} catch (err) {
  console.log(err.message);
}
Text
"pdf" is already registered

There are two clean fixes. Create a fresh registry per test through a factory, as createRegistry allows, and pass it to the code under test. Or provide a clear() that tests call in teardown. The first is better, because it also removes the hidden dependency on a global.

fresh.test.mjsJavaScript
import assert from "node:assert/strict";
import { test } from "node:test";

test("convert uses the registry it is given", () => {
  const local = createRegistry();
  local.register("txt", (t) => t.toUpperCase());
  const run = (ext, text) => local.get(ext)(text);
  assert.equal(run("txt", "hi"), "HI");
});
Text
✔ convert uses the registry it is given (0.7ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0

Validating what gets registered

A registry that accepts anything defers errors to the moment of use, far from the cause. Check the value when it is registered.

validated.mjsJavaScript
function createHandlerRegistry() {
  const entries = new Map();
  return {
    register(name, handler) {
      if (typeof name !== "string" || name === "") {
        throw new TypeError("name must be a non-empty string");
      }
      if (typeof handler !== "function") {
        throw new TypeError(`handler for "${name}" must be a function`);
      }
      entries.set(name, handler);
    },
    get: (name) => entries.get(name),
  };
}

const handlers = createHandlerRegistry();
try {
  handlers.register("json", "not a function");
} catch (err) {
  console.log(err.message);
}
Text
handler for "json" must be a function

Failing at registration puts the stack trace in the plugin that made the mistake.

When not to use it

If a function has two fixed branches, a conditional is clearer than a registry. A registry is for open sets of things that third parties or later code may add to. And it should not become a place to stash everything the application needs, which turns it into a global with a friendlier name.

Registries in tools you already use

Registries are everywhere once you look for them. A web framework's router is a registry of path patterns to handlers. A bundler's loader list maps file extensions to loaders. Node's own module cache, require.cache, is a registry of loaded modules by path. A logger library often keeps a registry of named loggers, so asking for "db" twice returns the same instance. Seeing the shape makes unfamiliar systems easier to read: ask what the key is, what the value is, who may add entries and when lookups happen.

Deciding on keys

A string name is the simplest key and works for plugin systems, because a configuration file can mention it. The risk is typos, which fail at run time. Constants exported from one module remove most of that. Symbols avoid collisions entirely, since two symbols are never equal, but they cannot appear in a text configuration. Class constructors are a useful key when you want "the handler for this type", because the key is the type itself, and a Map accepts any value as a key.

by-class.mjsJavaScript
class Circle {}
class Square {}

const renderers = new Map([
  [Circle, () => "draw circle"],
  [Square, () => "draw square"],
]);

function render(shape) {
  const renderer = renderers.get(shape.constructor);
  if (!renderer) throw new Error(`no renderer for ${shape.constructor.name}`);
  return renderer(shape);
}

console.log(render(new Square()));
Text
draw square

This lookup does not follow inheritance: a subclass of Square would find no entry. If you need that, walk the prototype chain with Object.getPrototypeOf until a registered ancestor is found.

Freezing the registry after startup

Many applications register everything during startup and never again. Making that explicit prevents late registrations from changing behavior mid-flight, which is the cause of some of the hardest bugs to reproduce. Add a freeze() method that sets a flag, and have register throw once it is set. Call it after plugin loading finishes. A frozen registry is also safe to read from many places without worrying that a lookup result will change between two calls, and it makes the order of module loading less important to the program's behavior.

Handling missing entries gracefully

Throwing on a missing name is the right default, but some uses want a fallback. A file converter might fall back to treating unknown extensions as plain text. Make the fallback explicit with a get(name, fallback) signature or a separate getOrDefault, and not by returning undefined and letting callers cope. Returning undefined pushes the null check onto every caller, and one missing check becomes a crash far away from the lookup. When the fallback is a sensible default behavior, register it under a well-known name such as "default" and look it up when the specific name is absent, so the fallback is visible in the same list as every other handler.

Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

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

Unsubscribe in one click. No spam, ever.