Skip to content
jshacks.dev
Patterns

The Builder Pattern in JavaScript, With Real Examples

The builder pattern assembles a complex object step by step. See fluent builders, options objects and immutable builders in JavaScript, and when to skip them.

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

The builder pattern constructs a complex object in steps, so you do not need a constructor with ten parameters or a dozen variants of it. You call .from(), .where() and .limit() and finish with .build(), and the builder holds the partial state in between. It shines when an object has many optional parts, when construction has rules about combinations, or when you want readable call sites. JavaScript offers a lighter alternative that handles most cases, the options object, which this post covers first, so you can tell when a real builder is worth writing. You will see a fluent builder for an HTTP request, validation at build(), an immutable builder, a query builder and the costs, all on Node.js 24 with output shown.

Start with the options object

The classic builder problem is the telescoping constructor.

telescoping.mjsJavaScript
function createRequest(url, method, headers, body, timeout, retries) {
  return { url, method, headers, body, timeout, retries };
}

console.log(createRequest("https://api.example.com/users", "POST", { "content-type": "application/json" }, '{"name":"Ada"}', 5000, 2));
console.log(createRequest("https://api.example.com/users", "GET", undefined, undefined, undefined, 0));
Text
{
  url: 'https://api.example.com/users',
  method: 'POST',
  headers: { 'content-type': 'application/json' },
  body: '{"name":"Ada"}',
  timeout: 5000,
  retries: 2
}
{
  url: 'https://api.example.com/users',
  method: 'GET',
  headers: undefined,
  body: undefined,
  timeout: undefined,
  retries: 0
}

The second call has to pass undefined three times to reach retries, and the reader cannot tell what 0 means without counting. An options object solves it.

options.mjsJavaScript
function createRequest(url, { method = "GET", headers = {}, body, timeout = 10_000, retries = 0 } = {}) {
  return { url, method, headers, body, timeout, retries };
}

console.log(createRequest("https://api.example.com/users", { method: "POST", body: '{"name":"Ada"}', retries: 2 }));
Text
{
  url: 'https://api.example.com/users',
  method: 'POST',
  headers: {},
  body: '{"name":"Ada"}',
  timeout: 10000,
  retries: 2
}

Named, optional and defaulted. For most JavaScript code this is all you need, and a builder would be extra machinery. Reach for a real builder when the parts depend on each other, when the order of steps matters, or when you want to enforce rules before the object exists.

A fluent builder

Here is a builder for an HTTP request where a body only makes sense for some methods and headers accumulate.

request-builder.mjsJavaScript
export class RequestBuilder {
  #url;
  #method = "GET";
  #headers = {};
  #body = undefined;
  #timeout = 10_000;

  constructor(url) {
    this.#url = url;
  }

  method(value) {
    this.#method = value.toUpperCase();
    return this;
  }

  header(name, value) {
    this.#headers[name.toLowerCase()] = value;
    return this;
  }

  json(data) {
    this.#body = JSON.stringify(data);
    return this.header("content-type", "application/json");
  }

  timeout(ms) {
    this.#timeout = ms;
    return this;
  }

  build() {
    if (this.#body !== undefined && ["GET", "HEAD"].includes(this.#method)) {
      throw new Error(`${this.#method} requests cannot have a body`);
    }
    return Object.freeze({
      url: this.#url,
      method: this.#method,
      headers: { ...this.#headers },
      body: this.#body,
      timeout: this.#timeout,
    });
  }
}

const request = new RequestBuilder("https://api.example.com/users")
  .method("post")
  .json({ name: "Ada" })
  .header("Authorization", "Bearer token-123")
  .timeout(3000)
  .build();

console.log(request);

try {
  new RequestBuilder("https://api.example.com/users").json({ a: 1 }).build();
} catch (err) {
  console.log(err.message);
}
Text
{
  url: 'https://api.example.com/users',
  method: 'POST',
  headers: {
    'content-type': 'application/json',
    authorization: 'Bearer token-123'
  },
  body: '{"name":"Ada"}',
  timeout: 3000
}
GET requests cannot have a body

Each method returns this, which is what makes the chain fluent. The advantages over an options object are visible: json() sets the body and the header together, the call site reads like a sentence, and build() is the single place where rules about combinations are checked. The builder's fields are private, so nothing can reach in and produce an invalid half-built request. build() returns a frozen object, so the product is immutable.

An immutable builder

A mutable builder surprises people when it is reused: calling .header() on a shared base builder changes it for everyone.

shared-mutation.mjsJavaScript
import { RequestBuilder } from "./request-builder.mjs";

const base = new RequestBuilder("https://api.example.com/items").header("accept", "application/json");

const a = base.header("x-trace", "a").build();
const b = base.header("x-trace", "b").build();
console.log(a.headers["x-trace"], b.headers["x-trace"]);
Text
a b

That output is right only because build() copies the headers before the second call changes them. But base itself now carries x-trace: b, and the next person who reuses it inherits the leftover. An immutable builder returns a new builder from each step.

immutable-builder.mjsJavaScript
class Builder {
  constructor(state = { headers: {} }) {
    this.state = Object.freeze(state);
  }

  header(name, value) {
    return new Builder({ ...this.state, headers: { ...this.state.headers, [name]: value } });
  }

