<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ahmed Boukri on Medium]]></title>
        <description><![CDATA[Stories by Ahmed Boukri on Medium]]></description>
        <link>https://medium.com/@aboukri?source=rss-4965f8ce1051------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GWgzUkdO85qDcHWKE3tS-g.jpeg</url>
            <title>Stories by Ahmed Boukri on Medium</title>
            <link>https://medium.com/@aboukri?source=rss-4965f8ce1051------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 12:59:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aboukri/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From Callbacks to Observables (2/2): When Is a Message Actually Done?]]></title>
            <link>https://medium.com/@aboukri/from-callbacks-to-observables-2-2-when-is-a-message-actually-done-7a2dbc6fee6c?source=rss-4965f8ce1051------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a2dbc6fee6c</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Ahmed Boukri]]></dc:creator>
            <pubDate>Sun, 01 Nov 2026 15:58:44 GMT</pubDate>
            <atom:updated>2026-11-01T15:58:44.940Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A handler can return a value, a Promise, or an Observable. A broker only understands “done” or “not done”. Everything hard about a message consumer lives in that gap.</em></p><p>Part 1 ended on the two differences that really separate a Promise from an Observable. First: are delivering a value and finishing one event or two? Second: what makes the work start? A Promise delivers its value and finishes in a single event, and its work was launched when the Promise was created, not when you await it. An Observable keeps the two events apart, and when it’s <em>cold</em> (the common case), its work starts only when someone subscribes.</p><p>This second difference rarely matters, until you write a message consumer. The consumer calls a handler it didn’t write and gets back a result it didn’t choose. Then it must tell the broker that the work succeeded, and it can’t take that back.</p><p>Same domain as part 1: an e-commerce backend, an order.placed message arriving from Azure Service Bus, our broker, and a NestJS custom transport strategy in the middle.</p><p><em>→ Part 1: callbacks, Promises and Observables, and what really separates them. </em><a href="https://medium.com/@aboukri/from-callbacks-to-observables-1-2-promises-observables-and-what-really-separates-them-e51a47e0edd8?sharedUserId=aboukri">https://medium.com/@aboukri/from-callbacks-to-observables-1-2-promises-observables-and-what-really-separates-them-e51a47e0edd8?sharedUserId=aboukri</a></p><h3>The contract you sign with the broker</h3><p>Under PeekLock (the default, and the mode to reach for as soon as losing a message is unacceptable), receiving a message isn’t taking it. It’s <strong>borrowing it, exclusively, for a limited time</strong>. Four main ways to give it back:</p><ul><li>completeMessage(): the processing succeeded, delete it;</li><li>abandonMessage(): I can&#39;t process it right now, put it back in circulation;</li><li>deadLetterMessage(): no point retrying it, park it out of the way;</li><li>say nothing and let the lock expire: the message becomes available again, for any consumer.</li></ul><p>Notice what’s missing from that list. <strong>None of these options means “I received it.”</strong> The broker doesn’t care that the message reached your process. It cares whether the work is finished. So the consumer’s job comes down to one question, asked for every message:</p><blockquote><strong><em>When can I safely consider this message processed?</em></strong></blockquote><h3>A handler can return three different things</h3><p>In NestJS, you can write the order.placed handler in any of these three ways, and all three are valid:</p><pre>@MessagePattern(&#39;order.placed&#39;)<br>handleOrderPlaced(order: Order): Receipt { /* synchronous */ }<br>@MessagePattern(&#39;order.placed&#39;)<br>handleOrderPlaced(order: Order): Promise&lt;Receipt&gt; { /* TypeORM, repositories */ }<br>@MessagePattern(&#39;order.placed&#39;)<br>handleOrderPlaced(order: Order): Observable&lt;Receipt&gt; { /* HttpService, RxJS */ }</pre><p>From inside the transport strategy, you don’t call your method directly, but a wrapper that NestJS builds around it. Its type, Promise&lt;Observable&lt;T&gt;&gt; | Promise&lt;T&gt;, only tells you one thing: you get a Promise, which may hold a plain value or an Observable.</p><pre>const handler = this.messageHandlers.get(pattern);<br>const result: unknown = handler(message.body);</pre><p>unknown is the honest type. Whatever comes back has to be inspected at runtime.</p><h3>The naive version, and why it lies</h3><p>Here’s the consumer everyone writes first:</p><pre>const processMessage = async (message: ServiceBusReceivedMessage) =&gt; {<br>  const handler = this.messageHandlers.get(message.subject as string);<br><br>  handler(message.body);<br>  await this.receiver.completeMessage(message);<br>};</pre><p>Every message succeeds. Instantly. Including the ones that fail.</p><p>handler() returns a Promise that is still pending. The stock isn&#39;t reserved yet, the payment isn&#39;t charged yet, and the message is already deleted from the queue. If the payment API times out three seconds later, all that&#39;s left is a log line: the message that would have triggered a retry no longer exists. The broker guaranteed you <em>at-least-once</em>; <strong>your processing has just become <em>at-most-once</em></strong>: a guarantee nobody chose here.</p><p>The fix looks obvious:</p><pre>const result: unknown = await handler(message.body);<br>await this.receiver.completeMessage(message);</pre><p>It works when the handler returns a value or a Promise, and succeeds. In every other case it quietly breaks, starting with Observables.</p><h3>The Observable case, where it quietly breaks</h3><p>Remember part 1: await only waits for thenables, objects with a .then() method. An Observable has no .then(). So await returns it right away, without waiting for anything, and nobody subscribes to it.</p><p>But in a cold Observable, subscribing is what starts the work. No subscriber means the work <strong>never starts</strong>:</p><pre>@MessagePattern(&#39;order.placed&#39;)<br>handleOrderPlaced(order: Order): Observable&lt;Receipt&gt; {<br>  return this.http<br>    .post&lt;Receipt&gt;(&#39;/fulfillment&#39;, order)<br>    .pipe(map(response =&gt; response.data));<br>}</pre><p>With this consumer, that POST is never sent. The Observable is created, await returns it unchanged, and it&#39;s thrown away. The message is completed and deleted from the queue. Fulfillment never heard about the order, and every log line in the system says success.</p><p>You might object that you never write .subscribe() yourself, and everything works. That&#39;s true in a NestJS HTTP controller: the framework subscribes for you, because it needs the value to build the response. In a custom transport strategy, you are the framework.</p><p>There’s no exception to catch here, which is what makes this bug hard to spot. A cold Observable that nobody subscribes to doesn’t fail. It just never runs.</p><p>The NestJS wrapper makes this worse: an async handler also comes back as an Observable when it throws, or when an interceptor is registered. In both cases, await alone completes the message without the work being done or the failure being seen by the consumer. Every handler needs the Observable check, not only those that return one.</p><h3>lastValueFrom(): the bridge between the two worlds</h3><p>RxJS ships the adapter:</p><pre>const result: unknown = await handler(message.body);<br><br>if (isObservable(result)) {<br>  await lastValueFrom(result);<br>}</pre><p>lastValueFrom subscribes (which starts the work), keeps the latest value, and returns a Promise that <strong>resolves on </strong><strong>complete</strong> and rejects on error:</p><pre>Observable<br>    ├── next(value)<br>    ├── next(value)<br>    └── complete  ──────────→  the Promise resolves</pre><p>The key word is complete, not next. For an HttpService call, the value and the completion arrive together, so you can&#39;t see the difference. On a real stream you can: if the Observable never completes, lastValueFrom never resolves, your consumer waits forever, and the message lock expires while it waits. A timeout() in the pipe turns a stream that goes silent into a visible error. But it measures the time between two values, not the total time, so it won&#39;t stop a stream that keeps emitting. If the first value is your success signal, use firstValueFrom() instead: it unsubscribes as soon as it gets one.</p><h3>Another trap: EmptyError</h3><p>lastValueFrom on an Observable that completes <strong>without emitting anything</strong> doesn&#39;t resolve. It rejects, with EmptyError: no elements in sequence.</p><p>That’s not an edge case. A handler with nothing to do is enough:</p><pre>@MessagePattern(&#39;order.placed&#39;)<br>handleOrderPlaced(order: Order): Observable&lt;Receipt&gt; {<br>  if (order.items.length === 0) {<br>    return EMPTY; // nothing to ship<br>  }<br>  return this.http<br>    .post&lt;Receipt&gt;(&#39;/fulfillment&#39;, order)<br>    .pipe(map(response =&gt; response.data));<br>}</pre><p>An order with no items has nothing to ship, so the handler returns EMPTY: a stream that completes right away without emitting anything. For the handler, that&#39;s a success. For lastValueFrom, it&#39;s an error. Your consumer catches an EmptyError and abandons the message. It comes back, fails the same way, and goes around until maxDeliveryCount sends a perfectly valid order to the dead-letter queue.</p><p>The reflex is to silence it with lastValueFrom(result, { defaultValue: undefined }). But that option turns every empty stream into a success, for every handler at once, including a bug that skipped the work. So choose a contract, once per consumer: either completion is enough, and defaultValue is fine, or a value is required, and a handler with nothing to do emits one explicitly instead of returning EMPTY.</p><h3>Putting it together</h3><p>The receiver is subscribed with autoCompleteMessages: false, since the consumer settles every message itself:</p><pre>const processMessage = async (message: ServiceBusReceivedMessage) =&gt; {<br>  const pattern = message.subject as string;<br>  const handler = this.messageHandlers.get(pattern);<br><br>  if (!handler) {<br>    await this.receiver.deadLetterMessage(message, {<br>      deadLetterReason: &#39;NoHandler&#39;,<br>      deadLetterErrorDescription: `No handler registered for pattern: ${pattern}`,<br>    });<br>    return;<br>  }<br><br>  try {<br>    const result: unknown = await handler(message.body);<br><br>    if (isObservable(result)) {<br>      await lastValueFrom(result); // see the EmptyError contract above<br>    }<br>  } catch (error) {<br>    this.logger.error(`Handler failed for pattern ${pattern}`, error);<br>    await this.receiver.abandonMessage(message);<br>    return;<br>  }<br><br>  await this.receiver.completeMessage(message);<br>};</pre><p>Call the handler, wait for the work to finish whatever its shape, <em>then</em> acknowledge. completeMessage() stays outside the try: if it fails, the handler didn&#39;t. The rest of the article covers what this code doesn&#39;t handle yet.</p><h3>The unhandled pattern that leaks a lock</h3><p>The first version of this code did something reasonable-looking:</p><pre>if (!handler) {<br>  console.warn(`No handler found for pattern: ${pattern}`);<br>  return;<br>}</pre><p>Returning settles nothing. What happens next depends on autoCompleteMessages:</p><ul><li><strong>false</strong>: the SDK keeps renewing the lock for a while (5 minutes by default), then lets it expire. The message comes back, hits the same missing handler, and goes around again until maxDeliveryCount sends it to the dead-letter queue. With default settings, that&#39;s around fifty minutes of useless retries.</li><li><strong>true</strong>, the SDK default: your callback didn&#39;t throw, so the SDK completes the message. It&#39;s gone, and all that&#39;s left of it is a console.warn.</li></ul><p>Neither is what you want.</p><p>You know on the first attempt that this message can’t be processed. Say so right away: dead-letter it yourself, with a reason. It’s faster, and it leaves a readable explanation in the dead-letter queue.</p><h3>abandonMessage is not a retry strategy</h3><p>Abandon puts the message back <strong>immediately</strong>, with no delay. The same code runs again, with the same payload, against the same API that just failed. If that API is down, you’ve built a tight retry loop against a service that’s already struggling. You’ll burn through maxDeliveryCount very quickly and dead-letter a message that would have worked thirty seconds later.</p><p>The first fix is to stop treating all failures alike:</p><pre>} catch (error) {<br>  if (error instanceof ValidationError) {<br>    await this.receiver.deadLetterMessage(message, {<br>      deadLetterReason: &#39;ValidationFailed&#39;,<br>      deadLetterErrorDescription: error.message,<br>    });<br>    return;<br>  }<br><br>  await this.receiver.abandonMessage(message);<br>  return;<br>}</pre><p>A malformed payload will never succeed, however many times you retry it, so dead-letter it on the first attempt. Only temporary failures deserve a redelivery. For a real <em>backoff</em>, abandon is not the tool: you have to republish a delayed attempt with scheduleMessages(), at the cost of one more message in the system.</p><p>One catch in NestJS: by default, <strong>the error your consumer catches is not the one the handler threw</strong>. The wrapper replaces it with a generic { status: &#39;error&#39;, message: &#39;Internal server error&#39; }, so the instanceof check above is always false. A @Catch() filter on the consumer&#39;s controller that returns throwError(() =&gt; exception) fixes it.</p><h3>The failure path only exists if the handler lets it</h3><p>There’s a version of this consumer where the entire catch block is dead code. It&#39;s more common than it sounds, and it looks like this:</p><pre>@MessagePattern(&#39;order.placed&#39;)<br>async handleOrderPlaced(message: OrderMessage): Promise&lt;void&gt; {<br>  try {<br>    await this.orchestrator.process(message);<br>    await this.events.publish(successEvent(message));<br>  } catch (error) {<br>    this.logger.error(`Order ${message.orderId} failed`, error);<br>    await this.events.publish(failureEvent(message, error));<br>    // no rethrow<br>  }<br>}</pre><p>The handler swallows the exception, reports the failure through its own channel, and returns normally. From the consumer’s point of view that’s a success: await handler(...) resolves, completeMessage() runs, the message is deleted. The abandonMessage branch never runs for this pattern.</p><p>That may be exactly what you want. Reporting failures as business events instead of broker retries is a legitimate design: if the event is stored, it leaves a durable, queryable error trail, and it stops a permanently broken payload from cycling through the queue. But it has to be a decision, not a side effect. The moment a handler catches everything, you’ve opted out of redelivery, out of maxDeliveryCount and out of the dead-letter queue, and a two-second database blip now produces a permanent failure event where a retry would have succeeded.</p><p><strong>The rule: whoever catches the exception owns the retry.</strong> If the handler keeps the error, the handler decides what happens next. If you want the broker to decide, rethrow.</p><h3>The lock has a deadline, and concurrency spends it</h3><p>Under PeekLock, the lock has a limited lifetime, set on the queue. The SDK renews it for you in the background, up to a ceiling you can raise when you create the receiver.</p><p>So if you see The lock supplied is invalid while renewal is on, you didn&#39;t forget to renew. Renewal wasn&#39;t enough. Most often, either the processing took longer than the ceiling, or the event loop was too busy for the renewal timer to fire on time, or the connection dropped. The event loop case is the hardest to catch, because it only shows up under load.</p><p>And the error shows up at the worst moment: it’s the <strong>acknowledgement</strong> that fails, not the work. The order was fulfilled, but the message becomes available again, and another consumer may already have picked it up. Each of these errors can turn into a duplicate order.</p><p>This is the key point of the article: <em>at-least-once</em> is not a bug to remove. It’s the contract. A message you tried to acknowledge can still come back. So the handler must be <strong>idempotent</strong>: seeing the same message twice must not produce two effects, for example thanks to a unique constraint on the order.</p><p>And be careful with maxConcurrentCalls, the option you pass to receiver.subscribe(). A message&#39;s renewal budget starts running as soon as it&#39;s received, even while the handler is only waiting, for example for a free database connection. Raise concurrency beyond what your database pool or downstream API can handle and you don&#39;t get more throughput. You get handlers queuing on a saturated resource while their locks run out.</p><h3>What “finished” actually means</h3><p>The whole article, in one table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nSCCfO3VGz36vTGMaVXvLw.png" /></figure><p>Read it top to bottom: from the handler down, each row relies on the ones above it. The handler’s result comes from a Promise or an Observable, the consumer trusts the handler, and the broker trusts the consumer. Break one link and the rows below give the wrong answer. A consumer that never subscribes reports a success that never happened. A lock lost during acknowledgement reports a failure for work that was done.</p><p>isObservable(result) is a single line. But it&#39;s where JavaScript&#39;s async model meets the broker&#39;s delivery guarantee, and that&#39;s where bugs hide.</p><p>Callbacks, Promises and Observables can all tell you <em>it’s done</em>. A broker asks a harder question: <strong>is it done enough that I can forget about it?</strong> No library can know that for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a2dbc6fee6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Callbacks to Observables (1/2): Promises, Observables, and What Really Separates Them]]></title>
            <link>https://medium.com/@aboukri/from-callbacks-to-observables-1-2-promises-observables-and-what-really-separates-them-e51a47e0edd8?source=rss-4965f8ce1051------2</link>
            <guid isPermaLink="false">https://medium.com/p/e51a47e0edd8</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ahmed Boukri]]></dc:creator>
            <pubDate>Mon, 07 Sep 2026 23:42:43 GMT</pubDate>
            <atom:updated>2026-09-07T23:42:43.094Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Three abstractions, one syntax, and a single question: what do you do when the result isn’t there yet? A guided tour, from the oldest to the most misunderstood.</em></p><p>Open any mature NestJS codebase and you’ll find all four living side by side: an event emitter taking a callback, a repository returning a Promise, business logic written with async/await, and an HttpService handing you an Observable. Nobody planned that. Each one showed up at a different moment, for a problem the ones before it didn’t solve, and none of them ever left.</p><p>The result is a language most developers speak fluently without ever having learned the grammar. You know await works. You know .subscribe() works. What&#39;s usually murky is why a function returns one rather than the other, and what that choice actually changes.</p><p>That gap is rarely about syntax. It’s conceptual. And it starts with a clarification that heads off half the confusion: those four names cover only <strong>three abstractions</strong>. A callback lets the producer call you back when something happens; a Promise stands for a single eventual result; an Observable delivers zero, one or many values, as they arrive. async/await isn&#39;t a fourth abstraction: it&#39;s syntax over Promises, for readably chaining operations that each produce one result. Three models, one writing convenience, and a single question:</p><blockquote><strong><em>What do you do when the result of an operation isn’t available yet?</em></strong></blockquote><p>Every example below comes from the same place: an e-commerce backend processing an order. Place the order, reserve the stock, charge the payment, notify the customer. Nothing exotic, but every one of those steps takes time.</p><h4>The problem never changed: the result isn’t there yet</h4><p>Lay out the steps with their real cost and the problem becomes obvious:</p><pre>validateOrder(order);   //  &lt; 1 ms  : pure computation<br>reserveStock(order);    //  ~40 ms  : database<br>chargePayment(order);   // ~800 ms  : external payment API<br>notifyCustomer(order);  // ~120 ms  : another service</pre><p>Only the first line is free. The other three spend most of their time waiting on something that isn’t your process, and your JavaScript runs on a single thread. Node does hand the I/O itself off to the OS. That’s the whole point of the event loop, but the thread executing <em>your</em> code is still just one thread: keep it busy waiting and nothing else gets served. So the language never offered “wait here”. It only ever offered variations on one sentence:</p><blockquote><em>“Start this operation, and let me know when it’s done.”</em></blockquote><p>Callbacks, Promises and Observables are three ways of saying it.</p><h4>Callbacks: “call me back when you’re done”</h4><p>The oldest answer, and the most direct: you hand the operation a function, and it calls it when it has something for you.</p><pre>reserveStock(order, (error, reservation) =&gt; {<br>  if (error) return handleFailure(error);<br>  console.log(&#39;Stock reserved:&#39;, reservation.id);<br>});</pre><p>That’s the Node convention: error first, result second. It works, it’s still everywhere, and for a single operation it’s perfectly readable. The trouble starts when one operation depends on another:</p><pre>reserveStock(order, (error, reservation) =&gt; {<br>  if (error) return handleFailure(error);<br><br>  chargePayment(order, (error, payment) =&gt; {<br>    if (error) return releaseStock(reservation, () =&gt; handleFailure(error));<br><br>    notifyCustomer(order, (error) =&gt; {<br>      if (error) return handleFailure(error);<br>      // 3 levels deep, and we haven&#39;t done anything interesting yet<br>    });<br>  });<br>});</pre><p>This is what everyone calls <strong>callback hell</strong>, and almost everyone misdiagnoses it. The problem isn’t the indentation. Indentation is a symptom. The problem is that <strong>the pending operation isn’t a value</strong>.</p><p>The callback is obviously a value in JavaScript: a function you can store, pass around, return. But it stands for what to do <em>afterwards</em>, not for the reservation currently in flight. There’s no object to hold, to return, or to hand to a function whose job would be to wait on three of them at once.</p><p>And try/catch is no help either:</p><pre>try {<br>  reserveStock(order, (error, reservation) =&gt; {<br>    if (error) throw error;<br>  });<br>} catch (error) {<br>  // never reached: the callback runs after this block has exited<br>}</pre><p>The callback runs later, once the I/O completes, long after the try block is gone from the stack. Errors have to travel back through the callback path by hand: every level re-handles them, and one forgotten if (error) silently swallows a failure. Composition, error handling and readability degrade together, because they all rest on the same missing thing.</p><p>JavaScript’s next move was to invent exactly that object.</p><h4>Promise: an object that stands for a future result</h4><p>Instead of “give me a function I’ll call later”, a Promise says:</p><blockquote><em>“Give me an object that stands for the result. I’ll fill it in.”</em></blockquote><pre>const reservation: Promise&lt;Reservation&gt; = reserveStock(order);</pre><p>reserveStock doesn&#39;t return a Reservation. It returns a Promise&lt;Reservation&gt;, a placeholder with three states and a one-way trip between them:</p><pre>pending<br>             │<br>      ┌──────┴──────┐<br>      ↓             ↓<br>  fulfilled     rejected<br>   (value)      (reason)</pre><p>It starts pending, then <strong>settles once</strong>: it either produces a value or fails with a reason, and the transition is irreversible. That’s the entire contract.</p><p>The consequence is bigger than it looks. A Promise is <strong>the pending operation, as a value</strong>, so everything you can do with a value, you can now do with work in flight:</p><pre>const [customer, rates] = await Promise.all([<br>  loadCustomer(order.customerId),<br>  loadShippingRates(order.address),<br>]);</pre><p>Two operations running in parallel, one line, one failure path. Try that with callbacks: you can, but you’ll write the coordination yourself, a counter, a results array, a guard so the final callback fires exactly once. Promise.all exists because there&#39;s finally an object to pass it.</p><p>One more property, easy to skim past and central to part 2: <strong>a Promise is eager</strong>. By the time loadCustomer(order.customerId) has returned, the query is already in flight. Nothing had to ask for it. .then() doesn&#39;t start the work: it only decides who hears about the result.</p><h4>async/await: the same thing, readable</h4><p>Promises fixed composition, not readability. Chained .then() calls get long, and threading a value from step one into step three means nesting or juggling:</p><pre>reserveStock(order)<br>  .then(reservation =&gt;<br>    chargePayment(order).then(payment =&gt; ({ reservation, payment })),<br>  )<br>  .then(({ reservation, payment }) =&gt; notifyCustomer(order).then(() =&gt; payment))<br>  .catch(handleFailure);</pre><p>async/await is syntax over the exact same objects:</p><pre>async function processOrder(order: Order): Promise&lt;Receipt&gt; {<br>  const reservation = await reserveStock(order);<br><br>  let payment: Payment;<br>  try {<br>    payment = await chargePayment(order);<br>  } catch (error) {<br>    await releaseStock(reservation);<br>    throw error;<br>  }<br><br>  await notifyCustomer(order);<br>  return { reservation, payment };<br>}</pre><p>That’s the callback pyramid from earlier, flattened, with try/catch, return and throw all working again. Nothing became synchronous, though: processOrder still returns a Promise&lt;Receipt&gt;, and every await suspends <em>that function</em> until the value lands, without blocking the thread, , which moves on to serve something else in the meantime..</p><p>And now the detail that carries the whole second part of this series: <strong>await doesn&#39;t mean &quot;wait for anything asynchronous&quot;. It waits for thenables</strong>: anything exposing a .then() method. Give it anything else and you get that value back, unchanged:</p><pre>const answer = await 42;               // 42<br>const order  = await { id: &#39;A-1024&#39; }; // { id: &#39;A-1024&#39; }, untouched</pre><p>No error, no warning. await on a non-thenable is a no-op with extra steps.</p><p>Which is what turns that curiosity into the hinge of this whole series: <strong>an Observable is not a thenable</strong>. It exposes .subscribe(), not .then(). Hand one to await and it comes straight back, unwaited, with nothing having happened. Part 2 grows entirely out of that single fact.</p><h4>What if there isn’t just one future result?</h4><p>await fits one shape perfectly: one operation, one future result, done. Plenty of problems don&#39;t have that shape.</p><p>Say the customer wants to follow their order live:</p><pre>order.placed → stock.reserved → payment.charged → shipment.created → delivered</pre><p>Five values, arriving over minutes or days, and what you want here is each one as it lands, not just the final one. A Promise settles once, definitively: it stands for <em>a </em>completion. Nothing stops you creating one per event as they come, but then the sequence is yours to hold: who creates the next one, when, and how the consumer learns there won’t be another. At that point you’re not modelling a stream, you’re rebuilding one by hand.</p><p>Same story for a WebSocket, a file read in chunks, keystrokes in a search box, or a queue of incoming messages. The abstraction that fits isn’t “a future value”. It’s <strong>values over time</strong>.</p><h4>Observable: a stream of values over time</h4><p>That’s the ReactiveX model; RxJS is its JavaScript implementation. An Observable can push <strong>zero, one, or many</strong> values over time, and may eventually terminate, either by completing or by failing:</p><pre>const orderEventsObs: Observable&lt;OrderEvent&gt; = trackOrder(order.id);<br><br>orderEventsObs.subscribe({<br>  next:     event =&gt; console.log(&#39;Status:&#39;, event.status),<br>  error:    error =&gt; console.error(&#39;Tracking lost&#39;, error),<br>  complete: ()    =&gt; console.log(&#39;Order closed&#39;),<br>});</pre><p>The Obs suffix is only a naming habit: it marks a variable holding a stream rather than a value.</p><p>Three channels, and their arithmetic is the whole point: next fires zero to n times, error and complete fire at most once and are mutually exclusive. A Promise has only two ways to settle, fulfilled or rejected, and both of them end it: nothing resembling next, no way to deliver a value without ending. For a Promise, <strong>producing the value and finishing are the same event</strong>.</p><p><strong>In an Observable they’re two different events.</strong> A stream can hand you three values and keep running. It can complete without ever emitting anything. It can also never terminate at all. Hold on to that sentence: part 2 turns on it entirely.</p><p>An Observable can also emit exactly one value and stop:</p><pre>of(reservation) // one value, then complete</pre><p>Which is why “Promise = one value, Observable = many values” is a decent first approximation and a poor mental model. The real difference is elsewhere.</p><h4>The difference that actually matters: lazy vs eager</h4><p>Two lines of the same shape, behaving nothing alike:</p><pre>const payment  = chargePayment(order);          // Promise:    the work has ALREADY started<br>const paymentObs = http.post(&#39;/payments&#39;, order); // Observable: nothing has happened</pre><p>An Observable is a <strong>recipe, not a result</strong>. And the recipe doesn’t run until someone subscribes. No subscriber means no HTTP request, no database write, no side effect, ever:</p><pre>const auditObs = this.http.post(&#39;/audit&#39;, { orderId: order.id });<br>// nothing was posted. The request doesn&#39;t exist yet.<br><br>auditObs.subscribe(); // now it goes out</pre><p>That distinction has caused more than one production incident, and it drags two more behind it.</p><p>Because the recipe is executed for each subscriber, <strong>each subscription redoes the work</strong>. Two subscribers on that auditObs therefore means two POST requests: that&#39;s a <em>cold</em> Observable, the default and by far the most common case. A <em>hot</em> one emits independently of any subscription; subscribers present at the same moment can therefore receive the same events.</p><p>A Promise works differently: its work starts the moment it is created and runs only once; every .then() attached to it then observes the same result, or the same error.</p><p>And because a cold Observable’s work is owned by each subscription, <strong>it gives you an off switch</strong>: unsubscribe() runs the teardown declared by its source. An interval is cleared, and Nest&#39;s HttpService cancels its underlying Axios request by default. What unsubscribe() guarantees is that no further notifications will be delivered to that subscriber; whether an operation already in flight is genuinely interrupted depends on the source.</p><p>A Promise doesn’t even offer that first level of cancellation: it has no cancellation protocol of its own. You can abort an underlying operation with an AbortController, but that capability belongs to the operation&#39;s API, not to the Promise itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*QRvpW7VJaNfOQNNVSupxdQ.png" /></figure><h3>Choosing between them, in one question</h3><p><strong>The rule: one result, use a Promise. Values over time, use an Observable.</strong> Useful, and not quite enough, because plenty of Observables carry a single value.</p><p>The sharper test is to ask which question you need answered. <em>What is the value?</em> Or <em>is it finished?</em> A Promise answers both at once and can’t separate them. An Observable answers them on two different channels, which is more power and more rope.</p><p>NestJS doesn’t pick for you, and neither choice is a workaround. TypeORM hands you Promises, HttpService hands you Observables, and a message handler can return either:</p><pre>@MessagePattern(&#39;order.placed&#39;)<br>handleOrderPlaced(order: Order): Promise&lt;Receipt&gt; {<br>  return this.orders.process(order);<br>}</pre><pre>@MessagePattern(&#39;order.placed&#39;)<br>handleOrderPlaced(order: Order): Observable&lt;Receipt&gt; {<br>  return this.http<br>    .post&lt;Receipt&gt;(&#39;/fulfillment&#39;, order)<br>    .pipe(map(response =&gt; response.data));<br>}</pre><p>Both are valid. Both compile. And the piece of infrastructure that invokes that handler only finds out which one it got after calling it: at runtime, the declared type is gone.</p><p>You now have the three abstractions, the syntax that makes them readable, and the two axes that actually separate a Promise from an Observable: whether delivering a value and finishing are one event or two, and what makes the work start. That’s enough to read almost any asynchronous code. It isn’t enough to write the layer underneath: the one that receives a Promise or an Observable it didn’t choose, and has to decide when the work is really done.</p><p>That’s part 2: a NestJS consumer plugged into Azure Service Bus, lastValueFrom(), and the deceptively simple question of what &quot;finished&quot; means.</p><p><em>→ Part 2, coming soon: when is a message actually done? Acknowledgement, </em><em>lastValueFrom() and message locks.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e51a47e0edd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[We Talk a Lot About Technical Change. Much Less About the People Who Live It.]]></title>
            <link>https://medium.com/@aboukri/we-talk-a-lot-about-technical-change-much-less-about-the-people-who-live-it-467722d9e603?source=rss-4965f8ce1051------2</link>
            <guid isPermaLink="false">https://medium.com/p/467722d9e603</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[engineering-management]]></category>
            <category><![CDATA[change-management]]></category>
            <category><![CDATA[leadership]]></category>
            <dc:creator><![CDATA[Ahmed Boukri]]></dc:creator>
            <pubDate>Fri, 14 Aug 2026 20:59:27 GMT</pubDate>
            <atom:updated>2026-08-14T20:59:27.359Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Introducing clean architecture (or any other new practice) rarely fails on the diagrams. What my experience taught me about developers, change, and trust.</em></p><p>In many teams, the scene goes like this. On a Tuesday morning, the lead books a room and presents the new direction: clean architecture. The slides are polished, the hexagons neatly aligned, every dependency pointing inward. At the end: “Any questions?” A couple of nods, a polite silence, and everyone goes back to coding. Three months later, the new layers exist, but business logic keeps leaking into the controllers, and nobody seems to really know why any of this is happening.</p><p>The natural reaction at that point is to look for a technical explanation: was the slicing right, should there have been a pilot module, was the documentation lacking? Yet the problem is almost always somewhere else. Diagrams won’t apply the new architecture, and the backlog won’t write the code. Developers will. Humans. And the question “how do we get this change right technically?” has a twin we ask far less often: <strong>how are the developers going to live through this change?</strong></p><p>That second question is the one I want to talk about. Not the hexagons or the layers (maybe a future article): what happens inside a team the moment you ask it to change.</p><p>I have been through this kind of change, and it isn’t the technology that left a mark. It’s the signals I failed to read at the time: a silence in a meeting, an objection dropped too quickly, an “okay” that meant something else.</p><h3>Resistance isn’t always bad faith</h3><p>Back to the Tuesday meeting. One of the most experienced developers on the team knows the application inside out. They spend the workshop raising objections: “what about performance?”, “what about this edge case?”, “we already tried something like this before”. The immediate reading: they’re resisting change.</p><p>Sometimes that’s true. But often, what we call resistance is something else: confusion, or fear. Fear of not measuring up, of not getting what everyone else seems to get, of being judged, or simply of losing one’s bearings. A technical decision can call years of habits into question; it can mean relearning your craft, and it can make accumulated experience suddenly feel worthless. Taking the theory apart is a comfortable position; admitting you no longer know where you stand is a much harder one. <strong>What looks like a refusal to learn is often a way of protecting yourself.</strong></p><p>This distinction matters because it changes how you respond. If you read fear as bad faith, you will answer with more pressure. And pressure doesn’t create buy-in. It creates silence.</p><h3>Silence is far more dangerous than disagreement</h3><p>A developer who says “I disagree with this approach” is doing you a favor: you know where the friction sits, you can discuss it, understand their reasoning, lay out yours, and maybe discover something you hadn’t seen.</p><p>The real problem starts when they stop saying anything. They nod, comply, approve the pull requests. Deliveries keep coming, the indicators stay green. Seen from the dashboards, the change is a success. But something broke: trust. <strong>And unlike a bug, trust never shows up in the logs.</strong></p><p>That’s what makes this scenario so dangerous: it triggers no alert. A disagreement can be settled with a conversation; entrenched silence sends the bill months later: disengagement, resignations, “what’s the point, they’ve already decided”. A developer who still dares to speak can still be convinced; a developer who has gone quiet is already halfway out the door.</p><h3>You can win the technical argument and lose the team</h3><p>Let’s grant that the decision is excellent: the target architecture is better and the code will be more testable. None of that guarantees the buy-in of the people who will have to live with it. Announcing “from now on, this is how we work”, then acting surprised weeks later that nobody has truly adopted it, is confusing two distinct problems: the quality of the solution, and the way it was introduced. More often than not, the second explains the failure better than the first. Nobody took part in building the decision.</p><p>The trap is that the signals that would let you course-correct are systematically misread:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*MQzOCN0rbo0XpayOz718gQ.png" /></figure><p>The last row is the most counter-intuitive: a team scrupulously applying rules it doesn’t believe in looks exactly like a convinced team. The difference only shows the day an unforeseen case calls for initiative, and there is none.</p><h3>Involving people doesn’t mean deciding by consensus</h3><p>An important nuance: involving developers doesn’t mean putting every decision to a vote. A lead sometimes has to make the call. There are business constraints, deadlines, decisions that come from outside the team, and not everyone can win every time.</p><p>But there is a chasm between “I disagree with you” and “I don’t care what you think”. The first sentence leaves the relationship intact: you can be heard, contradicted, and still get behind the decision. The second destroys involvement, one decision at a time. A developer can accept a decision they disagree with; what they cannot accept for long is that their point of view doesn’t count. Listening doesn’t weaken the decision; if anything, it makes it easier to accept.</p><h3>Convincing builds autonomy, imposing builds dependency</h3><p>Imposing is fast; convincing takes time. That’s exactly what makes imposing so tempting. You save weeks now; you pay them back a hundred times over later.</p><p>A developer who only knows the rule will apply the rule. “Dependencies point inward”: fine, they’ll make dependencies point inward. But the first time reality serves up a case the rule didn’t anticipate (the legacy batch job that writes straight to the database, the library that would require a very odd adapter), they’ll be back at your desk: “What do I do here?” A developer who understood why the rule exists (protecting the business core from infrastructure details) can decide on their own, even in cases nobody foresaw. A lead who imposed the rule becomes the bottleneck of their own architecture.</p><h3>The old architecture changes. The experience stays.</h3><p>When a new approach arrives, everything in the messaging implies the existing system was bad. Otherwise, why change? It’s rarely that simple. Yesterday’s choices were made with yesterday’s information and constraints; what looks absurd today probably had a reason back then.</p><p>Above all, years spent on an application produce a kind of knowledge no documentation can replace: the historical constraints, the trade-offs, the places you don’t touch without a safety net. That knowledge doesn’t depreciate because the architecture changes. Quite the opposite: migrating a legacy system without the people who know where the traps are buried is walking through a minefield with a blank map. Your skeptic from the first workshop is not the obstacle to the migration. They are its terrain expert.</p><h3>Give the team ownership of the change</h3><p>A change only lasts if the team builds it instead of just going along with it. If I had to keep a few principles for supporting that kind of change, it would be these:</p><ul><li><strong>Decide upstream, not in code review.</strong> Structural choices are made in workshops, recorded in ADRs (Architecture Decision Records), tried out in pair programming, not in pull request comments, when the code is already written and every remark lands as a rebuke.</li><li><strong>Explain as many times as it takes.</strong> Present concepts to the group, follow up one-on-one with whoever needs it, redo the diagrams and the analogies until they stick. Never answer “it’s simple”: if it were simple for the person in front of you, they wouldn’t have asked.</li><li><strong>Protect the right not to understand.</strong> People must be able to say “I don’t get it” without fearing they’ll be seen as incompetent. Otherwise they will pretend, and pretending is far worse than not understanding.</li><li><strong>Move in small increments.</strong> Don’t disappear into a six-month refactoring project: the architecture is there to help you ship, not the other way around. Every iteration is a chance to adjust, to be wrong, to learn. Failed experiments aren’t accidents of the process: they are the process.</li></ul><p>And if buy-in still doesn’t come, change your question. “Why don’t they want to change?” looks for a culprit. “What’s keeping them from feeling safe enough to change?” looks for a cause. Maybe they didn’t understand; maybe they weren’t involved; maybe they’re afraid of getting it wrong. Or maybe they have already lived through three big changes that never went anywhere. In that last case, their skepticism isn’t a mindset problem. It’s experience.</p><p>And the human side is only part of the equation. A convinced team can still fail: available time, the organization, management, delivery pressure can all derail a transformation just as surely as missing buy-in. But those are topics for another article.</p><p>No architecture will keep compensating for a team where trust has broken down. <strong>Technical change rarely starts with the technology: it starts with the people who will have to carry it.</strong> And maybe the most important part of a lead’s job isn’t knowing where to take the team — it’s making the team want to go there with you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=467722d9e603" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Testing: The Mental Toolbox (2/2) — A Testing Strategy]]></title>
            <link>https://medium.com/@aboukri/unit-testing-the-mental-toolbox-2-2-a-testing-strategy-8d4e754133da?source=rss-4965f8ce1051------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d4e754133da</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ahmed Boukri]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 23:37:34 GMT</pubDate>
            <atom:updated>2026-07-10T23:37:34.317Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Where to invest your testing effort, the architecture that makes it possible, the right testing proportions, and when to write tests: everything that makes a test suite pay off.</em></p><p>Part 1 laid the foundations: entry and exit points, the “one test per exit point” rule, stable versus volatile dependencies, and the five families of test doubles. This second part zooms out. Now that you know how to <em>write</em> a good unit test, which ones are worth writing, and which ones are better left unwritten?</p><p><em>→ Part 1: writing good tests — exit points and test doubles. (</em><a href="https://medium.com/@ahmed_boukri/unit-testing-the-mental-toolbox-1-2-writing-good-tests-90d220a11018?sharedUserId=ahmed_boukri"><em>Part 1</em></a><em>)</em></p><h4>Not all code deserves a test</h4><p>This grid is now a classic of the testing literature: rate every piece of code on two axes: its <strong>complexity</strong> (logic, calculations, branching) and its <strong>number of collaborators</strong> (database, external services, orchestration). Crossing the two gives four profiles, each with its own strategy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rLBA0haQALq0CRsq8Hc8aQ.png" /></figure><p>Two practical takeaways. First, stop testing getters and trivial mappings: it’s noise. Second, and this is the big one, the “rich logic + many collaborators” quadrant is a design smell, not a testing challenge: <strong>split it apart</strong>, extracting the logic on one side and the orchestration on the other. The answer isn’t better tests, it’s better design.</p><h4>Architecture is your first testability tool</h4><p>That split is exactly what layered architectures do for you at application scale. From the classic three layers (presentation, business, data) to the four-layer variant that separates use cases (<em>application services</em>) from business entities (<em>domain</em>), all the way to the onion architecture: they all chase the same goal: dependencies pointing inward, and <strong>a business core that knows nothing about the outside world</strong>.</p><p>The reward is immediate: a domain with no volatile dependency can be unit-tested with no double and no setup. If you struggle to test your business logic without mocking half the application, you don’t have a testing problem, you have an architecture problem.</p><h4>The pyramid, and a realistic test budget</h4><p>The test pyramid remains the best compass for distribution: <strong>a wide base of unit tests (~80%), a middle layer of integration tests (~15%), a small top of end-to-end tests (~5%)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rCI3F0DYbx5Eaw6L7EwYIA.png" /></figure><p>Each level has a precise job:</p><ul><li><strong>business logic</strong> → unit tests;</li><li><strong>infrastructure</strong> (SQL queries, HTTP calls, files) → integration tests;</li><li><strong>wiring it all together</strong> → a few e2e tests that check everything is plugged in correctly, not tests that re-verify every business rule.</li></ul><h4>What about 100% coverage?</h4><p>Aim for it, the way you aim for the horizon: a useful direction, never a requirement. Some things just aren’t worth specifying. How would you test a function that returns the current time? The assertion would have to recompute the time itself, a test that merely repeats the implementation proves nothing. Same dead end for a UUID or random-value generator: the output can’t be predicted, so there’s nothing to assert. The coverage number is a thermometer, not a target: 100% coverage with hollow assertions is worth less than 75% of tests that actually verify something.</p><h4>When should you write the tests?</h4><p>Four strategies, from the latest to the most radical:</p><ul><li><strong>Test-Last</strong>:<strong> </strong>writing tests after the code. It’s the path of least resistance and you pay for it in cash: since the code wasn’t designed to be testable, the tests are painful to write. That said, on <strong>legacy code</strong> it’s often the only option — you secure what exists before touching it.</li><li><strong>Test-First</strong>:<strong> </strong>writing the test before the code, turning expectations into an executable specification. It’s the natural approach for <strong>acceptance tests</strong>: describe the expected behavior of a user story, then develop until green.</li><li><strong>TDD</strong> — the <strong>Red / Green / Refactor</strong> cycle: a failing assertion, the minimal code that makes it pass, a cleanup at constant coverage. The benefit goes far beyond the safety net: the “testable first” constraint <strong>drives the design</strong> — small units, explicit dependencies, low coupling.</li><li><strong>TCR</strong> (<em>test &amp;&amp; commit || revert</em>): the extreme variant: tests green, you commit; tests red, everything is reverted. Brutal, but unbeatable for learning to move in <strong>micro-increments</strong>, especially while refactoring.</li></ul><h4>Organizing your test files: three patterns</h4><p>One last structural choice, too often left to chance:</p><ul><li><strong>one test file per production class</strong>:<strong> </strong>the one-to-one technical mirror; natural for algorithmic code and unit tests;</li><li><strong>one test file per feature: </strong>BookingCreation, BookingCancellation…; the test documents the specification, not the structure; ideal for test-first and acceptance tests;</li><li><strong>one test file per fixture</strong>:<strong> </strong>one per starting data set (“3-day rental”, “10-day rental” : different pricing rules apply), with every scenario declined within that context; precious when behavior depends heavily on the initial data.</li></ul><p>The first pattern follows the code; the other two follow the behavior. Over time, the behavior-driven ones age better: you can restructure the code without reorganizing the tests.</p><p>Tests are not a tax you pay at the end of the sprint. Done right, they are the executable specification of your software.</p><p>Good tests are not there to prove your code works today. <strong>They’re there to let you change it safely tomorrow.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d4e754133da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Testing: The Mental Toolbox (1/2) — Writing Good Tests]]></title>
            <link>https://medium.com/@aboukri/unit-testing-the-mental-toolbox-1-2-writing-good-tests-90d220a11018?source=rss-4965f8ce1051------2</link>
            <guid isPermaLink="false">https://medium.com/p/90d220a11018</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[software-testing]]></category>
            <dc:creator><![CDATA[Ahmed Boukri]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 23:29:52 GMT</pubDate>
            <atom:updated>2026-10-26T22:48:59.711Z</atom:updated>
            <content:encoded><![CDATA[<p><em>One test per exit point, five families of test doubles, a pyramid — and a handful of simple rules for writing tests that help you instead of slowing you down.</em></p><p>Most developers don’t hate unit tests because of the syntax or the tooling. They hate them because brittle tests create more fear than confidence: a few get written to ease the conscience, they slowly turn slow and flaky, they break on every refactoring, and eventually someone marks them skip, &quot;just for now&quot;.</p><p>The problem is rarely the framework. It’s almost always <strong>conceptual</strong>: tests written without ever asking what exactly is being tested, through which observable point, and what should stand in for the parts that get in the way.</p><p>This article gathers the handful of concepts that, put together, change the game. Nothing here is new: it all comes from the classic literature (Kent Beck, Gerard Meszaros, Roy Osherove, Martin Fowler, Vladimir Khorikov), filtered through practice.</p><h4>Before writing a test, know what a good one looks like</h4><p>Let’s start from the end. A good unit test has a few non-negotiable properties.</p><p>It’s <strong>fast: </strong>we’re talking milliseconds, not seconds. It’s <strong>deterministic</strong>: same code, same result, whether it runs on your machine on a Monday morning or in CI on a Friday night. It runs <strong>entirely in memory</strong>: no network, no disk, no database. It’s <strong>independent of every other test</strong>, so it can run in parallel without any special setup. And above all, it reads like a sentence: someone opening the file for the first time should understand the intent without ever without opening the production code.</p><p>If a test doesn’t tick these boxes, it isn’t necessarily a bad test, but it isn’t a <em>unit</em> test, and it shouldn’t live (or run) in the same place.</p><h4>The anatomy: Arrange, Act, Assert</h4><p>The AAA pattern (formalized by Bill Wake) structures every test in three parts:</p><ul><li><strong>Arrange</strong>: set up the context (optional when the scenario doesn’t need any)</li><li><strong>Act</strong>: invoke the entry point of the code under test <strong>(one single invocation per test)</strong></li><li><strong>Assert</strong>: check the outcome.</li></ul><p>The classic trap hides in the <em>Assert</em>: nothing forbids multiple assertions, as long as they all verify <strong>the same thing</strong>. Three expect calls inspecting different facets of one returned object? Perfectly fine. Three expect calls checking three different effects of the function? That&#39;s a sign some tests are missing, which is exactly what the next section is about.</p><h4>The concept that changes everything: exit points</h4><p>It’s arguably the most structuring concept in unit testing, and the least taught. Any unit of work like this: <strong>a single entry point </strong>(the function call) and <strong>one or more exit points</strong>, meaning everything the execution leaves behind that can be observed.</p><p>There are three kinds:</p><ol><li><strong>the return value</strong> (direct output);</li><li><strong>an observable state change</strong> (indirect output) — a modified property, an item added to a collection;</li><li><strong>a call to an external dependency</strong> (behavioral output) — the kind you verify with doubles.</li></ol><p>Look at this function:</p><pre>function confirmBooking(id: string): string {<br>  const booking = bookingRepository.findById(id);<br><br>  booking.confirm();<br>  bookingRepository.save(booking);<br>  smsGateway.notify(booking.customerPhone);<br><br>  return booking.reference;<br>}</pre><p>One entry point, but <strong>three exit points</strong>: the returned reference, the save to the database, and the SMS being sent. Three things that can break independently. Hence the rule:</p><blockquote><strong><em>Write one test per exit point.</em></strong></blockquote><p>Each test verifies a single thing; when it turns red, the diagnosis is instant: no need to figure out which of five expect calls failed, or why. And this granularity fits hand in glove with TDD, where every red assertion calls for one small increment of code.</p><p>On a minimal example, direct and indirect outputs therefore give two tests:</p><pre>class Playlist {<br>  public tracks: string[] = [];<br><br>  add(track: string): number {<br>    this.tracks.push(track);<br>    return this.tracks.length;<br>  }<br>}<br><br>test(&#39;add() returns the new number of tracks (direct output)&#39;, () =&gt; {<br>  const playlist = new Playlist();<br>  expect(playlist.add(&#39;Blue in Green&#39;)).toBe(1);<br>});<br><br>test(&#39;add() stores the track in the playlist (indirect output)&#39;, () =&gt; {<br>  const playlist = new Playlist();<br>  playlist.add(&#39;Blue in Green&#39;);<br>  expect(playlist.tracks).toEqual([&#39;Blue in Green&#39;]);<br>});</pre><p>One last point, and not the least: the three kinds of outputs are not equally desirable.</p><blockquote><strong><em>Favor return values.</em></strong></blockquote><p>Accept state changes (they’re in the nature of objects, especially when you separate commands from queries), and <strong>be wary of interaction checks</strong>: they’re what welds your tests to the implementation.</p><h4>Unit or integration? Follow the dependencies</h4><p>The boundary between a unit test and an integration test isn’t “one class versus several”. It runs along the nature of the dependencies of the code under test.</p><p>A dependency is <strong>stable</strong> when it’s always available, needs no setup or teardown, and responds instantly: a utility function, a data structure, a domain class. A dependency is <strong>volatile</strong> when it requires a prerequisite (an initialized database, a running service), when it’s non-deterministic (the clock, an ID generator), or simply slow.</p><p>The decision rule then fits in one sentence: <strong>code that relies only on stable dependencies gets unit tests; as soon as a volatile dependency enters the picture, you’re writing an integration test</strong>, with its setup, its teardown, its grouped assertions (every run is expensive) and its sequential execution.</p><p>Or… you replace the volatile dependency with a double, and you stay on unit-test ground. That’s exactly what <em>test doubles</em> are for.</p><h4>Test doubles: five tools, not one universal hammer</h4><p>This taxonomy is a classic of the testing literature. Five families, from the dumbest to the smartest, with one warning up front: the wrong double makes a test more complicated, not less.</p><p><strong>Dummy: the filler object</strong></p><p>Provided only because a method or constructor signature demands an argument. The tested scenario never uses it: its behavior is irrelevant, and whatever its methods return (if anything) is never read.</p><pre>interface SeasonRate {<br>  multiplier(): number;<br>}<br><br>class NullSeasonRate implements SeasonRate {<br>  multiplier() {<br>    return 0;<br>  }<br>}<br><br>function quoteRental(dailyPrice: number, days: number, season: SeasonRate): number {<br>  let total = dailyPrice * days;<br><br>  if (days &gt;= 7) {<br>    total *= season.multiplier();<br>  }<br><br>  return total;<br>}<br><br>test(&#39;a short stay is billed at the standard rate&#39;, () =&gt; {<br>  expect(quoteRental(40, 3, new NullSeasonRate())).toBe(120);<br>});</pre><p>A three-day rental: the seasonal rate will never be consulted, but you still have to pass something in.</p><p><strong>Stub: the scripted answer</strong></p><p>A stub answers with the values the test decided in advance: you control the data the code under test consumes, in order to reproduce one precise scenario. The test then verifies nothing but the observable result.</p><pre>class FixedSeasonRate implements SeasonRate {<br>  constructor(private readonly value: number) {}<br><br>  multiplier() {<br>    return this.value;<br>  }<br>}<br><br>test(&#39;a week-long stay gets the seasonal rate applied&#39;, () =&gt; {<br>  expect(quoteRental(40, 10, new FixedSeasonRate(0.8))).toBe(320);<br>})</pre><p>10 days of rental: the seasonal branch runs, and since the stub answers 0.8, the outcome is fully predictable: 40 × 10 = 400, then 400 × 0.8 = 320.</p><p><strong>Spy: the witness</strong></p><p>A spy records the interactions it receives (arguments, number and order of calls) so they can be inspected after execution. It’s how you test a behavioral output; in return, the test becomes coupled to the way the code interacts with its dependency.</p><pre>interface SearchEngine {<br>  query(term: string): string[];<br>}<br><br>class SpySearchEngine implements SearchEngine {<br>  public queries: string[] = [];<br><br>  constructor(private readonly results: string[] = []) {}<br><br>  query(term: string) {<br>    this.queries.push(term);<br>    return this.results;<br>  }<br>}<br><br>function searchArticles(term: string, engine: SearchEngine): string[] {<br>  const normalized = term.trim().toLowerCase();<br>  return engine.query(normalized);<br>}</pre><p>Here, searchArticles has two exit points: the results it returns, and the query it hands to the engine. The rule from earlier applies, two tests:</p><pre>test(&#39;returns the results provided by the engine&#39;, () =&gt; {<br>  const engine = new SpySearchEngine([&#39;Refactoring&#39;, &#39;Clean Code&#39;]);<br>  const results = searchArticles(&#39;  TypeScript  &#39;, engine);<br><br>  expect(results).toEqual([&#39;Refactoring&#39;, &#39;Clean Code&#39;]);<br>});<br><br>test(&#39;normalizes the term before passing it to the engine&#39;, () =&gt; {<br>  const engine = new SpySearchEngine();<br>  searchArticles(&#39;  TypeScript  &#39;, engine);<br><br>  expect(engine.queries).toEqual([&#39;typescript&#39;]);<br>});</pre><p>When one of the two breaks, you know exactly which behavior regressed.</p><p>You may have noticed: by answering with a configured value, this spy also plays the stub’s role. That’s fine: the five families describe <strong>roles played in a test</strong>, not mutually exclusive kinds of classes; a single object can hold several at once.</p><p><strong>Mock: the spy with expectations</strong></p><p>A mock is configured <strong>before</strong> execution: you tell it how to respond and how it is expected to be used. Instead of letting the test inspect the interactions after the fact, the mock verifies those expectations on your behalf. The example reuses the searchArticles function introduced with the spy.</p><pre>class MockSearchEngine implements SearchEngine {<br>  private results: string[] = [];<br>  private expectedTerm?: string;<br><br>  willReturn(results: string[]) {<br>    this.results = results;<br>  }<br><br>  expectTerm(term: string) {<br>    this.expectedTerm = term;<br>  }<br><br>  query(term: string) {<br>    if (this.expectedTerm !== undefined &amp;&amp; term !== this.expectedTerm) {<br>      throw new Error(`unexpected term: ${term}`);<br>    }<br>    return this.results;<br>  }<br>}<br><br>test(&#39;queries the engine with the right term and relays its answer&#39;, () =&gt; {<br>  const engine = new MockSearchEngine();<br>  engine.expectTerm(&#39;tdd&#39;);<br>  engine.willReturn([&#39;TDD Guide&#39;, &#39;Clean Code&#39;]);<br><br>  const results = searchArticles(&#39;  TDD &#39;, engine);<br>  expect(results).toEqual([&#39;TDD Guide&#39;, &#39;Clean Code&#39;]);<br>});</pre><p>An unexpected term makes the test fail because the mock <strong>enforces the expectations declared before execution</strong>. With a spy, the test asks “what happened?” after the fact; with a mock, the expectations are part of the test double itself: it verifies them for you.</p><p><strong>Fake: the real implementation, only simpler</strong></p><p>The fake is the odd one out: unlike the other doubles, it’s a <strong>lightweight but functional implementation</strong> of the contract: real behavior, rather than preprogrammed responses. The canonical example is the in-memory repository standing in for the database.</p><pre>class InMemorySearchEngine implements SearchEngine {<br>  constructor(private readonly documents: string[]) {}<br><br>  query(term: string) {<br>    return this.documents.filter((doc) =&gt; doc.toLowerCase().includes(term));<br>  }<br>}<br><br>test(&#39;finds the documents matching the search term&#39;, () =&gt; {<br>  const engine = new InMemorySearchEngine([&#39;TDD Guide&#39;, &#39;Clean Code&#39;, &#39;Refactoring&#39;]);<br><br>  const results = searchArticles(&#39;  Clean &#39;, engine);<br>  expect(results).toEqual([&#39;Clean Code&#39;]);<br>});</pre><p>Unlike a stub that would answer [&#39;Clean Code&#39;] hardcoded, the fake actually <strong>computes</strong> its result: it filters its documents the way the real engine would. No scenario-specific logic: the same implementation can be reused by every test in the suite, each with its own data.</p><h4>Which one should you pick?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pwU6nHCskDMFujXLZ-4CcA.png" /></figure><p>A good rule of thumb: <strong>introduce a test double only when a volatile dependency forces you to, and prefer fakes whenever you can.</strong></p><p>Assertions on mocks should be a last resort: each one is another thread tying the test to the code’s internal structure. Tests that are too tightly coupled to the implementation tend to fail after every refactoring, even when the observable behavior hasn’t changed — and those false positives are the slow poison of a test suite: cry wolf often enough, and people stop listening.</p><blockquote><strong><em>Fakes test contracts; mocks test implementation details.</em></strong></blockquote><p>You now know what a good unit test looks like, how to structure it, which output to verify, and which double to reach for when a volatile dependency gets in the way. That leaves the strategic question: which tests should you write, where should the effort go, in what proportions, and when? That’s what part 2 is about.</p><p><em>→ Part 2: a testing strategy (where to invest, architecture, the pyramid, TDD). </em><a href="https://medium.com/@ahmed_boukri/unit-testing-the-mental-toolbox-2-2-a-testing-strategy-8d4e754133da"><em>Part 2</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90d220a11018" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NestJS: The Invisible Trap Between TypeScript, CommonJS, and ESM]]></title>
            <link>https://medium.com/@aboukri/nestjs-the-invisible-trap-between-typescript-commonjs-and-esm-57ae21995e3b?source=rss-4965f8ce1051------2</link>
            <guid isPermaLink="false">https://medium.com/p/57ae21995e3b</guid>
            <category><![CDATA[commonjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[esm]]></category>
            <dc:creator><![CDATA[Ahmed Boukri]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 16:22:40 GMT</pubDate>
            <atom:updated>2026-06-16T16:22:40.155Z</atom:updated>
            <content:encoded><![CDATA[<p>When starting a new NestJS project, we usually think about:</p><ul><li>architecture</li><li>design patterns</li><li>domain boundaries</li><li>tooling</li><li>databases</li><li>ORMs</li></ul><p>And when applying Hexagonal Architecture or DDD, we already know that some infrastructure choices can evolve later.</p><p>But there’s another decision, far more fundamental, that happens very early in the project:</p><p>👉 the module system used by the application.</p><p>In the Node.js ecosystem, this choice usually comes down to:</p><ul><li>CommonJS (CJS)</li><li>ESM (ECMAScript Modules)</li></ul><p>And contrary to what many developers think, this is not just a syntax difference.</p><p>You write this:</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;</pre><p>So you naturally assume: <em>“My NestJS application is already using ESM.”</em></p><p>But in many projects, that’s simply not true.</p><p>Under the hood, TypeScript may still compile everything into CommonJS:</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;module&quot;: &quot;commonjs&quot;<br>  }<br>}</pre><p>Meaning:</p><ul><li>your code looks modern</li><li>your IDE behaves as if you’re using ESM</li><li>but Node.js still executes the application as CommonJS</li></ul><p>And that invisible mismatch becomes increasingly important as the Node.js ecosystem moves toward native ESM.</p><h4><strong>What CommonJS and ESM actually change</strong></h4><p>CommonJS and ESM are not just two different syntaxes.</p><p>They define:</p><ul><li>how modules are loaded</li><li>how dependencies are resolved</li><li>how the runtime behaves</li><li>how tooling analyzes your application</li></ul><h4>CommonJS: Dynamic and Synchronous Loading</h4><p>CommonJS is the historical module system of Node.js.</p><pre>const math = require(&#39;./math&#39;);</pre><p>When Node.js encounters this code:</p><ol><li>it loads the requested file</li><li>immediately executes the module</li><li>retrieves module.exports</li><li>caches the result</li></ol><p>The loading process is therefore:</p><ul><li>dynamic</li><li>synchronous</li><li>executed on demand</li></ul><p>In practice, CommonJS works like:</p><p>“I load the module when I need it.”</p><p>For years, this model worked perfectly well for the Node.js ecosystem.</p><h4>ESM: Static Analysis Before Execution</h4><p>With ESM:</p><pre>import { sum } from &#39;./math.js&#39;;</pre><p>Node.js follows a different approach:</p><ol><li>it analyzes all imports before execution</li><li>builds a dependency graph</li><li>links modules together</li><li>then executes the application</li></ol><p>This enables:</p><ul><li>stronger static analysis</li><li>more predictable resolution</li><li>better tooling integration</li><li>more advanced optimizations</li></ul><p>ESM works more like:</p><p>“I know the entire structure of the application before it starts.”</p><h4>CommonJS vs ESM in Practice</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*BiyrhgYfRfyrYqrlRHVIYw.png" /></figure><h3>Why the Ecosystem Is Moving Toward ESM</h3><p>The transition to ESM is not just about syntax modernization.</p><p>It solves several historical limitations of CommonJS.</p><h4>1. Better Alignment With Modern Tooling</h4><p>Modern runtimes and tools increasingly assume ESM:</p><ul><li>Vite</li><li>Bun</li><li>Deno</li><li>Astro</li><li>modern bundlers</li><li>newer Node.js packages</li></ul><p>are increasingly built around ESM.</p><p>Some libraries are now even published as: <em>ESM-only</em></p><p>meaning they no longer provide a CommonJS build.</p><h4>2. Better Optimization Capabilities</h4><p>Because ESM imports are static, tools can:</p><ul><li>analyze dependencies precisely</li><li>optimize bundling</li><li>remove unused code (tree-shaking)</li></ul><p>Tree-shaking is especially relevant in:</p><ul><li>frontend applications</li><li>monorepos</li><li>serverless deployments</li><li>edge runtimes</li><li>bundled architectures</li></ul><p>In traditional non-bundled NestJS backends, the impact is usually less significant.</p><h4>3. A More Unified Frontend/Backend Model</h4><p>Modern frontend ecosystems already rely heavily on ESM:</p><ul><li>React</li><li>Vue</li><li>Vite</li><li>Astro</li></ul><p>Using ESM on the backend also creates:</p><ul><li>more consistent conventions</li><li>less cognitive switching</li><li>a shared module model across environments</li></ul><h3>The Illusion of Already Being “Modern”</h3><p>This is one of the most misleading aspects of the TypeScript ecosystem.</p><p>Many developers think:</p><p>“I use import, therefore my project already uses ESM.”</p><p>But TypeScript can easily transform this code:</p><pre>import { UserService } from &#39;./user.service&#39;;</pre><p>into roughly this:</p><pre>const user_service_1 = require(&#39;./user.service&#39;);</pre><p>The syntax in your source code does not guarantee the actual runtime behavior. And many teams only discover this:</p><ul><li>during an ESM migration</li><li>when introducing an ESM-only dependency</li><li>or when Node.js becomes stricter about module resolution</li></ul><h3>The Evolution From MikroORM v6 to v7</h3><p>MikroORM is a good example of how the Node.js ecosystem is progressively moving toward patterns that align better with ESM runtimes.</p><p>Between MikroORM v6 and v7, we can clearly see a shift toward:</p><ul><li>more explicit imports</li><li>stronger static analysis</li><li>reduced runtime discovery</li><li>more predictable module resolution</li></ul><h3>Typical Pattern Commonly Seen Around MikroORM v6</h3><p>Older projects often relied on filesystem discovery:</p><pre>import { MikroORM } from &#39;@mikro-orm/core&#39;;<br><br>const orm = await MikroORM.init({<br>  entities: [&#39;./dist/entities&#39;],<br>});</pre><p>This worked well in many CommonJS setups.</p><p>However, it relied heavily on:</p><ul><li>filesystem scanning</li><li>runtime discovery</li><li>implicit module resolution</li></ul><h3>More ESM-Oriented Patterns Around MikroORM v7</h3><p>Modern MikroORM configurations now tend to favor explicit imports:</p><pre>import { User } from &#39;./modules/users/user.entity.js&#39;;<br>import { Token } from &#39;./modules/auth/token.entity.js&#39;;<br><br>export default defineConfig({<br>  entities: [User, Token],<br>});</pre><p>This shift is directly driven by ESM.</p><p>The glob pattern:</p><pre>entities: [&#39;./dist/entities&#39;]</pre><p>relied heavily on CommonJS behavior:</p><ul><li>synchronous require()</li><li>filesystem scanning</li><li>__dirname-based runtime resolution</li></ul><p>In ESM, that model becomes much more fragile:</p><ul><li>imports are resolved statically before execution</li><li>there is no synchronous require()</li><li>__dirname no longer exists</li><li>.js extensions become mandatory</li></ul><p>Runtime filesystem discovery becomes significantly harder to reason about.</p><p>As a result, explicit imports:</p><pre>entities: [User, Token]</pre><p>are not simply a stylistic preference.</p><p>They are the natural consequence of how ESM resolves modules. And this is precisely where the module system starts influencing application architecture itself.</p><h3>Why Do Imports Use .js Extensions?</h3><p>This is often the most surprising detail.</p><p>Even inside TypeScript files, we write:</p><pre>import { User } from &#39;./user.entity.js&#39;;</pre><p>Why?</p><p>Because:</p><ul><li>TypeScript compiles the project into JavaScript</li><li>Node.js executes the compiled JavaScript files</li><li>and in ESM mode, Node.js requires real runtime extensions</li></ul><p>This rule feels stricter at first. But it also makes behavior much more predictable.</p><h3>Common Friction Points During an ESM Migration</h3><p>The syntax migration itself is usually not the difficult part.</p><p>The ecosystem around it is.</p><h4><strong>1. </strong><strong>__dirname and </strong><strong>__filename Disappear</strong></h4><p>In ESM:</p><pre>console.log(__dirname);</pre><p>produces:</p><pre>ReferenceError: __dirname is not defined in ES module scope<br>         at file: ...</pre><p>You must instead use:</p><pre>import { fileURLToPath } from &#39;node:url&#39;;<br>import path from &#39;node:path&#39;;<br><br>const __filename = fileURLToPath(import.meta.url);<br>const __dirname = path.dirname(__filename);</pre><h4>2. .js Extensions Become Mandatory</h4><p>In CommonJS:</p><pre>import { UserService } from &#39;./user.service&#39;;</pre><p>often works.</p><p>In ESM:</p><pre>import { UserService } from &#39;./user.service.js&#39;;</pre><p>becomes necessary.</p><h4>3. CommonJS ↔ ESM Interoperability</h4><p>Historically, mixing CommonJS and ESM often produced runtime errors such as:</p><pre> Error [ERR_REQUIRE_ESM]: require() of ES Module ...</pre><p>However, recent Node.js versions (Node 20.19+ and Node 22.12+) have significantly improved interoperability between CommonJS and ESM.</p><p>In many cases, require() can now load ESM modules directly.</p><p>That said, friction can still appear depending on:</p><ul><li>the Node.js version</li><li>the tooling stack</li><li>how dependencies are published</li><li>and whether multiple module systems coexist inside the same application</li></ul><h3>The Real Complexity of ESM in NestJS</h3><p>In practice, switching from:</p><pre>require()</pre><p>to:</p><pre>import / export</pre><p>is usually the easy part.</p><p>The real complexity often comes from the NestJS tooling ecosystem itself.</p><p>NestJS dependency injection relies heavily on emitDecoratorMetadata, which emits constructor parameter types (design:paramtypes) at compile time.</p><p>This is also one of the reasons why many NestJS projects still depend on the legacy TypeScript decorators ecosystem rather than the newer TC39 standard decorators, which currently do not fully cover parameter decorators or runtime type metadata in the same way.</p><p>This is also why interfaces cannot be injected directly in NestJS.</p><p>Interfaces do not exist at runtime, which means there is no design:paramtypes metadata available for the dependency injection container to inspect.</p><p>Instead, you must use an explicit injection token:</p><pre>@Inject(TOKEN)</pre><p>Once again, the explicit pattern turns out to be the more predictable and robust one.</p><p>Fast transpilers behave differently here.</p><p>esbuild, for example, does not emit decorator metadata — which silently breaks dependency injection.</p><p>SWC supports it, but has historically had its own inconsistencies compared to tsc.</p><p>This is exactly the kind of friction NestJS v12 aims to remove by making SWC and Vitest first-class defaults for ESM projects.</p><p>In real-world projects, migration challenges usually come from tooling rather than code:</p><ul><li>Jest’s ESM support (experimental and fragile)</li><li>ts-node ESM loaders</li><li>transpiler metadata (SWC / esbuild emitting design:paramtypes differently from tsc)</li><li>path aliases that resolve at compile time but not at runtime</li><li>deployment runtimes behaving differently from local dev</li></ul><p>This is one of the reasons why many production NestJS applications still remain on CommonJS today, despite the broader ecosystem shift toward ESM.</p><p>The syntax is rarely the difficult part. The ecosystem integration is.</p><h3>How to Migrate a NestJS Project to ESM</h3><p>The migration mainly involves two files:</p><ul><li>package.json</li><li>tsconfig.json</li></ul><h4>1. Update package.json</h4><p>Add:</p><pre>{<br>  &quot;type&quot;: &quot;module&quot;<br>}</pre><p>👉 This tells Node.js that the project uses ESM.</p><h4>2. Update tsconfig.json</h4><p>Configure TypeScript with:</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;target&quot;: &quot;ES2025&quot;,<br>    &quot;module&quot;: &quot;NodeNext&quot;,<br>    &quot;moduleResolution&quot;: &quot;NodeNext&quot;<br>  }<br>}</pre><h4>What Do These Options Mean?</h4><p><strong>target</strong></p><pre>{<br>  &quot;target&quot;: &quot;ES2025&quot;<br>}</pre><p>tells TypeScript:</p><p>“Which level of modern JavaScript should be generated.”</p><p><strong>module</strong></p><pre>{<br>  &quot;module&quot;: &quot;NodeNext&quot;<br>}</pre><p>tells TypeScript:</p><p>“Which module system should be used.”</p><p><strong>moduleResolution</strong></p><pre>{<br>  &quot;moduleResolution&quot;: &quot;NodeNext&quot;<br>}</pre><p>tells TypeScript:</p><p>“How imports should be resolved according to modern Node.js rules.”</p><p>Why<strong> NodeNext </strong>Matters</p><p>Many examples still use:</p><pre>{<br>  &quot;module&quot;: &quot;ESNext&quot;<br>}</pre><p>But in a NestJS application executed directly by Node.js, NodeNext is usually more coherent.</p><p>Why?</p><p>Because it follows the actual Node.js runtime behavior:</p><ul><li>native ESM resolution</li><li>.js extensions</li><li>CommonJS / ESM interoperability</li><li>runtime-accurate module handling</li></ul><p>In other words:</p><ul><li>ESNext generates modern JavaScript</li><li>NodeNext generates modern JavaScript compatible with the real Node.js runtime</li></ul><p>And this distinction becomes increasingly important as projects grow.</p><h3>What NestJS v12 Changes</h3><p>This direction is no longer hypothetical.</p><p>NestJS v12 (major release planned around Q3 2026) introduces:</p><ul><li>native ESM support</li><li>Vitest + SWC as defaults for ESM projects</li><li>Standard Schema validation in route decorators (Zod, Valibot, ArkType…)</li></ul><p>This matters because v12 directly targets the exact friction described above:</p><ul><li>the painful Jest ESM setup is replaced by Vitest, which is ESM-native</li><li>the SWC metadata inconsistencies are absorbed by making SWC a standardized, first-class part of the toolchain</li></ul><p>In other words, the ecosystem isn’t just drifting toward ESM — NestJS is actively building ESM into its core.</p><h3>Should You Migrate Right Now?</h3><p>That depends mostly on your project context.</p><p>Migrating to ESM makes sense if:</p><ul><li>you’re starting a new service rather than migrating an existing on</li><li>a dependency you need is now published as ESM-only</li><li>your toolchain is already modern (SWC, Vitest, recent Node.js)</li><li>the team wants to reduce future technical debt before the ecosystem forces the move</li></ul><p>On the other hand, staying on CommonJS is the reasonable choice if:</p><ul><li>the application is stable and rarely touched</li><li>your test suite relies heavily on Jest’s CommonJS setup</li><li>you still depend on packages that ship CommonJS only</li><li>the migration cost outweighs any concrete benefit today</li></ul><p>A stable legacy project can keep running perfectly well on CommonJS.</p><p>The important part is not blindly following trends. It is</p><p>👉 understanding how your runtime actually behaves.</p><h3><strong>Conclusion</strong></h3><p>For years, CommonJS was the invisible default of the Node.js ecosystem.</p><p>Today, ESM is progressively becoming the new standard, and NestJS v12 confirms that this transition is no longer theoretical: the framework itself is evolving toward an ESM-native ecosystem, with SWC, Vitest, and modern runtime tooling integrated into its core direction.</p><p>But in NestJS, the real challenge was never replacing:</p><pre>require()</pre><p>with:</p><pre>import</pre><p>👉 It’s making the runtime, the tooling, and the framework ecosystem behave consistently once the module system changes.</p><p>The module system is no longer just a Node.js detail.<br>It increasingly shapes the architecture and behavior of the entire application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57ae21995e3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>