Skip to content
jshacks.dev
Patterns

The Decorator Pattern in JavaScript, With Real Examples

The decorator pattern adds behavior to an object by wrapping it, without changing its class. See function, object and TypeScript decorators with output.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Node.js, Vite and npm logos.

The decorator pattern adds behavior to an object by wrapping it in another object with the same interface. Callers keep using the same methods, and the wrapper does something extra before or after delegating: log the call, cache the result, retry on failure, check permissions. The point is that you can stack these additions in any combination without a subclass for each. In JavaScript the idea shows up in three forms that deserve separate treatment: wrapping a function, wrapping an object, and the @decorator syntax of TypeScript and the TC39 decorators proposal, which is related but not identical. This post covers all three on Node.js 24 and TypeScript 5.9, with logging, caching and retry examples, and the ordering, this and typing pitfalls. Every sample prints its output.

The problem: behavior explosion

Suppose a data fetcher needs optional logging, caching and retries. With inheritance you get LoggingFetcher, CachingFetcher, LoggingCachingFetcher, RetryingCachingFetcher and so on, one class per combination. Decorators let each concern live once and combine freely.

Decorating a function

The simplest decorator is a higher-order function: it takes a function and returns a function with the same signature.

function-decorators.mjsJavaScript
export const withLogging = (fn, name = fn.name) => async (...args) => {
  console.log(`-> ${name}(${args.map((a) => JSON.stringify(a)).join(", ")})`);
  const result = await fn(...args);
  console.log(`<- ${name} returned ${JSON.stringify(result)}`);
  return result;
};

export const withCache = (fn) => {
  const cache = new Map();
  return async (...args) => {
    const key = JSON.stringify(args);
    if (cache.has(key)) return cache.get(key);
    const value = await fn(...args);
    cache.set(key, value);
    return value;
  };
};

let calls = 0;
async function getUser(id) {
  calls += 1;
  return { id, name: "Ada" };
}

const cached = withLogging(withCache(getUser), "getUser");
await cached(1);
await cached(1);
console.log(`real calls: ${calls}`);
Text
-> getUser(1)
<- getUser returned {"id":1,"name":"Ada"}
-> getUser(1)
<- getUser returned {"id":1,"name":"Ada"}
real calls: 1

Both calls were logged because logging is the outer wrapper, and only one reached getUser because the cache is inside. cached has the same shape as getUser, so anything that accepted one accepts the other. The wrappers know nothing about users.

Order matters

Stacking is a composition, and the order changes behavior. Swap the layers and see.

order.mjsJavaScript
import { withLogging, withCache } from "./function-decorators.mjs";

async function getUser(id) {
  return { id, name: "Ada" };
}

const loggingOutside = withLogging(withCache(getUser), "outer-log");
const loggingInside = withCache(withLogging(getUser, "inner-log"));

console.log("logging outside the cache");
await loggingOutside(1);
await loggingOutside(1);
console.log("logging inside the cache");
await loggingInside(1);
await loggingInside(1);
Text
logging outside the cache
-> outer-log(1)
<- outer-log returned {"id":1,"name":"Ada"}
-> outer-log(1)
<- outer-log returned {"id":1,"name":"Ada"}
logging inside the cache
-> inner-log(1)
<- inner-log returned {"id":1,"name":"Ada"}

With logging outside, you see every call, including cache hits. With logging inside, you see only the calls that actually reached the function. Neither is wrong, but you should choose it on purpose. The same applies to retry and timeout: a timeout inside a retry limits each attempt, and a timeout outside limits the whole operation.

A retry decorator

A more practical wrapper that you can reuse across the codebase.

retry.mjsJavaScript
export const withRetry = (fn, { attempts = 3, delayMs = 1 } = {}) => async (...args) => {
  let lastError;
  for (let attempt = 1; attempt <= attempts; attempt++) {
    try {
      return await fn(...args);
    } catch (err) {
      lastError = err;
      console.log(`attempt ${attempt} failed: ${err.message}`);
      if (attempt < attempts) await new Promise((resolve) => setTimeout(resolve, delayMs));
    }
  }
  throw lastError;
};

let n = 0;
const flaky = async () => {
  n += 1;
  if (n < 3) throw new Error("timeout");
  return "ok";
};

console.log(await withRetry(flaky)());

const alwaysFails = withRetry(async () => {
  throw new Error("down");
}, { attempts: 2 });
try {
  await alwaysFails();
} catch (err) {
  console.log(`gave up: ${err.message}`);
}
Text
attempt 1 failed: timeout
attempt 2 failed: timeout
ok
attempt 1 failed: down
attempt 2 failed: down
gave up: down

Retrying everything blindly is dangerous. Retry only idempotent operations and only on transient errors, since repeating a payment charge could charge twice. Decorators make the policy visible at the call site, so a reviewer sees what is wrapped.

Decorating an object

For objects with several methods, wrap the object and forward every method. A Proxy does it generically.

object-decorator.mjsJavaScript
function logged(target, name) {
  return new Proxy(target, {
    get(obj, prop, receiver) {
      const value = Reflect.get(obj, prop, receiver);
      if (typeof value !== "function") return value;
      return (...args) => {
        console.log(`${name}.${String(prop)}(${args.join(", ")})`);
        return value.apply(obj, args);
      };
    },
  });
}