  build() {
    return { ...this.state };
  }
}

const base = new Builder().header("accept", "application/json");
const a = base.header("x-trace", "a");
const b = base.header("x-trace", "b");

console.log(Object.keys(base.build().headers));
console.log(a.build().headers["x-trace"], b.build().headers["x-trace"]);
Text
[ 'accept' ]
a b

base is unchanged by the two derivations, so it is safe to share. The cost is an allocation per step, which is irrelevant for the dozens of steps a typical builder has.

A query builder

The best-known real builders are query builders. This miniature shows the idea: steps can arrive in any order and build() assembles the string in the order SQL requires.

query-builder.mjsJavaScript
class Query {
  #table;
  #columns = ["*"];
  #conditions = [];
  #params = [];
  #order = null;
  #limit = null;

  constructor(table) {
    this.#table = table;
  }

  select(...columns) {
    this.#columns = columns;
    return this;
  }

  where(column, value) {
    this.#params.push(value);
    this.#conditions.push(`${column} = $${this.#params.length}`);
    return this;
  }

  orderBy(column, direction = "ASC") {
    this.#order = `${column} ${direction}`;
    return this;
  }

  limit(n) {
    this.#limit = n;
    return this;
  }

  build() {
    let sql = `SELECT ${this.#columns.join(", ")} FROM ${this.#table}`;
    if (this.#conditions.length) sql += ` WHERE ${this.#conditions.join(" AND ")}`;
    if (this.#order) sql += ` ORDER BY ${this.#order}`;
    if (this.#limit !== null) sql += ` LIMIT ${this.#limit}`;
    return { sql, params: [...this.#params] };
  }
}

const query = new Query("posts").limit(10).where("status", "published").select("id", "title").where("author_id", 7).orderBy("id", "DESC");
console.log(query.build());
Text
{
  sql: 'SELECT id, title FROM posts WHERE status = $1 AND author_id = $2 ORDER BY id DESC LIMIT 10',
  params: [ 'published', 7 ]
}

Note that values go into params, never into the SQL string, so the builder cannot produce an injectable query by accident. Column and table names are still interpolated, so a real builder must validate or quote them. The caller wrote the steps in an arbitrary order, and the builder produced valid SQL. That decoupling of call order from output order is something an options object cannot do.

A builder that guides with types

In TypeScript, a builder can encode required steps in its type, so forgetting one is a compile error. This sketch uses a different type after each required step.

typed-steps.tsTypeScript
class NeedsUrl {
  url(value: string) {
    return new NeedsMethod(value);
  }
}

class NeedsMethod {
  constructor(private readonly url: string) {}
  method(value: "GET" | "POST") {
    return new Ready(this.url, value);
  }
}

class Ready {
  constructor(
    private readonly url: string,
    private readonly method: string,
  ) {}
  build() {
    return `${this.method} ${this.url}`;
  }
}

console.log(new NeedsUrl().url("https://example.com").method("GET").build());
// new NeedsUrl().build();  // error TS2339: Property 'build' does not exist on type 'NeedsUrl'.
Text
GET https://example.com

build() exists only on the last step's type. This is the "step builder" or "staged builder" variation, useful when some parameters are mandatory. It multiplies the number of classes, so use it for a public API where the guard matters.

The costs

Builders add code: a class, a method per field and a build(). They add a second way to construct the same thing, which a team must keep in sync with the data shape. And a fluent chain has a subtle debugging downside, since a long chain gives one stack frame per line, and the failing step is not always obvious. Prefer a plain object literal with defaults for most data. A builder earns its place when the object is complex, construction is rule-heavy and the same call sites are written by many people.

Where the advice stops

If your options object has fewer than five fields and no rules between them, do not write a builder. If you do not need the object to be immutable or validated, a literal is enough. And in a language with named parameters and good literal syntax like JavaScript, many cases that the original pattern solved simply do not arise. Use a builder for the cases that remain: query construction, request assembly, test data creation and configuration with dependent options.

Builders for test data

One of the most productive uses of a builder is creating test data. Tests need many variations of the same object, a user with an expired subscription, an order with three lines, an admin without an email, and writing each literal in full buries the detail that matters. A test data builder starts from sensible defaults and lets each test override only what it cares about.

user-builder.mjsJavaScript
class UserBuilder {
  #fields = { name: "Ada", email: "[email protected]", role: "member", active: true };

  with(overrides) {
    const next = new UserBuilder();
    next.#fields = { ...this.#fields, ...overrides };
    return next;
  }

  inactive() {
    return this.with({ active: false });
  }

  admin() {
    return this.with({ role: "admin" });
  }

  build() {
    return { ...this.#fields };
  }
}

const base = new UserBuilder();
console.log(base.inactive().build());
console.log(base.admin().with({ name: "Grace" }).build());
Text
{ name: 'Ada', email: '[email protected]', role: 'member', active: false }
{ name: 'Grace', email: '[email protected]', role: 'admin', active: true }

Each test reads as a statement of what is special about it: base.inactive().build(). When a new required field is added to users, you change the defaults in one place and every test keeps working, instead of editing dozens of literals. The builder is immutable, so base is safe to share between tests.

Choosing between the options

Pick by asking what the caller needs. If they only need to name a few optional values, use an options object with defaults. If the object has rules about which combinations are valid, or if call order should not matter, use a builder with validation in build(). If they need to create many variations of a base object, use an immutable builder so the base can be shared. And if some inputs are mandatory, consider a staged builder in TypeScript so the compiler refuses to build an incomplete object. Writing the call site you want to read first, then picking the mechanism that supports it, produces better APIs than starting from the pattern.

Whichever you choose, document the defaults, since a builder with hidden defaults surprises its callers.

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.