# Chain of Responsibility

> Pass a request down a chain of handlers — each one decides to handle it or kick it to the next. The sender never knows who actually does the work.

- **Category**: Software Design
- **Subcategory**: behavioral
- **Canonical URL**: https://designpattern.fyi/patterns/chain-of-responsibility/

---

## Description
**Intent**: Decouple the thing that sends a request from the thing that handles it, with multiple potential handlers in play.

**Context**: You have requests that need different processing depending on type, priority, or context — middleware pipelines, auth checks, logging layers, support ticket escalation. Hard-coding which handler does what creates a branching mess.

**Solution**: Build a chain of handler objects. Each handler has a reference to the next. When a request arrives, the handler either processes it or calls `next.handle(request)`. Handlers are added, removed, or reordered without touching each other or the client.


## Use Cases
Use for middleware pipelines (Express, Koa), event processing with fallbacks, auth/validation chains, or any scenario where multiple handlers might process a request in sequence.



## Implementation Example

```javascript
class Handler {
  setNext(handler) {
    this.nextHandler = handler;
    return handler;
  }
  handle(request) {
    if (this.nextHandler) {
      return this.nextHandler.handle(request);
    }
    return null;
  }
}

class MonkeyHandler extends Handler {
  handle(request) {
    if (request === "Banana") {
      return `Monkey: I'll eat the ${request}.`;
    }
    return super.handle(request);
  }
}

```



## Trade-offs


### Advantages

- Add, remove, or reorder handlers without touching the client or other handlers.

- Each handler has one job — clean Single Responsibility.

- New handlers plug in without breaking anything downstream.




### Considerations & Drawbacks

- Requests can fall off the end of the chain unhandled if you forget a catch-all fallback.







---
**Reference**: [Original Source](https://refactoring.guru/design-patterns/chain-of-responsibility)