class Mailer {
  send(to, subject) {
    return `sent "${subject}" to ${to}`;
  }
}

const mailer = logged(new Mailer(), "mailer");
console.log(mailer.send("[email protected]", "Welcome"));
Text
mailer.send([email protected], Welcome)
sent "Welcome" to [email protected]

The proxy answers every method call by logging it first, so one decorator covers the whole interface. The value.apply(obj, args) matters: calling the method with obj as this keeps private fields and this references working. Passing the proxy itself as this breaks classes with #private fields, which throw a TypeError when accessed through a proxy.

A hand-written wrapper is clearer when you only need a few methods and want type-checking.

hand-written.tsTypeScript
interface Mailer {
  send(to: string, subject: string): Promise<string>;
}

class RealMailer implements Mailer {
  async send(to: string, subject: string) {
    return `sent "${subject}" to ${to}`;
  }
}

class RateLimitedMailer implements Mailer {
  private sent = 0;
  constructor(private readonly inner: Mailer, private readonly limit: number) {}
  async send(to: string, subject: string) {
    if (this.sent >= this.limit) throw new Error(`limit of ${this.limit} reached`);
    this.sent += 1;
    return this.inner.send(to, subject);
  }
}

const mailer: Mailer = new RateLimitedMailer(new RealMailer(), 1);
console.log(await mailer.send("[email protected]", "One"));
try {
  await mailer.send("[email protected]", "Two");
} catch (err) {
  console.log((err as Error).message);
}
Text
sent "One" to [email protected]
limit of 1 reached

RateLimitedMailer implements the same interface and holds an inner Mailer, so it can wrap any implementation, including another decorator.

Decorators in TypeScript syntax

The @decorator syntax is a language feature that applies a function to a class or member at definition time. TypeScript 5.0 and later support the standard ECMAScript decorators, which are a Stage 3 proposal and do not need experimentalDecorators. Check your runtime: Node.js 24 does not run decorator syntax directly, so compile TypeScript first.

method-decorator.tsTypeScript
function logCalls<This, Args extends unknown[], Return>(
  target: (this: This, ...args: Args) => Return,
  context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Return>,
) {
  const name = String(context.name);
  return function (this: This, ...args: Args): Return {
    console.log(`calling ${name}(${args.join(", ")})`);
    return target.call(this, ...args);
  };
}

class Calculator {
  @logCalls
  add(a: number, b: number) {
    return a + b;
  }
}

console.log(new Calculator().add(2, 3));
Text
calling add(2, 3)
5

The decorator receives the original method and returns a replacement, which is the function-wrapping pattern with syntax sugar. The same ideas apply, including the this handling, which is why the replacement calls target.call(this, ...). Frameworks such as NestJS and TypeORM use the older experimental decorators, whose signatures differ from this standard form, so follow your framework's documentation.

Pitfalls

  • Losing the function's identity. A wrapper has a different name and length, and loses custom properties. Copy what matters, or accept it.

  • **Wrong this.** Wrapping a method as a plain function loses its receiver. Use fn.apply(this, args) inside an ordinary function, or bind.

  • Types erased. A generic withCache(fn) in TypeScript needs Parameters<F> and ReturnType<F> to keep the original signature, or callers see any.

  • Hidden cost. Each layer adds a call and often a closure. Stacks of five wrappers on a hot path deserve a look, though you should measure before worrying.

  • Debugging. Stack traces get longer. Name your wrapper functions so frames read withRetry instead of anonymous.

Decorator versus similar patterns

A proxy controls access to an object and may have a different purpose, such as lazy loading or permissions, though the mechanics are the same. An adapter changes the interface, while a decorator keeps it. Middleware in Express and Koa is a chain of decorators around a request handler.

Where the advice stops

Use decorators for cross-cutting concerns that apply to many operations: logging, timing, caching, retry, authorization. Do not use them to bury core logic, because behavior that is hard to see at the call site is hard to debug. If a wrapper is applied in exactly one place, a few lines inside the function are clearer. And remember that order is part of the design, so write it down.

Decorating at the composition root

The cleanest place to apply decorators is where you wire the application, not inside the business code. The service itself stays free of logging and retry concerns, and the composition root states the policy in one readable expression, for example withLogging(withRetry(withCache(realFetcher))). A reader can see the layers in order and change them in a single place, and a test can build the same service with no decorators at all. This keeps cross-cutting concerns visible and separate, which is the reason the pattern exists.

It also gives you configuration per environment. Production wraps the fetcher with retries and metrics, a local environment wraps it with verbose logging only, and a test wraps nothing. Because each decorator exposes the same interface, none of these variations changes a line of the code that uses the fetcher.

Testing decorators

Test a decorator separately from the things it wraps. Give it a fake inner function that records calls, then assert the extra behavior: the cache avoids a second call, the retry stops after the limit, the logger prints the arguments. Then add one test of the stacked result to confirm the order is what you intended. Since the decorator knows nothing about the wrapped function beyond its signature, these tests stay small and apply to every use of it.

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.