The Bridge Pattern in JavaScript, With Real Examples
The bridge pattern splits an abstraction from its implementation so each can vary on its own. See it in JavaScript with notifications, rendering and storage.

The bridge pattern separates an abstraction from its implementation so the two can change independently. It is aimed at a specific problem: a class hierarchy that grows in two directions at once. If you have shapes in several kinds and renderers in several technologies, inheritance forces one class per combination, CircleSvg, CircleCanvas, SquareSvg, SquareCanvas, and each new shape or renderer multiplies the count. A bridge replaces the multiplication with addition: shapes hold a reference to a renderer and delegate the drawing. This post builds the problem and the fix with shapes and renderers, then a more realistic notification example and a storage example, covers the relation to adapter and strategy, testing and the limits, on Node.js 24. Every sample prints its output.
The explosion
Here is the inheritance version.
class CircleSvg {
draw() {
return '<circle r="5"/>';
}
}
class CircleText {
draw() {
return "(o)";
}
}
class SquareSvg {
draw() {
return '<rect width="5" height="5"/>';
}
}
class SquareText {
draw() {
return "[#]";
}
}
for (const shape of [new CircleSvg(), new CircleText(), new SquareSvg(), new SquareText()]) {
console.log(shape.draw());
}<circle r="5"/>
(o)
<rect width="5" height="5"/>
[#]Two shapes and two renderers need four classes. Add a triangle and a canvas renderer and you need nine. Each class duplicates knowledge of both dimensions, and a change to SVG output touches every *Svg class. The dimensions are independent, but the hierarchy ties them together.
The bridge
Split the two dimensions. The abstraction, the shape, holds a reference to the implementation, the renderer, and delegates to it.
// Implementation side: how to draw primitives
const svgRenderer = {
circle: (r) => `<circle r="${r}"/>`,
rect: (w, h) => `<rect width="${w}" height="${h}"/>`,
};
const textRenderer = {
circle: () => "(o)",
rect: () => "[#]",
};
// Abstraction side: what the shapes are
class Circle {
constructor(renderer, radius) {
this.renderer = renderer;
this.radius = radius;
}
draw() {
return this.renderer.circle(this.radius);
}
}
class Square {
constructor(renderer, side) {
this.renderer = renderer;
this.side = side;
}
draw() {
return this.renderer.rect(this.side, this.side);
}
}
console.log(new Circle(svgRenderer, 5).draw());
console.log(new Circle(textRenderer, 5).draw());
console.log(new Square(svgRenderer, 4).draw());
console.log(new Square(textRenderer, 4).draw());<circle r="5"/>
(o)
<rect width="4" height="4"/>
[#]Two shape classes and two renderer objects give all four combinations, and a triangle plus a canvas renderer add one class and one object, five in total, not nine. The reference from shape to renderer is the bridge. A new renderer needs no change to any shape as long as it implements the primitives, and a new shape needs no change to any renderer unless it needs a new primitive.
A realistic example: notifications
The pattern matters most when both sides evolve. Say messages come in kinds, an alert and a receipt, and are delivered by channels, email and SMS. The kind decides content, and the channel decides transport.
// Implementation: how to deliver
const email = {
deliver: ({ to, subject, body }) => `EMAIL to ${to} | ${subject} | ${body}`,
};
const sms = {
deliver: ({ to, subject, body }) => `SMS to ${to}: ${subject} - ${body.slice(0, 30)}`,
};
// Abstraction: what to say
class Notification {
constructor(channel) {
this.channel = channel;
}
send(to, data) {
return this.channel.deliver({ to, ...this.compose(data) });
}
}
class AlertNotification extends Notification {
compose({ service, severity }) {
return { subject: `Alert: ${service}`, body: `${service} is ${severity}. Check the dashboard now.` };
}
}
class ReceiptNotification extends Notification {
compose({ orderId, totalCents }) {
return { subject: `Receipt ${orderId}`, body: `Total charged: ${(totalCents / 100).toFixed(2)}` };
}
}
console.log(new AlertNotification(email).send("[email protected]", { service: "api", severity: "down" }));
console.log(new AlertNotification(sms).send("+15550100", { service: "api", severity: "down" }));
console.log(new ReceiptNotification(email).send("[email protected]", { orderId: "o-1", totalCents: 2900 }));EMAIL to [email protected] | Alert: api | api is down. Check the dashboard now.
SMS to +15550100: Alert: api - api is down. Check the dashboa
EMAIL to [email protected] | Receipt o-1 | Total charged: 29.00The base class Notification is the bridge: it holds the channel and implements send once. Subclasses vary the content only. Adding a push channel means writing one object with a deliver method, and every notification kind can immediately use it. Adding a new kind means writing one subclass, and it works over every channel. SMS truncation is handled in the SMS channel, where it belongs, and the alert text does not know about it.
Without classes
In JavaScript the abstraction side can be plain functions that receive the implementation, so the bridge becomes a function argument.
const channels = {
email: ({ to, subject, body }) => `EMAIL ${to}: ${subject} | ${body}`,
sms: ({ to, subject }) => `SMS ${to}: ${subject}`,
};
const compose = {
alert: ({ service }) => ({ subject: `Alert: ${service}`, body: `${service} is down` }),
receipt: ({ orderId }) => ({ subject: `Receipt ${orderId}`, body: "Thanks for your order" }),
};
function notify(kind, channel, to, data) {
return channels[channel]({ to, ...compose[kind](data) });
}
console.log(notify("alert", "sms", "+15550100", { service: "api" }));
console.log(notify("receipt", "email", "[email protected]", { orderId: "o-9" }));SMS +15550100: Alert: api
EMAIL [email protected]: Receipt o-9 | Thanks for your orderTwo lookup tables, one for each dimension, and a function combining them. This is the lightest form of the pattern, and for many programs it is all you need. The structure is the same: two independent axes of variation, joined at runtime.
A storage example with TypeScript
A typed bridge states the implementation interface, so every backend must satisfy it.
interface Storage {
read(key: string): Promise<string | null>;
write(key: string, value: string): Promise<void>;
}
class MemoryStorage implements Storage {
private data = new Map<string, string>();
async read(key: string) {
return this.data.get(key) ?? null;
}
async write(key: string, value: string) {
this.data.set(key, value);
}
}
class Settings {
constructor(protected readonly storage: Storage) {}
async get(name: string, fallback: string): Promise<string> {
return (await this.storage.read(`settings:${name}`)) ?? fallback;
}
}
class EditableSettings extends Settings {
async set(name: string, value: string): Promise<void> {
await this.storage.write(`settings:${name}`, value);
}
}
const settings = new EditableSettings(new MemoryStorage());
await settings.set("theme", "dark");
console.log(await settings.get("theme", "light"), await settings.get("locale", "en"));dark enSettings and EditableSettings vary independently of MemoryStorage, FileStorage or a database-backed one. The Storage interface is the bridge's implementor side.
Bridge, adapter and strategy
They look alike in code, since all three hold a reference to another object and delegate. The intent separates them.
| Pattern | Intent | When designed |
|---|---|---|
| Adapter | Make an existing incompatible interface fit | After the fact |
| Bridge | Let abstraction and implementation vary independently | Up front |
| Strategy | Swap an algorithm at runtime for one operation | Up front |
A bridge usually involves a whole hierarchy of abstractions over a family of implementations. A strategy is one algorithm slot in one class. If you only have one dimension of variation, you want a strategy, not a bridge.
Testing
Because the implementation side is an interface, tests substitute a recording implementation and check what the abstraction asked of it.
import assert from "node:assert/strict";
import { test } from "node:test";
test("a square asks the renderer for a rect of equal sides", () => {
const calls = [];
const renderer = { rect: (w, h) => calls.push([w, h]) };
class Square {
constructor(r, side) {
this.r = r;
this.side = side;
}
draw() {
return this.r.rect(this.side, this.side);
}
}
new Square(renderer, 3).draw();
assert.deepEqual(calls, [[3, 3]]);
});✔ a square asks the renderer for a rect of equal sides (0.8ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0Test each renderer separately for its output, and test each shape against a fake renderer for its behavior. The number of tests grows with shapes plus renderers, not with their product, which is the same win the pattern gave the code.
Pitfalls
The pattern needs two real axes of variation. If only one side ever changes, the indirection is wasted. It also needs a good implementation interface: if the primitives are too fine, every shape must make many calls, and if too coarse, renderers duplicate logic. Choose the primitives so each is something every implementation can do. And watch for the implementor interface growing a method for every new abstraction, which means the two sides are not independent after all.
Where the advice stops
If you have one abstraction and two implementations, a simple interface and injection is enough, and you do not need to call it a bridge. The pattern's value is in the multiplication it avoids, so reach for it when you can already see the second axis, such as new message kinds arriving while new channels also arrive. Otherwise write the simpler code and refactor to a bridge when the second axis shows up.
A growth story
Consider how this evolves in a real project. A team starts with email notifications. When SMS arrives, someone copies the email class and edits it, and now two classes share most of their logic. Push is next, and the copy-paste doubles again. Meanwhile product asks for a weekly digest, which is a new kind of message, and the team realizes every kind needs every channel. At that point the two axes are visible, and introducing a bridge is a small refactor: move the delivery code into channel objects with one deliver method, and make message kinds hold a channel. The test suite from before keeps passing, because the public behavior did not change.
The lesson is that you rarely need to design a bridge on day one. Notice the second axis when it appears, and extract the implementation side then. The code you write for the first variant, with a clear seam between what to say and how to send it, makes that later refactor cheap.
Keeping the implementor interface honest
The implementation interface is the contract between the two sides, so keep it small and stable. A good test is whether a new implementation can be written without reading the abstraction's code. If the renderer needs to know about shapes to work, the primitives are wrong. Define them in terms of operations every implementation can do, such as drawing a circle or delivering a message, and let the abstraction decide how to combine them. Document the contract in one place, and add a short shared test that any implementation must pass, so a new channel or renderer proves it behaves before it is used.


