<?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 Jakub Radzik on Medium]]></title>
        <description><![CDATA[Stories by Jakub Radzik on Medium]]></description>
        <link>https://medium.com/@jradzik4?source=rss-fe30da5ee536------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*x_dF6fnswvUlf10M6dt4yQ.jpeg</url>
            <title>Stories by Jakub Radzik on Medium</title>
            <link>https://medium.com/@jradzik4?source=rss-fe30da5ee536------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 10:56:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jradzik4/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[How We Backfilled 21 Million DynamoDB Records Without Scans or Prod Downtime]]></title>
            <link>https://medium.com/@jradzik4/how-we-backfilled-21-million-dynamodb-records-without-scans-or-prod-downtime-2ef667429610?source=rss-fe30da5ee536------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ef667429610</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[system-engineering]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Jakub Radzik]]></dc:creator>
            <pubDate>Fri, 25 Sep 2026 08:05:35 GMT</pubDate>
            <atom:updated>2026-09-25T08:05:35.314Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G4haYckbRCXhGYNu" /><figcaption>Photo by <a href="https://unsplash.com/@jankolar?utm_source=medium&amp;utm_medium=referral">Jan Antonin Kolar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Upgrading production database schemas at scale is a rite of passage for every backend engineer. Recently, our team faced a classic challenge: we needed to add and populate a new status field on every single row in a primary DynamoDB table.</p><p>While a simple AWS Lambda function took care of newly ingested records, we still had to update <strong>21 million historical records</strong> across a massive <strong>700 GB table</strong>.</p><p>The naive approach — running a full table Scan and executing updates inline—was off the table immediately. Scans are notoriously expensive, consume massive amounts of Read Capacity Units (RCUs), risk throttling production traffic, and take forever to run at scale.</p><p>Here is how we architected a zero-impact, resilient migration pipeline that processed 700 GB of data in minutes, along with the hard partition lessons we learned along the way.</p><h3>The Migration Architecture</h3><p>Instead of hitting the live DynamoDB API to read 21 million items, we decoupled our read path completely from production using native AWS features and a localized file-processing pipeline.</p><pre>+-------------------+      PITR Export      +-------------------+<br>|  DynamoDB Table   | --------------------&gt; |   AWS S3 Bucket   |<br>| (700GB / 21M rec) |                       | (.json.gz files)  |<br>+-------------------+                       +-------------------+<br>                                                      |<br>                                                      | PM2 + Node.js<br>                                                      v<br>                                            +-------------------+<br>                                            |  1,000 CSV Files  |<br>                                            |   (id, status)    |<br>                                            +-------------------+<br>                                                      |<br>                                                      | Round-Robin Parallel Writer<br>                                                      v<br>                                            +-------------------+<br>                                            |  DynamoDB Table   |<br>                                            |  (Updated Rows)   |<br>                                            +-------------------+</pre><h3>Step 1: Zero-Impact Data Extraction via PITR</h3><p>We triggered an export of our DynamoDB table to Amazon S3 using <strong>Point-in-Time Recovery (PITR)</strong>.</p><p>Because PITR reads directly from continuous backups rather than querying the live database instance, it incurred zero RCU cost and created zero load on our production table. The export yielded a collection of partitioned, compressed .json.gz files containing our entire dataset.</p><h3>Step 2: High-Speed S3 Processing with Node.js and PM2</h3><p>Next, we needed to transform these raw export files into lightweight key-value pairs (id, status).</p><p>We wrote a Node.js transformation script managed by <strong>PM2</strong> to process the .json.gz files in parallel across all available CPU cores.</p><ul><li><strong>Trial Run Safeguard:</strong> We included a dry-run mode that processed a single file first to validate schema changes and outputs before running full scale.</li><li><strong>Checkpointing Resilience:</strong> The transformation outputs were saved into approximately 1,000 discrete CSV files. Processing file-by-file gave us native fault tolerance: if the script crashed or an instance died, we didn’t have to restart from scratch — we simply resumed from the unverified CSV files.</li></ul><p><strong>The result:</strong> All 700 GB of data (21 million items) was transformed into localized CSV files in roughly <strong>10 minutes</strong>.</p><h3>The Bottleneck: The “Hot Partition” Trap</h3><p>With 1,000 ready-to-write CSV files in S3, we built a writer script to stream updates back into DynamoDB. However, our initial runs hit an immediate wall: <strong>throughput stalled at a dismal 30 rows per second.</strong></p><p>Investigating the writes revealed a classic DynamoDB physical architecture problem: <strong>Hot Partitions</strong>.</p><p>When AWS exports a table to S3, it writes contiguous partition keys into the same output files. Because our initial writer script processed one CSV file at a time sequentially, it flooded the same underlying physical DynamoDB partition with rapid updates while leaving the rest of the table’s allocated throughput completely idle. The partition choked, resulting in constant ProvisionedThroughputExceededException errors.</p><h3>The Fix: Round-Robin Partition Spreading</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uOAa3YOByySxAaYG" /><figcaption>Photo by <a href="https://unsplash.com/@joa70?utm_source=medium&amp;utm_medium=referral">Joachim Schnürle</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>To bypass partition-level throttling, we refactored the writer script to execute a <strong>Round-Robin</strong> strategy across multiple CSV files simultaneously:</p><p>Instead of consuming File_A.csv sequentially, the script opened a pool of CSV files (e.g., File_A.csv, File_B.csv, File_C.csv) concurrently. By cycling through writes from different files, the partition keys in each batch were broadly distributed across distinct physical partitions, allowing us to instantly break through the 30 rows/sec bottleneck.</p><h3>Script Configuration &amp; Tuning</h3><p>Below is the execution command we used for the writer script (ddb-write-s3-local-v3.js), engineered with aggressive adaptive scaling and hard protection limits:</p><pre>FILE_COUNT=3 \<br>MAX_ROWS_PER_SECOND=120 \ <br>WCU_START=3000 \<br>WCU_MIN=300 \<br>WCU_MAX=10000 \<br>WCU_RAMP_FACTOR=1.2 \ <br>WCU_RAMP_INTERVAL_MS=2500 \ <br>WCU_BACKOFF_FACTOR=0.9 \<br>THROTTLE_PAUSE_MS=100 RETRIES=8 \<br>TABLE_NAME=x BUCKET=y \<br>AWS_REGION=eu-west-1 \<br>node ddb-write-s3-local-v3.js</pre><h3>Settings Breakdown</h3><ul><li>FILE_COUNT=3 Controls how many CSV files are open and processed concurrently in the Round-Robin pool. Spreading writes across 3 distinct files ensures partition key variance across batches.</li><li>MAX_ROWS_PER_SECOND=120 <strong>The primary safety circuit breaker.</strong> While DynamoDB could handle faster writes, updating rows triggers downstream events (such as DynamoDB Streams and Kinesis Data Streams). Capping the script at 120 rows/sec prevented backpressure from overwhelming downstream Kinesis consumers and protected live production API traffic from competing resources.</li><li>WCU_START=3000<strong> / </strong>WCU_MIN=300<strong> / </strong>WCU_MAX=10000 Defines the operational boundaries for provisioned Write Capacity Units (WCUs). The script starts target capacity at 3,000 WCU, allowing dynamic scaling anywhere between a floor of 300 and a ceiling of 10,000 depending on database response times.</li><li>WCU_RAMP_FACTOR=1.2<strong> &amp; </strong>WCU_RAMP_INTERVAL_MS=2500Implements additive increase logic. If no throttling occurs within a 2.5-second interval, the target throughput target ramps up by 20% (1.2x).</li><li>WCU_BACKOFF_FACTOR=0.9Implements multiplicative decrease logic. Upon encountering rate-limiting errors from AWS, the script immediately dials back target throughput by 10% to let partitions recover.</li><li>THROTTLE_PAUSE_MS=100<strong> &amp; </strong>RETRIES=8Resilience configuration. If a batch is throttled, the worker pauses for 100ms before retrying, allowing up to 8 backoff retries per failed batch before marking a file segment for manual inspection.</li><li>TABLE_NAME=x<strong> / </strong>BUCKET=y<strong> / </strong>AWS_REGION=eu-west-1 Standard environment variables defining the target DynamoDB table, source S3 bucket, and target AWS region.</li></ul><h3>Key Takeaways</h3><ul><li><strong>Avoid Scans at all costs for heavy analytical processing:</strong> PITR exports to S3 are virtually free in terms of runtime database impact and offer extreme parallelism.</li><li><strong>Beware of S3 Export ordering:</strong> Data exported from DynamoDB to S3 tends to be grouped by partition key range. Always shuffle or process multiple export chunks concurrently (Round-Robin) to prevent hot physical partitions during write-backs.</li><li><strong>Always throttle bulk scripts based on downstream dependencies:</strong> The bottleneck is rarely DynamoDB itself — it’s often downstream Kinesis consumers, Lambda triggers, or third-party APIs listening to DB streams. Safe execution limits like MAX_ROWS_PER_SECOND keep production systems safe.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ef667429610" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NestJS Microservices: Real-World Patterns]]></title>
            <link>https://medium.com/@jradzik4/nestjs-microservices-real-world-patterns-32ae25b034e7?source=rss-fe30da5ee536------2</link>
            <guid isPermaLink="false">https://medium.com/p/32ae25b034e7</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Jakub Radzik]]></dc:creator>
            <pubDate>Thu, 12 Mar 2026 14:40:42 GMT</pubDate>
            <atom:updated>2026-03-12T14:40:42.761Z</atom:updated>
            <content:encoded><![CDATA[<p>Building microservices is easy; building <em>resilient</em> microservices is where most teams hit a wall. In the early days of Node.js, you were often left stitching together disparate libraries for networking, serialization, and discovery. You spent more time debugging your message broker than writing business logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1Njv9-BStqAzzmY2" /><figcaption>Photo by <a href="https://unsplash.com/@growtika?utm_source=medium&amp;utm_medium=referral">Growtika</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Enter <strong>NestJS</strong>. By providing a unified abstraction layer over different transport protocols — from simple TCP to high-performance gRPC and massive event-streamers like Kafka — NestJS allows you to swap your underlying infrastructure without rewriting your domain logic.</p><p>However, “transport-agnostic” doesn’t mean “one size fits all.” In this guide, we’re going to look past the “Hello World” tutorials and dive into the architectural patterns required for a 2026 production environment. We will explore how to balance the strict contracts of gRPC with the massive scalability of Kafka, all while maintaining a local developer experience that actually works, thanks to Docker.</p><h3>1. The Transport Dilemma: gRPC vs. TCP</h3><p>When moving away from standard HTTP/REST for internal communication, developers usually land on two primary candidates: <strong>TCP</strong> (the “Easy Mode”) and <strong>gRPC</strong> (the “Performance Mode”).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*4gfAhNZYLx2SN_JBDiFMrw.png" /><figcaption>The Technical Breakdown</figcaption></figure><h3>Use Cases: Choosing Your Weapon</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dRPbu1MrYZ8Cz7CU" /><figcaption>Photo by <a href="https://unsplash.com/@marcinjozwiak?utm_source=medium&amp;utm_medium=referral">Marcin Jozwiak</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Choose TCP when:</strong></p><ul><li>You are building a <strong>quick prototype</strong> or a small internal tool.</li><li>The team is small, and maintaining a separate schema repository feels like “over-engineering.”</li><li>You need simple, request-response communication without the overhead of learning Protobuf syntax.</li></ul><p><strong>Choose gRPC when:</strong></p><ul><li><strong>Polyglot Architecture:</strong> You have a NestJS gateway talking to a Go or Python microservice. gRPC is the universal language.</li><li><strong>Strict Contracts:</strong> You want to ensure that a change in the “User Service” doesn’t silently break the “Billing Service” (Schema-first development).</li><li><strong>High Throughput:</strong> You are handling thousands of requests per second where the overhead of parsing JSON strings becomes a CPU bottleneck.</li></ul><h3>Code Focus: Implementation Comparison</h3><p>Let’s look at how these two differ in a real NestJS setup for a HeroService.</p><h4>The TCP Approach (The Simple Way)</h4><p>In TCP, we rely on standard TypeScript classes. There is no external schema file; the “contract” is essentially the code itself.</p><p><strong>Service Configuration (Main.ts):</strong></p><pre>const app = await NestFactory.createMicroservice&lt;MicroserviceOptions&gt;(AppModule, {<br>  transport: Transport.TCP,<br>  options: {<br>    host: &#39;0.0.0.0&#39;,<br>    port: 3001,<br>  },<br>});</pre><p><strong>Controller Pattern:</strong></p><pre>@Controller()<br>export class HeroController {<br>  @MessagePattern({ cmd: &#39;get_hero&#39; }) // Simple object pattern<br>  getHero(data: { id: number }): Hero {<br>    return { id: data.id, name: &#39;Superman&#39; };<br>  }<br>}</pre><h4>The gRPC Approach (The Robust Way)</h4><p>gRPC requires a .proto file. This is your &quot;Source of Truth.&quot; It defines the service interface and the data structures in a language-agnostic format.</p><p><strong>1. The Contract (</strong><strong>hero.proto):</strong></p><pre>syntax = &quot;proto3&quot;;<br><br>package hero;<br><br>service HeroService {<br>  rpc FindOne (HeroById) returns (Hero) {}<br>}<br><br>message HeroById {<br>  int32 id = 1;<br>}<br><br>message Hero {<br>  int32 id = 1;<br>  string name = 2;<br>}</pre><p><strong>2. Service Configuration (Main.ts):</strong></p><pre>import { join } from &#39;path&#39;;<br><br>const app = await NestFactory.createMicroservice&lt;MicroserviceOptions&gt;(AppModule, {<br> transport: Transport.GRPC,<br> options: {<br>   package: &#39;hero&#39;,<br>   protoPath: join(__dirname, &#39;./hero/hero.proto&#39;),<br>   url: &#39;0.0.0.0:50051&#39;,<br> },<br>});</pre><p><strong>3. The Implementation:</strong> Using the @GrpcMethod decorator, NestJS automatically maps the incoming binary stream to your method.</p><pre>import { Controller } from &#39;@nestjs/common&#39;;<br>import { GrpcMethod } from &#39;@nestjs/microservices&#39;;<br><br>@Controller()<br>export class HeroController {<br>  @GrpcMethod(&#39;HeroService&#39;, &#39;FindOne&#39;) // Matches the .proto file<br>  findOne(data: HeroById): Hero {<br>    const heroes = [<br>      { id: 1, name: &#39;Batman&#39; },<br>      { id: 2, name: &#39;Wonder Woman&#39; },<br>    ];<br>    return heroes.find(({ id }) =&gt; id === data.id);<br>  }<br>}</pre><h3>The “2026” Perspective</h3><p>By 2026, the ts-proto plugin has become the industry standard for NestJS developers. It automatically generates TypeScript interfaces from your .proto files, ensuring that your gRPC implementation is <strong>end-to-end type-safe</strong> without manual interface mirroring.</p><blockquote><strong><em>Pro-Tip:</em></strong><em> If you’re building for scale, start with TCP for speed, but isolate your interfaces. As soon as you hit 3+ services or multiple languages, migrate to gRPC. The binary serialization alone can reduce your cloud networking costs by 30–40% in high-traffic environments.</em></blockquote><h3>2. Message Patterns: Commands vs. Events</h3><p>In a distributed system, how services talk is just as important as what they say. NestJS provides two primary decorators that define the “vibe” of your communication: @MessagePattern() and @EventPattern(). Understanding the difference is the line between a system that scales and one that collapses under its own latency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ugVawrXQcWZTf7Dx" /><figcaption>Photo by <a href="https://unsplash.com/@xiaowuuuuuuu?utm_source=medium&amp;utm_medium=referral">Le Vu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In NestJS, we categorize communication into <strong>Request-Response</strong> (Synchronous/Commands) and <strong>Event-Based</strong> (Asynchronous/Events).</p><h3>The Request-Response Pattern: Commands</h3><p>When you use @MessagePattern(), you are essentially performing a Remote Procedure Call (RPC). The requester sends a message and <strong>waits</strong> for a response. This is ideal for &quot;Commands&quot;—actions that require immediate confirmation or data retrieval.</p><ul><li><strong>Logic:</strong> “I need this data now to proceed.”</li><li><strong>Decorator:</strong> @MessagePattern(metadata)</li><li><strong>Best for:</strong> Fetching user profiles, calculating tax on a checkout, or validating a coupon code.</li></ul><p><strong>Implementation (The “User” Service):</strong></p><pre>@Controller()<br>export class BalanceController {<br>  @MessagePattern({ cmd: &#39;get_user_balance&#39; })<br>  async getBalance(data: { userId: string }): Promise&lt;number&gt; {<br>    // Business logic to query DB<br>    return 1500.50; <br>  }<br>}</pre><p><strong>Usage (The “Gateway” Service):</strong></p><pre>// The &#39;send&#39; method returns an Observable that we convert to a Promise<br>const balance = await firstValueFrom(<br>  this.client.send({ cmd: &#39;get_user_balance&#39; }, { userId: &#39;123&#39; })<br>);</pre><h3>The Event-Based Pattern: Fire-and-Forget</h3><p>When you use @EventPattern(), you are broadcasting information. The sender doesn&#39;t care if the receiver is busy, slow, or even online at that exact millisecond. This is the backbone of reactive systems.</p><ul><li><strong>Logic:</strong> “Something happened. Do with that what you will.”</li><li><strong>Decorator:</strong> @EventPattern(metadata)</li><li><strong>Best for:</strong> Sending emails, updating search indexes, or logging analytics.</li></ul><p><strong>Implementation (The “Notification” Service):</strong></p><pre>@Controller()<br>export class NotificationController {<br>  @EventPattern(&#39;order_created&#39;)<br>  async handleOrderCreated(data: OrderDto) {<br>    console.log(`Sending confirmation email for order: ${data.id}`);<br>    // No &#39;return&#39; value is expected by the sender<br>  }<br>}</pre><p><strong>Usage (The “Order” Service):</strong></p><pre>// The &#39;emit&#39; method just pushes the message to the broker and moves on<br>this.client.emit(&#39;order_created&#39;, newOrder);</pre><h3>Real-World Hybrid: The “Order-to-Inventory” Flow</h3><p>In a production environment, you rarely use just one. You use a hybrid approach to ensure the user gets a fast response while the system maintains eventual consistency in the background.</p><p>Imagine an <strong>E-commerce Checkout</strong>:</p><ul><li><strong>Gateway</strong> uses @MessagePattern to ask the <strong>Payment Service</strong> to charge the card. (We need to know <em>immediately</em> if it failed).</li><li>Once payment is confirmed, the <strong>Payment Service</strong> uses @EventPattern to broadcast payment_successful.</li><li>The <strong>Inventory Service</strong> listens to that event to deduct stock.</li><li>The <strong>Email Service</strong> listens to that same event to send a receipt.</li></ul><h4>The Hybrid Code Pattern</h4><pre>@Injectable()<br>export class CheckoutService {<br>  constructor(@Inject(&#39;SERVICE_BUS&#39;) private client: ClientProxy) {}<br><br>  async placeOrder(orderData: CreateOrderDto) {<br>      // 1. COMMAND: Synchronous check (RPC)<br>      const isProcessed = await firstValueFrom(<br>        this.client.send({ cmd: &#39;process_payment&#39; }, orderData)<br>      );<br>      if (isProcessed.success) {<br>        // 2. EVENT: Asynchronous broadcast (Event-driven)<br>        this.client.emit(&#39;order_placed&#39;, { <br>          orderId: isProcessed.orderId, <br>          timestamp: new Date() <br>        });<br>        <br>        return { status: &#39;Confirmed&#39; };<br>      }<br>      <br>      throw new BadRequestException(&#39;Payment failed&#39;);<br>    }<br>}</pre><h3>Why This Matters for Scaling</h3><p>By offloading the non-essential tasks (email, logs, secondary updates) to @EventPattern, you reduce the <strong>Total Response Time</strong> for the end-user. If the Email Service is down, the order still goes through. If you used @MessagePattern for everything, one slow service would create a &quot;bottleneck cascade,&quot; potentially bringing down your entire API Gateway.</p><h3>3. Scaling the Backbone with Kafka</h3><p>When your microservice architecture moves from “a few services” to a high-traffic “event-driven ecosystem,” standard message brokers like RabbitMQ or Redis can start to show their limits, particularly regarding message persistence and massive throughput. This is where <strong>Apache Kafka</strong> enters the chat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t4dllonBcEcrog9b" /><figcaption>Photo by <a href="https://unsplash.com/@nate_dumlao?utm_source=medium&amp;utm_medium=referral">Nathan Dumlao</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Why Kafka? From Message Broker to Event Stream</h3><p>Unlike traditional brokers that delete messages once they are acknowledged, Kafka is a <strong>distributed commit log</strong>.</p><ul><li><strong>Replayability:</strong> You can “rewind the tape” and re-process events from last week if a bug was discovered in your logic.</li><li><strong>High Throughput:</strong> It is designed to handle millions of events per second by decoupling the write and read operations across a cluster.</li><li><strong>Durability:</strong> Data is persisted to disk and replicated, ensuring you don’t lose the “Order Created” event even if the broker restarts.</li></ul><h3>The Partitioning Strategy &amp; Consumer Groups</h3><p>In NestJS, the secret to scaling Kafka lies in <strong>Partitions</strong> and <strong>Consumer Groups</strong>.</p><p>A Kafka Topic is split into multiple partitions. To scale your processing, you spin up multiple instances of your NestJS microservice under the same groupId. Kafka will then balance the partitions across these instances.</p><blockquote><strong><em>Rule of Thumb:</em></strong><em> You cannot have more active consumers in a group than you have partitions. If you have 6 partitions, you can scale to 6 NestJS pods. The 7th pod will sit idle as a “hot standby.”</em></blockquote><h3>Code Focus: Configuring the ClientKafka</h3><p>Setting up Kafka in NestJS requires a bit more configuration than TCP. You need to define the clientId, the brokers, and, crucially, the consumer group ID.</p><p><strong>1. Microservice Configuration (</strong><strong>main.ts):</strong></p><pre>const app = await NestFactory.createMicroservice&lt;MicroserviceOptions&gt;(AppModule, {<br>  transport: Transport.KAFKA,<br>  options: {<br>    client: {<br>      brokers: [&#39;localhost:9092&#39;], // In production, this is a comma-separated list<br>    },<br>    consumer: {<br>      groupId: &#39;billing-consumer&#39;, // Unique per service type<br>    },<br>  },<br>});</pre><p><strong>2. Handling Request-Response with </strong><strong>replyTopic</strong> By default, Kafka is asynchronous. However, NestJS allows you to perform request-response patterns over Kafka by using a <strong>Reply Topic</strong>. It sends a message with a correlation ID and waits for a response on a specific callback topic.</p><p><strong>The Client Gateway Configuration:</strong></p><pre>@Module({<br>  imports: [<br>    ClientsModule.register([<br>      {<br>        name: &#39;BILLING_SERVICE&#39;,<br>        transport: Transport.KAFKA,<br>        options: {<br>          client: {<br>            clientId: &#39;billing-client&#39;,<br>            brokers: [&#39;localhost:9092&#39;],<br>          },<br>          consumer: {<br>            groupId: &#39;billing-client-consumer&#39;, // Client needs its own consumer group<br>          },<br>        },<br>      },<br>    ]),<br>  ],<br>})<br>export class AppModule {}</pre><p><strong>Sending a Request (Gateway):</strong></p><pre>@Injectable()<br>export class AppService implements OnModuleInit {<br>  constructor(@Inject(&#39;BILLING_SERVICE&#39;) private readonly client: ClientKafka) {}<br><br>  async onModuleInit() {<br>      // We must manually subscribe to response topics in Kafka transport<br>      this.client.subscribeToResponseOf(&#39;get_invoice_status&#39;);<br>      await this.client.connect();<br>    }<br><br>    getInvoice(id: string) {<br>      return this.client.send(&#39;get_invoice_status&#39;, { id }); <br>      // NestJS handles the heavy lifting of correlation IDs behind the scenes<br>    }<br>}</pre><h3>Pro-Tip: The “2026” Partition Key</h3><p>In 2026, we don’t just broadcast; we route. Use <strong>Partition Keys</strong> (like userId or orderId) when emitting events. This ensures that all events related to the same user always land in the same partition and are processed by the same service instance, preventing race conditions in stateful operations.</p><h3>4. Orchestrating the Fleet: The Docker Compose Blueprint</h3><p>In a microservices architecture, your local machine needs to mimic the complexity of the cloud. If you are manually starting Kafka, then your Gateway, then your Billing service, you are doing it wrong. By 2026, <strong>Docker Compose</strong> isn’t just a convenience; it is your source of truth for service discovery and environment parity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g2hv7GnvKliWArqg" /><figcaption>Photo by <a href="https://unsplash.com/@guibolduc?utm_source=medium&amp;utm_medium=referral">Guillaume Bolduc</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The “Development Mirror”</h3><p>To run NestJS with Kafka, we need a broker. Modern Kafka setups (post-version 3.3) use <strong>KRaft</strong> mode, which removes the need for a separate Zookeeper container. This simplifies our “Development Mirror” significantly, reducing memory overhead and startup time.</p><h3>Networking Nuances: localhost vs. container_name</h3><p>The #1 reason developers fail to connect NestJS to Kafka in Docker is networking.</p><ul><li><strong>Outside the container:</strong> You access Kafka via localhost:9094.</li><li><strong>Inside the container:</strong> Your NestJS service must use the <strong>service name</strong> defined in the YAML (e.g., kafka:9092).</li></ul><p>We solve this using <strong>Advertised Listeners</strong>, telling Kafka to listen on different “interfaces” for internal and external traffic.</p><h3>Code Focus: Production-Ready docker-compose.yml</h3><p>This setup includes health checks to ensure your NestJS services don’t try to connect to Kafka before the broker is actually ready to receive messages.</p><pre>services:<br>  kafka:<br>    image: bitnami/kafka:3.7.0 # Using a stable 2024-2026 era image<br>    container_name: kafka-broker<br>    ports:<br>      - &quot;9094:9094&quot;<br>    environment:<br>      - KAFKA_CFG_NODE_ID=1<br>      - KAFKA_CFG_PROCESS_ROLES=controller,broker<br>      - KAFKA_CFG_LISTENERS=PLAINTEXT://:9092,CONTROLLER://:9093,EXTERNAL://:9094<br>      - KAFKA_CFG_ADVERTISED_LISTENERS=PLAINTEXT://kafka:9092,EXTERNAL://localhost:9094<br>      - KAFKA_CFG_LISTENER_SECURITY_PROTOCOL_MAP=CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT,EXTERNAL:PLAINTEXT<br>      - KAFKA_CFG_CONTROLLER_QUORUM_VOTERS=1@kafka:9093<br>      - KAFKA_CFG_CONTROLLER_LISTENER_NAMES=CONTROLLER<br>    healthcheck:<br>      test: [&quot;CMD-SHELL&quot;, &quot;kafka-topics.sh --bootstrap-server localhost:9092 --list&quot;]<br>      interval: 10s<br>      timeout: 5s<br>      retries: 5<br><br>  billing-service:<br>      build:<br>        context: .<br>        dockerfile: ./apps/billing/Dockerfile<br>      container_name: billing-service<br>      depends_on:<br>        kafka:<br>          condition: service_healthy<br>      environment:<br>        - KAFKA_BROKERS=kafka:9092 # Matches internal listener<br>      networks:<br>        - micro-network<br><br>    api-gateway:<br>      build:<br>        context: .<br>        dockerfile: ./apps/api-gateway/Dockerfile<br>      ports:<br>        - &quot;3000:3000&quot;<br>      depends_on:<br>        kafka:<br>          condition: service_healthy<br>      environment:<br>        - KAFKA_BROKERS=kafka:9092<br>      networks:<br>        - micro-network<br><br>  networks:<br>    micro-network:<br>      driver: bridge</pre><h3>The NestJS Environment Strategy</h3><p>In your NestJS code, you should never hardcode localhost. Use environment variables that Docker provides:</p><pre>// Inside your NestJS Kafka Configuration<br>options: {<br>  client: {<br>    brokers: [process.env.KAFKA_BROKERS || &#39;localhost:9094&#39;], <br>  },<br>}</pre><h3>Why Health Checks Matter</h3><p>Without the condition: service_healthy block, your NestJS service might start, try to connect to Kafka, fail, and crash loop while Kafka is still performing its internal startup routines. By using the kafka-topics.sh command as a health check, we ensure the &quot;Fleet&quot; orchestrates in the correct order.</p><h3>5. The Safety Net: Distributed Error Handling</h3><p>In a distributed system, a failure in one service can act like a virus, spreading through your network and crashing unrelated components. In 2026, we don’t just “try-catch”; we implement <strong>Resilience Patterns</strong>.</p><p>Error handling in microservices is a two-sided coin: you must handle errors that occur during a synchronous request (RPC) and those that occur during asynchronous streaming (Kafka).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RxtRKVSDYiB-IfEU" /><figcaption>Photo by <a href="https://unsplash.com/@heyquilia?utm_source=medium&amp;utm_medium=referral">Kenny Eliason</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The RpcException Filter: The Gateway Translator</h3><p>When a microservice throws an error, it doesn’t automatically become a 404 or 500 HTTP status code. It returns an RpcException. The API Gateway acts as the translator, catching these exceptions and converting them into something the frontend understands.</p><p><strong>The Microservice-Side Filter:</strong></p><pre>import { Catch, RpcExceptionFilter, ArgumentsHost } from &#39;@nestjs/common&#39;;<br>import { RpcException } from &#39;@nestjs/microservices&#39;;<br>import { Observable, throwError } from &#39;rxjs&#39;;<br><br>@Catch(RpcException)<br>export class MessageErrorFilter implements RpcExceptionFilter&lt;RpcException&gt; {<br>  catch(exception: RpcException, host: ArgumentsHost): Observable&lt;any&gt; {<br>    // Log the error for internal observability<br>    console.error(&#39;Microservice Error:&#39;, exception.getError());<br>    // Pass it back to the Gateway<br>    return throwError(() =&gt; exception.getError());<br>  }<br>}</pre><h3>Kafka Retries &amp; Dead Letter Queues (DLQ)</h3><p>What happens if your “Email Service” fails to send a receipt because the SMTP server is down? In a simple TCP setup, the message might just vanish. In Kafka, we use <strong>Retries</strong> and <strong>Dead Letter Queues</strong>.</p><p>If a message fails after X attempts, we move it to a billing.failed topic. This prevents a &quot;poison pill&quot; message from blocking your partition indefinitely.</p><p><strong>Implementation Logic:</strong></p><ul><li><strong>Retry:</strong> NestJS (via kafkajs) can be configured to retry connection errors.</li><li><strong>DLQ:</strong> If business logic fails (e.g., invalid data), catch the error and manually emit to a failure topic.</li></ul><p><strong>Code Focus: Manual DLQ Pattern</strong></p><pre>@EventPattern(&#39;process_payment&#39;)<br>async handlePayment(data: any, @Ctx() context: KafkaContext) {<br>  try {<br>    await this.paymentService.process(data);<br>  } catch (err) {<br>    const { topic, partition } = context.getMessage();<br>    // Logic: Send to Dead Letter Queue for manual review<br>    this.client.emit(&#39;payments_dlq&#39;, {<br>      originalError: err.message,<br>      originalTopic: topic,<br>      payload: data,<br>    });<br>  }<br>}</pre><h3>The Global Exception Filter</h3><p>To ensure no error goes unlogged, we apply a global filter to our microservice main.ts.</p><pre>// main.ts<br>app.useGlobalFilters(new MessageErrorFilter());</pre><h3>Conclusion: Engineering for the “In-Between”</h3><p>Mastering NestJS microservices in 2026 is about more than just knowing decorators; it’s about understanding the <strong>in-between</strong>. It’s the space between your services where latency lives, where Docker networking can fail, and where Kafka partitions can become unbalanced.</p><p>By choosing <strong>gRPC</strong> for performance, <strong>TCP</strong> for simplicity, and <strong>Kafka</strong> for massive scale, you aren’t just building a “backend” — you’re building a resilient, living organism. Use <strong>Docker Compose</strong> to treat your infrastructure as code, and never let an error go unhandled without a <strong>Dead Letter Queue</strong> safety net.</p><p>The “Microservice Tax” is real, but with NestJS, you finally have the tools to pay it in full and still come out ahead.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32ae25b034e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your “Clean Architecture” is Killing Your Node.js Performance]]></title>
            <link>https://medium.com/@jradzik4/why-your-clean-architecture-is-killing-your-node-js-performance-062563ab211c?source=rss-fe30da5ee536------2</link>
            <guid isPermaLink="false">https://medium.com/p/062563ab211c</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Jakub Radzik]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 11:36:03 GMT</pubDate>
            <atom:updated>2026-03-09T11:36:03.450Z</atom:updated>
            <content:encoded><![CDATA[<p>We’ve all been there. You open a new Node.js project, and before you can find the logic for “Create User,” you have to tunnel through six layers of directories: infrastructure, domain, application, interfaces, entities, and use-cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9YeTtn-k4bN2cCdA" /><figcaption>Photo by <a href="https://unsplash.com/@jeshoots?utm_source=medium&amp;utm_medium=referral">JESHOOTS.COM</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>You’ve been told this is “Clean Architecture.” It’s supposed to make your code decoupled, testable, and “screaming” its intent. But in the high-stakes world of modern Node.js development, this rigid adherence to the “Onion” or “Hexagonal” pattern is often a silent performance killer — both for your application’s latency and your team’s velocity.</p><p>It’s time to talk about <strong>Boilerplate Hell</strong> and how to fold your layers into <strong>Vertical Slices</strong>.</p><h3>The “Abstraction Tax” is Real</h3><p>In theory, Clean Architecture is beautiful. It promises that you can swap your database or web framework at any moment (an event that happens approximately once every never). In a Node.js runtime, however, every unnecessary abstraction comes with a hidden cost.</p><ul><li><strong>Memory Overhead &amp; GC Pressure:</strong> Every time you wrap a database call in an Adapter, which is called by an Interactor, which is injected into a Controller, you are creating closures, class instances, and extra stack frames. In high-throughput environments, this creates significant garbage collection pressure.</li><li><strong>The “Middleman” Problem:</strong> We often write code like this just to satisfy a “clean” interface:</li></ul><pre>// The Interactor (Application Layer)<br>export class CreateUserInteractor {<br>  constructor(private userRepository: IUserRepository) {}<br><br>  async execute(data: UserDTO) {<br>    // This layer does... absolutely nothing but pass data<br>    return await this.userRepository.save(data);<br>  }<br>}</pre><p>If your layer is just a pass-through, <strong>it shouldn’t exist.</strong> It’s just more code to maintain, more code to test, and more code for the V8 engine to optimize.</p><h3>The Visual Shift: Layers vs. Slices</h3><p>Traditional Clean Architecture organizes code by <strong>technical role</strong>. Vertical Slice Architecture organizes code by <strong>business feature</strong>.</p><p>When you organize by layers, you are forced to jump across the entire codebase to implement a single change. When you organize by slices, the code for “Register User” lives near the code for “Register User.” It doesn’t care about the code for “Update Profile.”</p><h3>Moving to Vertical Slices</h3><p>The alternative isn’t “Messy Architecture”; it’s <strong>Vertical Slice Architecture</strong>. We treat each feature as a standalone unit of work.</p><h4>The “Folded” Code Example</h4><p>Let’s look at how we can maintain Type Safety while collapsing the boilerplate. We’ll use a “Functional Service” approach that keeps things lean.</p><p><strong>The Old Way (Clean Architecture Overkill):</strong></p><ul><li>src/domain/user.entity.ts</li><li>src/application/use-cases/create-user.ts</li><li>src/infrastructure/repositories/sql-user.repo.ts</li><li>src/interfaces/http/user.controller.ts</li></ul><p><strong>The New Way (Vertical Slice):</strong></p><ul><li>src/features/users/register-user.handler.ts</li></ul><pre>// src/features/users/register-user.handler.ts<br>import { z } from &#39;zod&#39;;<br>import { db } from &#39;@/infra/database&#39;;<br>import { hash } from &#39;@/infra/crypto&#39;;<br><br>// 1. Define the Schema (Input Validation)<br>export const RegisterUserSchema = z.object({<br>  email: z.string().email(),<br>  password: z.string().min(8),<br>});<br><br>// 2. Define the Logic (The &quot;Slice&quot;)<br>// This is the handler, the interactor, and the repository call combined<br>export async function registerUserHandler(rawInput: unknown) {<br>  // Type-safe validation at the edge<br>  const input = RegisterUserSchema.parse(rawInput);<br><br>  // Directly use the DB driver or a thin query builder.<br>  // We skip the &#39;Repository Pattern&#39; because we aren&#39;t swapping <br>  // Postgres for MongoDB tomorrow.<br>  const user = await db.user.create({<br>    data: {<br>      email: input.email,<br>      passwordHash: await hash(input.password),<br>    },<br>  });<br><br>  return { id: user.id, email: user.email };<br>}</pre><h3>Why Vertical Slices Win</h3><h4>1. Locality of Reference</h4><p>When you need to change how a user is registered, everything — the validation, the database query, and the response shape — is in <strong>one file</strong>. You don’t have to play “Find the File” in your IDE.</p><h4>2. Real Decoupling</h4><p>In Clean Architecture, “Services” often become “God Objects.” Every feature starts importing UserService, creating a tangled web. In Vertical Slices, features are isolated. If you need to delete the register-user feature, you delete one folder. No side effects.</p><h4>3. Performance Tuning</h4><p>Because the logic is direct, profiling becomes easy. You aren’t wading through stack traces of InversifyJS or NestJS dependency injection containers; you are looking at the actual database query causing the bottleneck.</p><h3>When to Abstract?</h3><p>&quot;Folding your layers&quot; doesn&#39;t mean writing &quot;Spaghetti Code.&quot; You should still abstract logic that is <strong>truly shared</strong>.</p><ul><li><strong>Shared Infrastructure:</strong> Database connection pools, authentication middleware, and global error handlers.</li><li><strong>Feature Logic:</strong> Keep it in the slice.</li></ul><p>The rule of thumb: <strong>Don&#39;t abstract until you&#39;ve felt the pain of duplication at least three times.</strong> In Node.js, a little bit of duplication is far cheaper than the wrong abstraction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*E-MegXLpdi4eDmgeA97yzQ.png" /><figcaption>Metric comparison of architectures</figcaption></figure><h3>Conclusion</h3><p>Clean Architecture was designed for a orld of Java monoliths and expensive recompilations. Node.js is a different beast — it thrives on simplicity, horizontal scaling, and rapid execution.</p><p>By moving to <strong>Vertical Slices</strong>, you aren’t abandoning “Good Design.” You are choosing an architecture that respects the runtime, reduces “Boilerplate Hell,” and actually lets you ship features instead of folder structures.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=062563ab211c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[6 Node.js 24 Built-ins That Will Replace Your Heavy NPM Dependencies]]></title>
            <link>https://medium.com/@jradzik4/6-node-js-24-built-ins-that-will-replace-your-heavy-npm-dependencies-5de59a3a7ffd?source=rss-fe30da5ee536------2</link>
            <guid isPermaLink="false">https://medium.com/p/5de59a3a7ffd</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[node-js-development]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <dc:creator><![CDATA[Jakub Radzik]]></dc:creator>
            <pubDate>Wed, 04 Mar 2026 11:08:43 GMT</pubDate>
            <atom:updated>2026-03-04T11:08:43.970Z</atom:updated>
            <content:encoded><![CDATA[<p>For years, the Node.js mantra was “small core, large ecosystem.” This led to the explosion of node_modules, where even a basic &quot;Hello World&quot; app required hundreds of dependencies for testing, environment variables, and file watching.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3KBVrs-aLK6i26ib" /><figcaption>Photo by <a href="https://unsplash.com/@javardh?utm_source=medium&amp;utm_medium=referral">Javardh</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In 2026, that era is officially over. Node.js 24 has reached a “batteries-included” state. By moving these common utilities into the runtime, your apps become faster to install, more secure (fewer supply-chain attack vectors), and significantly more lightweight.</p><p>Here are the 6 Node.js built-ins that will let you delete your heaviest NPM dependencies today.</p><h3>1. Native Environment Support (--env-file)</h3><p><strong>Replaces:</strong> dotenv, dotenv-expand</p><p>Loading configuration from a .env file used to be the first line of every project. Now, Node.js handles this at the runtime level before your code even executes.</p><p><strong>The Description:</strong> By passing the --env-file flag, Node.js automatically parses key-value pairs and injects them into process.env. It supports multiline variables and basic expansion natively, eliminating the need to import and initialize a library in your source code.</p><pre># Terminal: No more &#39;require(&quot;dotenv&quot;).config()&#39;<br>node --env-file=.env server.js</pre><pre>// server.ts<br>console.log(`Port: ${process.env.PORT}`); // Works out of the box</pre><h3>2. The Native Test Runner (node:test)</h3><p><strong>Replaces:</strong> jest, mocha, vitest</p><p>Jest is a powerhouse, but it is notoriously heavy. Node.js now includes a fully-featured, high-performance test runner that starts instantly.</p><p><strong>The Description:</strong> The node:test module provides describe, it, and test blocks, along with a powerful mocking API (t.mock) and built-in code coverage reporting via the --experimental-test-coverage flag.</p><pre>import { test, describe, it } from &#39;node:test&#39;;<br>import assert from &#39;node:assert&#39;;<br><br>describe(&#39;User Service&#39;, () =&gt; {<br>  it(&#39;should format usernames to lowercase&#39;, () =&gt; {<br>    const name = &quot;ALEX&quot;;<br>    assert.strictEqual(name.toLowerCase(), &quot;alex&quot;);<br>  });<br>});</pre><h3>3. Integrated Watch Mode (--watch)</h3><p><strong>Replaces:</strong> nodemon, pm2-dev</p><p>Development productivity relies on the “save and reload” cycle. While nodemon was the industry standard for a decade, Node.js now has this capability baked into the binary.</p><p><strong>The Description:</strong> The --watch flag monitors your entry point and all imported modules. It uses a highly efficient internal file-system watcher that consumes fewer resources than external polling tools. It even supports --watch-path to monitor specific directories.</p><pre># Restart your app automatically on every save<br>node --watch index.js</pre><h3>4. Native Globbing (node:fs glob)</h3><p><strong>Replaces:</strong> glob, fast-glob, rimraf</p><p>Searching for files using patterns (like src/**/*.test.ts) used to require complex external libraries. Node.js 24 has integrated these directly into the filesystem module.</p><p><strong>The Description:</strong> The glob and globSync functions allow you to traverse directories using standard Unix-style patterns. This is essential for build tools, custom CLI scripts, or dynamic route loading in a server.</p><pre>import { glob } from &#39;node:fs/promises&#39;;<br><br>// Find all TS files in the project<br>for await (const entry of glob(&#39;src/**/*.ts&#39;)) {<br>  console.log(`Found: ${entry}`);<br>}</pre><h3>5. Native SQLite Driver (node:sqlite)</h3><p><strong>Replaces:</strong> sqlite3, better-sqlite3</p><p>For local caching, edge computing, or small-scale applications, SQLite is the world’s most deployed database. Node.js now ships with its own high-performance, built-in SQLite driver.</p><p><strong>The Description:</strong> The node:sqlite module provides a synchronous and asynchronous API to interact with SQLite databases. It eliminates the need for complex &quot;binary rebuilds&quot; that often plague sqlite3 and better-sqlite3 during Node.js version upgrades.</p><pre>import { DatabaseSync } from &#39;node:sqlite&#39;;<br><br>const db = new DatabaseSync(&#39;:memory:&#39;);<br><br>db.exec(`CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT)`);<br>const insert = db.prepare(`INSERT INTO users (name) VALUES (?)`);<br>insert.run(&#39;Gemini&#39;);<br><br>const result = db.prepare(`SELECT * FROM users`).all();<br>console.log(result); // [{ id: 1, name: &#39;Gemini&#39; }]</pre><h3>6. Native Argument Parser (node:util parseArgs)</h3><p><strong>Replaces:</strong> yargs, commander</p><p>Creating CLI tools used to mean adding a massive dependency just to handle flags like --port 3000 or -v.</p><p><strong>The Description:</strong> The parseArgs function in node:util provides a lightweight, spec-compliant way to parse command-line arguments. It handles booleans, strings, and even short-flag aliases without the overhead of a massive CLI framework.</p><pre>import { parseArgs } from &#39;node:util&#39;;<br><br>const options = {<br>  port: { type: &#39;string&#39;, short: &#39;p&#39; },<br>  debug: { type: &#39;boolean&#39; },<br>};<br><br>const { values } = parseArgs({ options });<br><br>console.log(values.port);  // &#39;3000&#39;<br>console.log(values.debug); // true</pre><h3>Outro: Leaner, Faster, Safer</h3><p>The transition to Node.js 24 signals a more mature ecosystem. By leveraging these built-ins, you aren’t just reducing your node_modules size—you are improving your application&#39;s <strong>cold-start time</strong>, reducing <strong>security vulnerabilities</strong>, and making your codebase much easier to maintain for other developers.</p><p>Next time you go to npm install, stop and check:<br><strong>Does Node.js already do this?</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5de59a3a7ffd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[6 Advanced “satisfies” Patterns for Bulletproof TS Configurations]]></title>
            <link>https://medium.com/@jradzik4/6-advanced-satisfies-patterns-for-bulletproof-ts-configurations-4468d8d39e1c?source=rss-fe30da5ee536------2</link>
            <guid isPermaLink="false">https://medium.com/p/4468d8d39e1c</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[learn-to-code]]></category>
            <category><![CDATA[typescript-satisfies]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jakub Radzik]]></dc:creator>
            <pubDate>Mon, 02 Mar 2026 08:46:25 GMT</pubDate>
            <atom:updated>2026-03-02T08:46:25.425Z</atom:updated>
            <content:encoded><![CDATA[<p>In the early days of TypeScript, we had a binary choice: either let TypeScript <strong>infer</strong> the types (flexible but risky) or <strong>explicitly annotate</strong> them (safe but restrictive). If you annotated a config object with a type, you often lost the specific literal information that made your IDE’s autocomplete feel like magic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*im2AsHmrBhWiiNay" /><figcaption>Photo by <a href="https://unsplash.com/@ixxlhey?utm_source=medium&amp;utm_medium=referral">Izdhan Imran</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Then came the satisfies operator.</p><p>It is the “validator” of the TypeScript world. It allows you to verify that an object matches a specific shape <strong>without</strong> widening the underlying types. Here are six advanced patterns to move your configurations from “stringly-typed” to bulletproof.</p><h3>1. The Exhaustive Registry Pattern</h3><p>When building a system that requires a value for every possible key (like a Theme or a Language map), you want to ensure no key is missing, but you also want TS to remember exactly what those values are.</p><pre>type ThemeColor = &#39;primary&#39; | &#39;secondary&#39; | &#39;accent&#39;;<br>interface ColorSatus {<br>  hex: string;<br>  isAccessible: boolean;<br>}<br><br>// ❌ Problem with annotation: <br>// const Palette: Record&lt;ThemeColor, ColorSatus&gt; = { ... } <br>// Palette.primary.hex would just be &quot;string&quot;<br><br>// ✅ The satisfies solution:<br>const Palette = {<br>  primary: { hex: &#39;#007bff&#39;, isAccessible: true },<br>  secondary: { hex: &#39;#6c757d&#39;, isAccessible: true },<br>  accent: { hex: &#39;#ffc107&#39;, isAccessible: false },<br>} satisfies Record&lt;ThemeColor, ColorSatus&gt;;<br><br>// Autocomplete knows exactly which keys exist and <br>// preserves the literal boolean values for logic.<br>if (Palette.accent.isAccessible === false) {<br>  console.warn(&quot;Low contrast detected&quot;);<br>}</pre><h3>2. The “Smart” API Route Map</h3><p>Hard-coded strings are the silent killers of large-scale Node.js apps. Using satisfies, you can create a central route registry that validates structure while keeping track of which routes require specific metadata.</p><pre>type RouteConfig = {<br>  path: `/${string}`;<br>  method: &#39;GET&#39; | &#39;POST&#39; | &#39;PUT&#39; | &#39;DELETE&#39;;<br>  roles?: string[];<br>};<br><br>const ApiRoutes = {<br>  GET_USERS: { path: &#39;/users&#39;, method: &#39;GET&#39; },<br>  DELETE_ADMIN: { path: &#39;/admin/delete&#39;, method: &#39;DELETE&#39;, roles: [&#39;admin&#39;] },<br>} satisfies Record&lt;string, RouteConfig&gt;;<br><br>// TS knows &#39;roles&#39; doesn&#39;t exist on GET_USERS, <br>// avoiding &#39;undefined&#39; checks in your routing logic.<br>const adminOnly = ApiRoutes.DELETE_ADMIN.roles.includes(&#39;admin&#39;);</pre><h3>3. Deep Property Validation (Nested Objects)</h3><p>One of the most annoying parts of TypeScript is validating nested configurations, like a multi-region cloud setup. satisfies ensures the deep structure is correct without forcing you to cast the entire object as any.</p><pre>type Region = &#39;us-east-1&#39; | &#39;eu-central-1&#39;;<br>type ServiceConfig = {<br>  instances: number;<br>  autoscaling: boolean;<br>};<br><br>const CloudManifest = {<br>  &#39;us-east-1&#39;: { instances: 10, autoscaling: true },<br>  &#39;eu-central-1&#39;: { instances: 5, autoscaling: false },<br>  // &#39;ap-south-1&#39;: { ... } ❌ Error: ap-south-1 is not a valid Region<br>} satisfies Record&lt;Region, ServiceConfig&gt;;<br><br>// manifest.instances is inferred as a literal number or a specific range <br>// if defined, rather than just &#39;number&#39;.</pre><h3>4. Validating “Branded” String Formats</h3><p>In Node.js, we often deal with strings that must follow a pattern (URLs, Hex codes, ISO dates). By combining <strong>Template Literal Types</strong> with satisfies, you create a compile-time regex for your config.</p><pre>type VersionString = `v${number}.${number}.${number}`;<br><br>interface PackageInfo {<br>  name: string;<br>  version: VersionString;<br>}<br><br>const ProjectConfig = {<br>  name: &quot;my-node-app&quot;,<br>  version: &quot;v1.2.0&quot;, // ✅ Correct<br>  // version: &quot;1.2.0&quot; // ❌ Error: Missing the &#39;v&#39; prefix<br>} satisfies PackageInfo;</pre><h3>5. The Plug-and-Play Middleware Pattern</h3><p>If you are building an Express or Fastify app, you likely have a set of middlewares. satisfies allows you to ensure every middleware provides the required handler function while allowing each middleware to carry its own unique helper functions.</p><pre>type Middleware = {<br>  name: string;<br>  handler: (req: any, res: any) =&gt; void;<br>};<br><br>const AuthGuard = {<br>  name: &quot;auth-guard&quot;,<br>  handler: (req, res) =&gt; { /* logic */ },<br>  bypassForTesting: () =&gt; true // This custom method is PRESERVED<br>} satisfies Middleware;<br><br>// You can call custom methods because AuthGuard isn&#39;t <br>// &quot;flattened&quot; into the Middleware type.<br>AuthGuard.bypassForTesting();</pre><h3>6. Discriminated Union Consistency</h3><p>This is the ultimate “Senior Developer” pattern. It forces your configuration to be logically sound. If you choose one option, you must provide the related data.</p><pre>type DatabaseDriver = <br>  | { type: &#39;postgres&#39;; connectionString: string }<br>  | { type: &#39;sqlite&#39;; dbPath: string; memory: boolean };<br><br>const DatabaseConfig = {<br>  production: { <br>    type: &#39;postgres&#39;, <br>    connectionString: &#39;postgres://localhost:5432&#39; <br>  },<br>  development: { <br>    type: &#39;sqlite&#39;, <br>    dbPath: &#39;:memory:&#39;, <br>    memory: true <br>  }<br>} satisfies Record&lt;&#39;production&#39; | &#39;development&#39;, DatabaseDriver&gt;;<br><br>// Logic check: TS knows that because production.type is &#39;postgres&#39;,<br>// it MUST have a connectionString and DOES NOT have a dbPath.</pre><h3>Conclusion: The New Standard for Node.js Configs</h3><p>The satisfies operator represents a shift in the TypeScript ecosystem. We are moving away from <strong>defensive programming</strong> (where we cast types and hope for the best) toward <strong>intentional modeling</strong>.</p><p>By using these patterns, you eliminate the “Type Widening” problem that plagues complex configurations. Your IDE becomes smarter, your refactors become safer, and your code becomes the documentation itself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4468d8d39e1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 tsconfig.json Settings That Will Make Your Build Process 2x Stricter (and Better)]]></title>
            <link>https://medium.com/@jradzik4/5-tsconfig-json-settings-that-will-make-your-build-process-2x-stricter-and-better-fadaf0109f88?source=rss-fe30da5ee536------2</link>
            <guid isPermaLink="false">https://medium.com/p/fadaf0109f88</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typescript-tips]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[tsconfig]]></category>
            <dc:creator><![CDATA[Jakub Radzik]]></dc:creator>
            <pubDate>Wed, 25 Feb 2026 13:50:13 GMT</pubDate>
            <atom:updated>2026-02-25T13:50:13.861Z</atom:updated>
            <content:encoded><![CDATA[<p>TypeScript is a fantastic tool that saves us from countless runtime errors. However, out of the box, TypeScript’s default configuration is surprisingly lenient. It was designed to make migrating from vanilla JavaScript as frictionless as possible — not to enforce maximum type safety from day one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8vlWQICsMPbwMHR8" /><figcaption>Photo by <a href="https://unsplash.com/@designer_magdeburg?utm_source=medium&amp;utm_medium=referral">Robert Klank</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you already have &quot;strict&quot;: true enabled in your project (and you absolutely should!), you are off to a great start. But lurking in the depths of the TypeScript documentation are several lesser-known compiler flags that can catch even more subtle bugs.</p><p>If you want to bulletproof your codebase, here are 5 tsconfig.json settings that will make your build process significantly stricter and your code much more predictable.</p><h3>1. noUncheckedIndexedAccess</h3><p>If you only enable one extra flag from this list, make it this one. It is an absolute game-changer.</p><p>By default, when you access an array or a record by an index, TypeScript assumes the element exists and returns its type. In reality, that index might be out of bounds, leading to the classic Cannot read properties of undefined runtime error.</p><p><strong>Without the flag:</strong></p><pre>const names: string[] = [&quot;Alice&quot;, &quot;Bob&quot;];<br>const thirdName = names[2]; // TypeScript says this is a &#39;string&#39;<br><br>console.log(thirdName.toUpperCase()); // Runtime error!</pre><p><strong>With </strong>noUncheckedIndexedAccess<strong> enabled:</strong> TypeScript automatically appends | undefined to any indexed access type. It forces you to check if the item actually exists before using it.</p><pre>const names: string[] = [&quot;Alice&quot;, &quot;Bob&quot;];<br>const thirdName = names[2]; // TypeScript says this is &#39;string | undefined&#39;<br><br>if (thirdName) {<br>  console.log(thirdName.toUpperCase()); // Safe!<br>}</pre><h3>2. exactOptionalPropertyTypes</h3><p>Handling optional properties can be tricky. Historically, TypeScript treated an optional property (name?: string) as equivalent to name: string | undefined. But conceptually, a property being <em>missing</em> is not the same as a property being explicitly set to <em>undefined</em>.</p><p><strong>Without the flag:</strong></p><pre>interface User {<br>  username: string;<br>  bio?: string;<br>}<br><br>const user: User = {<br>  username: &quot;johndoe&quot;,<br>  bio: undefined // TypeScript allows this<br>};</pre><p><strong>With </strong><strong>exactOptionalPropertyTypes enabled:</strong> TypeScript will enforce that you either omit the optional property entirely or provide a value of the exact specified type (in this case, string). This prevents your database or API payloads from being cluttered with explicit undefined keys, leading to cleaner and more predictable data structures.</p><h3>3. noImplicitOverride</h3><p>If you use object-oriented programming patterns, this flag is a lifesaver. When extending classes, it’s easy to accidentally break a subclass when a method in the parent class is renamed or removed.</p><p><strong>Without the flag:</strong></p><pre>class Animal {<br>  makeSound() { /* ... */ }<br>}<br><br>class Dog extends Animal {<br>  makeSound() { /* ... */ } // Overrides parent method<br>}</pre><p>If someone renames makeSound to speak in the Animal class, the Dog class will silently stop overriding the parent method. Dog.makeSound() becomes a brand new, disconnected method.</p><p><strong>With </strong><strong>noImplicitOverride enabled:</strong> You are forced to use the override keyword when overriding parent methods.</p><pre>class Dog extends Animal {<br>  override makeSound() { /* ... */ } <br>}</pre><p>Now, if the parent class changes, TypeScript will throw a build error, immediately alerting you that override makeSound() is trying to override a method that no longer exists.</p><h3>4. noPropertyAccessFromIndexSignature</h3><p>TypeScript allows you to define “dictionaries” using index signatures, like Record&lt;string, string&gt;. By default, you can access these dynamic properties using dot notation (obj.key), which blurs the line between well-defined object properties and dynamic data.</p><p><strong>Without the flag:</strong></p><pre>interface AppSettings {<br>  theme: string;<br>  [key: string]: string; // Index signature for dynamic settings<br>}<br><br>const settings: AppSettings = { theme: &quot;dark&quot; };<br>console.log(settings.tehme); // Typo! But TypeScript allows it, returning &#39;string&#39;</pre><p><strong>With </strong><strong>noPropertyAccessFromIndexSignature enabled:</strong> TypeScript forces you to use bracket notation (obj[&#39;key&#39;]) for any property not explicitly defined in the interface. Dot notation is strictly reserved for known, statically typed properties.</p><pre>console.log(settings.tehme); // TypeScript Error: Property &#39;tehme&#39; comes from an index signature...<br>console.log(settings[&quot;tehme&quot;]); // Allowed, but visually flags it as dynamic access</pre><h3>5. noFallthroughCasesInSwitch</h3><p>Switch statements are notorious for causing bugs when a developer forgets to add a break or return statement, causing the code execution to &quot;fall through&quot; to the next case unintentionally.</p><p><strong>Without the flag:</strong></p><pre>let state = &quot;loading&quot;;<br><br>switch (state) {<br>  case &quot;loading&quot;:<br>    console.log(&quot;Loading...&quot;);<br>    // Oops, forgot &#39;break&#39; here!<br>  case &quot;success&quot;:<br>    console.log(&quot;Success!&quot;);<br>    break;<br>}<br>// Prints both &quot;Loading...&quot; and &quot;Success!&quot;</pre><p><strong>With </strong><strong>noFallthroughCasesInSwitch enabled:</strong> TypeScript acts as a strict linter during the build process. If a case contains code but lacks a break or return, the compiler will throw an error. (Note: Empty cases that fall through intentionally to group logic are still allowed).</p><h3>The Takeaway</h3><p>TypeScript is incredibly powerful, but its true potential is unlocked only when you tighten the screws on the compiler. By adding these 5 flags to your tsconfig.json, you shift a massive amount of debugging from runtime to build time:</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;strict&quot;: true,<br>    &quot;noUncheckedIndexedAccess&quot;: true,<br>    &quot;exactOptionalPropertyTypes&quot;: true,<br>    &quot;noImplicitOverride&quot;: true,<br>    &quot;noPropertyAccessFromIndexSignature&quot;: true,<br>    &quot;noFallthroughCasesInSwitch&quot;: true<br>  }<br>}</pre><p>Your team might groan at first because the compiler will start yelling at them more often. But in the long run? They’ll thank you for the bugs that never made it to production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fadaf0109f88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Advanced TypeScript Utility Types to Level Up Your Type Safety]]></title>
            <link>https://medium.com/@jradzik4/5-advanced-typescript-utility-types-to-level-up-your-type-safety-386dcb24756b?source=rss-fe30da5ee536------2</link>
            <guid isPermaLink="false">https://medium.com/p/386dcb24756b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typescript-utility-types]]></category>
            <dc:creator><![CDATA[Jakub Radzik]]></dc:creator>
            <pubDate>Mon, 23 Feb 2026 15:49:00 GMT</pubDate>
            <atom:updated>2026-02-23T15:49:00.516Z</atom:updated>
            <content:encoded><![CDATA[<p>TypeScript’s built-in utilities like Pick and Omit are great, but they only scratch the surface. If you want to build truly robust, self-documenting architectures, you need to master the art of type transformation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Rvtr1MMqZkxAafR1" /><figcaption>Photo by <a href="https://unsplash.com/@max010?utm_source=medium&amp;utm_medium=referral">Danil Shostak</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Input validation is only half the battle. Once data enters your system, how you handle it determines whether your codebase remains a “clean room” or becomes a “spaghetti factory.” While TypeScript’s structural typing is flexible, it can sometimes be <em>too</em> flexible, leading to “Primitive Obsession” or runtime errors that the compiler should have caught.</p><p>In this article, we’ll explore <strong>5 advanced Utility Types</strong> that solve real-world architectural headaches, from recursive object updates to type-safe URL parsing.</p><h3>1. The “DeepPartial” Pattern: Mastering Nested Updates</h3><p>The standard Partial&lt;T&gt; is shallow. It makes top-level keys optional, but if you have a nested object, those sub-properties remain required. This is a nightmare for update() methods in services.</p><pre>type DeepPartial&lt;T&gt; = {<br>  [P in keyof T]?: T[P] extends (infer U)[]<br>    ? DeepPartial&lt;U&gt;[]<br>    : T[P] extends object<br>    ? DeepPartial&lt;T[P]&gt;<br>    : T[P];<br>};<br><br>// --- Example ---<br>interface UserSettings {<br>  theme: string;<br>  notifications: {<br>    email: boolean;<br>    push: boolean;<br>  };<br>}<br><br>// Standard Partial would fail if you only wanted to update { notifications: { email: true } }<br>const update: DeepPartial&lt;UserSettings&gt; = {<br>  notifications: {<br>    email: true <br>  }<br>};</pre><p><strong>Why it’s robust:</strong> It ensures your update DTOs (Data Transfer Objects) are perfectly mapped to your nested entities without manual interface duplication.</p><h3>2. The “Dot-Notation Path” Pattern: Type-Safe Nested Keys</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*46nnXcl6T2jRT0N7" /><figcaption>Photo by <a href="https://unsplash.com/@syinq?utm_source=medium&amp;utm_medium=referral">Susan Q Yin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Have you ever used a library like react-hook-form or an i18n tool and wished the string paths (like &quot;user.address.city&quot;) were type-checked? This pattern transforms a nested object into a union of all possible string paths.</p><pre>type Path&lt;T&gt; = T extends object ? { [K in keyof T]: <br>  K extends string | number ?<br>    `${K}` | `${K}.${Path&lt;T[K]&gt;}`<br>    : never<br>}[keyof T] : never;<br><br>// --- Example ---<br>interface Config {<br>  db: { host: string; port: number };<br>  api: { key: string };<br>}<br><br>function getConfigValue(path: Path&lt;Config&gt;) { ... }<br><br>getConfigValue(&quot;db.host&quot;); // ✅ Valid<br>getConfigValue(&quot;db.password&quot;); // ❌ TypeScript Error: Property does not exist</pre><h3>3. The “Branded Primitive” Pattern: Killing Primitive Obsession</h3><p>In a large app, a UserId, ProductId, and OrderId are often just string. Passing a UserId into a function that expects a ProductId is a classic bug that standard TypeScript won’t catch.</p><pre>type Brand&lt;K, T&gt; = T &amp; { __brand: K };<br><br>type UserId = Brand&lt;&quot;UserId&quot;, string&gt;;<br>type ProductId = Brand&lt;&quot;ProductId&quot;, string&gt;;<br><br>const getUser = (id: UserId) =&gt; { ... };<br><br>const myProductId = &quot;prod_123&quot; as ProductId;<br><br>// @ts-expect-error: Argument of type &#39;ProductId&#39; is not assignable to &#39;UserId&#39;<br>getUser(myProductId);</pre><p><strong>Why it’s robust:</strong> It adds “nominal typing” to TypeScript, forcing you to explicitly validate or cast values before using them in sensitive logic.</p><h3>4. The “ExtractRouteParams” Pattern: Magic URL Parsing</h3><p>Modern frameworks like Next.js or Express use string routes. You can actually use TypeScript to parse those strings and extract the parameters as a type.</p><pre>type ExtractRouteParams&lt;T extends string&gt; =<br>  T extends `${string}:${infer Param}/${infer Rest}`<br>    ? Param | ExtractRouteParams&lt;Rest&gt;<br>    : T extends `${string}:${infer Param}`<br>    ? Param<br>    : never;<br><br>// --- Example ---<br>const API_ROUTE = &quot;/api/users/:userId/posts/:postId&quot; as const;<br><br>type RouteParams = ExtractRouteParams&lt;typeof API_ROUTE&gt;; <br>// Result: &quot;userId&quot; | &quot;postId&quot;<br><br>function getParam(name: RouteParams) { ... }</pre><h3>5. The “RequiredKeys” Pattern: Metadata Extraction</h3><p>Sometimes you need to know exactly which keys of an object are mandatory — for example, to dynamically generate a UI form where only required fields have an asterisk (*).</p><pre>type RequiredKeys&lt;T&gt; = {<br>  [K in keyof T]-?: {} extends Pick&lt;T, K&gt; ? never : K;<br>}[keyof T];<br><br>// --- Example ---<br>interface Project {<br>  id: string;      // Required<br>  title: string;   // Required<br>  description?: string; // Optional<br>}<br><br>type Mandatory = RequiredKeys&lt;Project&gt;; <br>// Result: &quot;id&quot; | &quot;title&quot;</pre><h3>Conclusion: Code that Teaches Itself</h3><p>Advanced Utility Types aren’t just about “showing off.” They are about reducing the mental overhead for every developer on your team. When the IDE tells you exactly what a nested path should be, or prevents you from swapping a User ID with a Product ID, you spend less time debugging and more time building.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J9BWqBjfsYqhOVKk" /><figcaption>Photo by <a href="https://unsplash.com/@artchicago?utm_source=medium&amp;utm_medium=referral">Art Institute of Chicago</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=386dcb24756b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authentication in NestJS — JWT and Refresh Tokens]]></title>
            <link>https://medium.com/@jradzik4/authentication-in-nestjs-jwt-and-refresh-tokens-c44b7e715709?source=rss-fe30da5ee536------2</link>
            <guid isPermaLink="false">https://medium.com/p/c44b7e715709</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[refresh-token]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Jakub Radzik]]></dc:creator>
            <pubDate>Fri, 20 Feb 2026 12:21:01 GMT</pubDate>
            <atom:updated>2026-02-20T12:21:01.047Z</atom:updated>
            <content:encoded><![CDATA[<p>Authentication is one of those essential yet tricky parts of building modern web applications. Whether you’re building a simple blog, an e-commerce store, or a full-fledged social media app, ensuring your users can securely log in and maintain their session is crucial. NestJS, with its powerful modular architecture, makes implementing robust authentication straightforward and scalable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RzwZXB97rHKBpJVc" /><figcaption>Photo by <a href="https://unsplash.com/@edhardie?utm_source=medium&amp;utm_medium=referral">Ed Hardie</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you’re a developer or tech enthusiast wanting to dive into secure authentication in NestJS, particularly using JWT (JSON Web Tokens) and refresh tokens, this article is for you. We’ll break down the concepts, why they matter, and how to implement them in your NestJS apps step-by-step.</p><h4>Why JWT and Refresh Tokens Matter in Authentication</h4><p>Traditional session-based authentication relies on server-side sessions, which can get cumbersome when you need your app to scale or when you have multiple frontends or microservices. JWT offers a stateless, compact, and secure way to represent user information that can be verified easily without hitting a database on every request.</p><p>The catch? JWTs are usually short-lived to reduce risk exposure. Once they expire, users need to log in again — which harms user experience. That’s where refresh tokens come in: they’re long-lived and allow users to seamlessly get new access tokens without re-authenticating, adding both security and convenience.</p><p>Imagine an online bookstore. When a user logs in, your app issues a JWT valid for 15 minutes and a refresh token valid for 7 days. The access token lets the user browse the catalog and place orders without repeatedly entering credentials. Once the access token expires, the refresh token is used behind the scenes to get a new one, keeping the session smooth and secure.</p><h4>Setting Up JWT Authentication in NestJS</h4><p>NestJS has a terrific @nestjs/jwt package that makes working with JWTs intuitive. Here’s how to set up basic JWT authentication.</p><p>1. <strong>Install Dependencies:</strong></p><pre>npm install @nestjs/jwt @nestjs/passport passport passport-jwt bcrypt</pre><p>2. <strong>Create an AuthModule:</strong></p><p>The module will handle authentication logic and token generation. Here’s a simplified implementation:</p><pre>// auth.service.ts<br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { JwtService } from &#39;@nestjs/jwt&#39;;<br>import * as bcrypt from &#39;bcrypt&#39;;<br><br>@Injectable()<br>export class AuthService {<br> constructor(private jwtService: JwtService) {}<br><br> // This simulates user validation - replace with real DB calls<br> async validateUser(username: string, pass: string): Promise&lt;any&gt; {<br>   const user = { username: &#39;john&#39;, passwordHash: await bcrypt.hash(&#39;changeme&#39;, 10) }; // mock user<br>   <br>   const isMatch = await bcrypt.compare(pass, user.passwordHash);<br>   <br>   if (user &amp;&amp; isMatch) {<br>     const { passwordHash, …result } = user;<br>     return result;<br>   }<br>   return null;<br> }<br><br> async login(user: any) {<br>   const payload = { username: user.username };<br>  <br>   return {<br>     access_token: this.jwtService.sign(payload, { expiresIn: &#39;15m&#39; }),<br>   };<br> }<br>}</pre><p>This service validates a user and creates a JWT token with a 15-minute expiration. In a real app, you’d query your database instead of hardcoding the user.</p><h4>Adding Refresh Tokens for a Seamless User Experience</h4><p>While the short-lived JWT access token keeps your app secure, users shouldn’t have to log in every time it expires. That’s where refresh tokens shine.</p><p><strong>How does it work?</strong></p><ul><li>When users log in, issue both an access token and a refresh token</li><li>The access token is used in most API requests</li><li>When the access token expires, your frontend calls a refresh endpoint with the refresh token</li><li>Your backend verifies the refresh token, then issues new tokens</li></ul><p>Because refresh tokens usually have a longer expiration (like 7 days), users stay logged in without constant prompts.</p><p><strong>Example snippet for issuing a refresh token:</strong></p><pre>// auth.service.ts (continued)<br>async login(user: any) {<br> const payload = { username: user.username };<br> const accessToken = this.jwtService.sign(payload, { expiresIn: &#39;15m&#39; });<br> const refreshToken = this.jwtService.sign(payload, { expiresIn: &#39;7d&#39; });<br> // In a real app, store refresh token securely (DB, Redis)<br> return {<br> access_token: accessToken,<br> refresh_token: refreshToken,<br> };<br>}<br><br>async refreshTokens(token: string) {<br> try {<br>   const payload = this.jwtService.verify(token);<br>   const newAccessToken = this.jwtService.sign({ username: payload.username }, { expiresIn: &#39;15m&#39; });<br>   const newRefreshToken = this.jwtService.sign({ username: payload.username }, { expiresIn: &#39;7d&#39; });<br>   <br>   return {<br>     access_token: newAccessToken,<br>     refresh_token: newRefreshToken,<br>   };<br> } catch (e) {<br>   throw new UnauthorizedException(&#39;Invalid refresh token&#39;);<br> }<br>}</pre><p>In this example, when your frontend calls a <em>/refresh</em> endpoint with a refresh token, you verify it, then issue new tokens. Remember, refresh tokens should be stored securely and optionally revoked if compromised.</p><h3>Practical Tips for Securing and Managing Tokens</h3><ul><li><strong>Store refresh tokens securely:</strong> On the client side, HttpOnly cookies are safer than local storage. On the server side, keep track of issued refresh tokens using a database or cache so you can revoke them if needed.</li><li><strong>Use HTTPS:</strong> Always serve your app over HTTPS to prevent token interception.</li><li><strong>Set proper expirations:</strong> Access tokens should be short-lived (minutes) and refresh tokens longer (days or weeks).</li><li><strong>Invalidate refresh tokens:</strong> Invalidate or blacklist tokens when users log out or change their password.</li><li><strong>Guard routes:</strong> In NestJS, use Guards to protect routes that require valid access tokens.</li></ul><p>Example of a route guard using JWT in NestJS:</p><pre>// jwt-auth.guard.ts<br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { AuthGuard } from &#39;@nestjs/passport&#39;;<br>@Injectable()<br>export class JwtAuthGuard extends AuthGuard(&#39;jwt&#39;) {}</pre><p>Then protect your controller routes like this:</p><pre>import { Controller, Get, UseGuards } from &#39;@nestjs/common&#39;;<br><br>@Controller(&#39;profile&#39;)<br>export class ProfileController {<br><br> @UseGuards(JwtAuthGuard)<br> @Get()<br> getProfile() {<br>   return { message: &#39;This route is protected with JWT&#39; };<br> }<br>}</pre><h3>Conclusion</h3><p>Implementing authentication with JWTs and refresh tokens in NestJS not only improves your app’s security but also delivers a smooth user experience. By issuing short-lived access tokens and longer-lived refresh tokens, you balance security with convenience — ensuring users stay logged in while minimizing risk.</p><h4>Next steps:</h4><ul><li>Try implementing the login and refresh token mechanism in a simple NestJS app</li><li>Explore storing refresh tokens safely (e.g., in Redis) and revoking them</li><li>Combine your JWT authentication with Passport strategies for social logins</li></ul><p>With these basics under your belt, you’ll be well-equipped to secure your NestJS applications confidently!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c44b7e715709" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[6 Advanced “as const” Patterns to Make Your TS Enums More Powerful]]></title>
            <link>https://medium.com/@jradzik4/6-advanced-as-const-patterns-to-make-your-ts-enums-more-powerful-f725a53eba78?source=rss-fe30da5ee536------2</link>
            <guid isPermaLink="false">https://medium.com/p/f725a53eba78</guid>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Jakub Radzik]]></dc:creator>
            <pubDate>Wed, 18 Feb 2026 11:09:17 GMT</pubDate>
            <atom:updated>2026-02-18T11:09:17.995Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction: The Enum Conundrum<br></strong>Enums are a beloved (and sometimes debated) feature in TypeScript. They offer a way to group related constants, improving readability and preventing “magic strings.”</p><pre>// Traditional TypeScript Enum<br>enum UserRole {<br>  ADMIN = &quot;ADMIN&quot;,<br>  EDITOR = &quot;EDITOR&quot;,<br>  VIEWER = &quot;VIEWER&quot;,<br>}<br><br>function hasPermissions(role: UserRole) {<br>  // ...<br>}<br><br>hasPermissions(UserRole.ADMIN); // Works<br>hasPermissions(&quot;ADMIN&quot;);       // Error! Good!</pre><p>But traditional enums come with a few quirks: they generate extra JavaScript code at runtime, and their behavior can sometimes be less flexible than pure literal types.</p><p>Enter as const. This powerful TypeScript keyword, when applied to arrays or objects, tells the compiler to infer the narrowest possible type for its contents. Instead of inferring string[] or Record&lt;string, string&gt;, it infers precise literal types. This seemingly small detail unlocks a whole new universe of enum-like patterns that are often more flexible, type-safe, and even runtime-efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IRXoLlX1YMIsec7j" /><figcaption>Photo by <a href="https://unsplash.com/@michaelafreshideas?utm_source=medium&amp;utm_medium=referral">Michaela J</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. The “Tuple as Enum” Pattern: Zero Runtime Overhead</h3><p><strong>The Problem:</strong> Traditional string enums compile to JavaScript objects, adding a small amount of runtime overhead. Sometimes you just need a list of literal types without the extra JS bundle size.<strong>The Solution:</strong> Use an as const tuple (an array of fixed length with specific types).</p><pre>// ❌ Traditional Enum (adds JS runtime code)<br>enum HttpStatus {<br>  OK = 200,<br>  NOT_FOUND = 404,<br>}<br><br>// ✅ &#39;as const&#39; Tuple (zero runtime JS code for the enum itself)<br>const HTTP_STATUS_CODES = [200, 400, 404, 500] as const;<br><br>type HttpStatusCode = typeof HTTP_STATUS_CODES[number];<br>// type HttpStatusCode = 200 | 400 | 404 | 500<br><br>function getStatusMessage(code: HttpStatusCode) {<br>  switch (code) {<br>    case 200: return &quot;OK&quot;;<br>    case 404: return &quot;Not Found&quot;;<br>    // ...<br>  }<br>}<br><br>getStatusMessage(HTTP_STATUS_CODES[0]); // Works!<br>getStatusMessage(200);                  // Works!<br>// getStatusMessage(201);               // Error! Perfect!</pre><p><strong>Why it’s powerful:</strong></p><ul><li><strong>Zero JS Output:</strong> The HTTP_STATUS_CODES constant becomes a simple array in JavaScript, but HttpStatusCode provides strict type checking <em>at compile time</em>.</li><li><strong>Flexibility:</strong> Easily iterate over HTTP_STATUS_CODES at runtime.</li></ul><h3>2. The “Object as Enum” Pattern: Key-Value Type Safety</h3><p><strong>The Problem:</strong> You want a key-value pair structure where both the keys <em>and</em> the values are strictly typed as literals, similar to a string enum but with more flexibility.<strong>The Solution:</strong> An as const object allows you to define a set of related literal values.</p><pre>// ✅ &#39;as const&#39; Object<br>const USER_ROLES = {<br>  ADMIN: &quot;admin_user&quot;,<br>  EDITOR: &quot;editor_user&quot;,<br>  VIEWER: &quot;viewer_user&quot;,<br>} as const;<br><br>type UserRoleKey = keyof typeof USER_ROLES;<br>// type UserRoleKey = &quot;ADMIN&quot; | &quot;EDITOR&quot; | &quot;VIEWER&quot;<br><br>type UserRoleValue = typeof USER_ROLES[keyof typeof USER_ROLES];<br>// type UserRoleValue = &quot;admin_user&quot; | &quot;editor_user&quot; | &quot;viewer_user&quot;<br><br>function assignRole(role: UserRoleValue) {<br>  console.log(`Assigning role: ${role}`);<br>}<br><br>assignRole(USER_ROLES.ADMIN);    // Works!<br>assignRole(&quot;admin_user&quot;);       // Also works (UserRoleValue allows this literal)<br>// assignRole(&quot;super_admin&quot;);   // Error! Nice!</pre><p><strong>Why it’s powerful:</strong></p><ul><li><strong>Dual Type Safety:</strong> You get type safety for both the “keys” (like ADMIN) and the &quot;values&quot; (like admin_user).</li><li><strong>Runtime Access:</strong> USER_ROLES is a plain JavaScript object at runtime, making it easy to access values like USER_ROLES.ADMIN.</li></ul><h3>3. The “Action Union” Pattern: Redux-Style Action Creators</h3><p><strong>The Problem:</strong> In state management (like Redux), you often define action types and then action objects. Ensuring consistency between the string literal type and the action creator is crucial.<strong>The Solution:</strong> Use as const within an object to define action types, then derive a union of action <em>objects</em>.</p><pre>const ActionTypes = {<br>  ADD_TODO: &quot;ADD_TODO&quot;,<br>  TOGGLE_TODO: &quot;TOGGLE_TODO&quot;,<br>  DELETE_TODO: &quot;DELETE_TODO&quot;,<br>} as const;<br><br>type ActionType = typeof ActionTypes[keyof typeof ActionTypes];<br>// type ActionType = &quot;ADD_TODO&quot; | &quot;TOGGLE_TODO&quot; | &quot;DELETE_TODO&quot;<br><br>interface AddTodoAction {<br>  type: typeof ActionTypes.ADD_TODO; // Ensures correct literal string<br>  payload: string;<br>}<br><br>interface ToggleTodoAction {<br>  type: typeof ActionTypes.TOGGLE_TODO;<br>  payload: number; // todoId<br>}<br><br>type TodoAction = AddTodoAction | ToggleTodoAction;<br><br>function handleTodoAction(action: TodoAction) {<br>  if (action.type === ActionTypes.ADD_TODO) {<br>    console.log(`Adding: ${action.payload}`);<br>  } else if (action.type === ActionTypes.TOGGLE_TODO) {<br>    console.log(`Toggling: ${action.payload}`);<br>  }<br>}</pre><p><strong>Why it’s powerful:</strong></p><ul><li><strong>Guaranteed Consistency:</strong> typeof ActionTypes.ADD_TODO ensures that your action object&#39;s type property is always a specific string literal, not just string.</li><li><strong>Discriminant Unions:</strong> This sets up powerful discriminated unions for TodoAction, allowing TypeScript to narrow types based on action.type.</li></ul><h3>4. The “Strict Configuration Options” Pattern</h3><p><strong>The Problem:</strong> You have a configuration object where certain properties should only accept a predefined set of literal values.<strong>The Solution:</strong> Combine as const with object definitions and union types.</p><pre>const LogLevels = [&quot;info&quot;, &quot;warn&quot;, &quot;error&quot;, &quot;debug&quot;] as const;<br>type LogLevel = typeof LogLevels[number];<br>// type LogLevel = &quot;info&quot; | &quot;warn&quot; | &quot;error&quot; | &quot;debug&quot;<br><br>interface AppConfig {<br>  appName: string;<br>  logLevel: LogLevel;<br>  features: {<br>    darkMode: boolean;<br>    analytics: boolean;<br>    enabledModules: readonly string[]; // Just an example of another readonly type<br>  };<br>}<br><br>const defaultConfig: AppConfig = {<br>  appName: &quot;My Awesome App&quot;,<br>  logLevel: &quot;info&quot;, // Must be one of LogLevel<br>  features: {<br>    darkMode: true,<br>    analytics: false,<br>    enabledModules: [&quot;users&quot;, &quot;products&quot;]<br>  }<br>};<br><br>// const invalidConfig: AppConfig = {<br>//   ...defaultConfig,<br>//   logLevel: &quot;critical&quot;, // Error! Property &#39;&quot;critical&quot;&#39; is not assignable...<br>// };</pre><p><strong>Why it’s powerful:</strong></p><ul><li><strong>Prevents Typos:</strong> No more silently accepting loglevel: &quot;infO&quot; or loglevel: &quot;warning&quot;.</li><li><strong>Read-Only Defaults:</strong> If defaultConfig itself were as const, all its properties would become readonly, ensuring your default config isn&#39;t accidentally mutated.</li></ul><h3>5. The “Polymorphic Component Prop” Pattern (React/Vue Example)</h3><p><strong>The Problem:</strong> Building a flexible UI component whose behavior or rendering changes based on a specific “variant” prop, and you want strong type checking for the variant and related props.<strong>The Solution:</strong> Define your component variants using as const and then use a discriminated union for props.</p><pre>const ButtonVariants = [&quot;primary&quot;, &quot;secondary&quot;, &quot;ghost&quot;] as const;<br>type ButtonVariant = typeof ButtonVariants[number];<br>// type ButtonVariant = &quot;primary&quot; | &quot;secondary&quot; | &quot;ghost&quot;<br><br>interface BaseButtonProps {<br>  onClick: () =&gt; void;<br>  children: React.ReactNode;<br>}<br><br>interface PrimaryButtonProps extends BaseButtonProps {<br>  variant: &quot;primary&quot;;<br>  emphasis: &quot;high&quot; | &quot;low&quot;;<br>}<br><br>interface SecondaryButtonProps extends BaseButtonProps {<br>  variant: &quot;secondary&quot;;<br>  icon?: string;<br>}<br><br>interface GhostButtonProps extends BaseButtonProps {<br>  variant: &quot;ghost&quot;;<br>  isUnderline?: boolean;<br>}<br><br>type ButtonProps = PrimaryButtonProps | SecondaryButtonProps | GhostButtonProps;<br><br>function Button(props: ButtonProps) {<br>  // TypeScript knows what specific props are available based on props.variant<br>  if (props.variant === &quot;primary&quot;) {<br>    // props.emphasis is available here<br>    return &lt;button className={`btn-${props.variant}-${props.emphasis}`} onClick={props.onClick}&gt;{props.children}&lt;/button&gt;;<br>  }<br>  // ... other variants<br>  return &lt;button className={`btn-${props.variant}`} onClick={props.onClick}&gt;{props.children}&lt;/button&gt;;<br>}<br><br>// ✅ Correct usage<br>const MyButton = () =&gt; (<br>  &lt;Button variant=&quot;primary&quot; emphasis=&quot;high&quot; onClick={() =&gt; alert(&quot;clicked&quot;)}&gt;<br>    Click Me<br>  &lt;/Button&gt;<br>);<br><br>// ❌ Incorrect usage (emphasis not allowed on secondary)<br>// const MyBadButton = () =&gt; (<br>//   &lt;Button variant=&quot;secondary&quot; emphasis=&quot;low&quot; onClick={() =&gt; alert(&quot;clicked&quot;)}&gt;<br>//     Click Me<br>//   &lt;/Button&gt;<br>// );</pre><p><strong>Why it’s powerful:</strong></p><ul><li><strong>Contextual Type Safety:</strong> TypeScript ensures that when you choose a variant, only the relevant props for that variant are allowed.</li><li><strong>Refactor-Proof:</strong> If you rename a variant, TypeScript will catch all usages.</li></ul><h3>6. The “Deeply Nested Immutable Object” Pattern</h3><p><strong>The Problem:</strong> You have a complex, deeply nested configuration or data structure — like a theme object, a set of action constants, or a permissions tree. In standard TypeScript, even if you define the variable with const, the nested properties are still mutable. If you pass this object into a function, a junior dev (or a late-night version of yourself) could accidentally overwrite a value, leading to bugs that are notoriously hard to track down.</p><p><strong>The Solution:</strong> Apply as const to the root of the entire object. This is known as a <strong>Const Assertion</strong>. It signals to the compiler that every single property—no matter how deep—is readonly and that literals (like the string &quot;ADMIN&quot;) should be treated as their exact values, not just generic string types.</p><pre>const APP_CONFIG = {<br>  api: {<br>    base: &quot;https://api.example.com&quot;,<br>    version: &quot;v1&quot;,<br>    endpoints: {<br>      users: &quot;/users&quot;,<br>      posts: &quot;/posts&quot;<br>    }<br>  },<br>  roles: [&quot;ADMIN&quot;, &quot;USER&quot;, &quot;GUEST&quot;]<br>} as const;<br><br>// This will now throw a compile-time error!<br>APP_CONFIG.api.version = &quot;v2&quot;; <br><br>// TypeScript knows exactly what this value is, not just &#39;string&#39;<br>type AppRoles = typeof APP_CONFIG.roles[number]; // &quot;ADMIN&quot; | &quot;USER&quot; | &quot;GUEST&quot;</pre><h3>Conclusion: Choosing Your Tool Wisely</h3><p>While traditional enum has its place in the TypeScript ecosystem, the power of <strong>const assertions</strong> (as const) lies in their transparency and zero-runtime footprint. By moving away from custom TypeScript constructs toward native JavaScript structures enhanced by literal types, you write code that is:</p><ul><li><strong>Lighter:</strong> No extra functions or objects generated in your final .js bundle.</li><li><strong>Predictable:</strong> What you see in your object is exactly what the type system sees.</li><li><strong>Flexible:</strong> Easily convertible to unions, keys, or values without manual duplication.</li></ul><h3>Which one should you use?</h3><ul><li><strong>Tuple as Enum — </strong>Simple, ordered lists of values (like Status Codes)</li><li><strong>Object as Enum — </strong>When you need meaningful keys for your values (like Roles)</li><li><strong>Action Unions — </strong>Redux-style logic where type-safety in dispatching is key</li><li><strong>Strict Configs — </strong>Preventing “string soup” in your application settings</li><li><strong>Polymorphic Props — </strong>Complex UI components with conditional logic</li><li><strong>Deeply Nested — </strong>Large theme objects or API trees that must remain immutable.</li></ul><h3>Final Thoughts</h3><p>TypeScript is at its best when it gets out of your way at runtime while providing a “safety net” at compile time. The as const pattern is the ultimate expression of this philosophy. Next time you reach for enum, ask yourself: <em>Could a const-asserted object do this better?</em> In most modern TypeScript projects, the answer is a resounding <strong>yes</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f725a53eba78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[6 Zod Schema Patterns to Make Your Input Validation 10x More Robust]]></title>
            <link>https://medium.com/@jradzik4/6-zod-schema-patterns-to-make-your-input-validation-10x-more-robust-ffe0eab11b87?source=rss-fe30da5ee536------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffe0eab11b87</guid>
            <category><![CDATA[zod]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Jakub Radzik]]></dc:creator>
            <pubDate>Sun, 15 Feb 2026 08:09:28 GMT</pubDate>
            <atom:updated>2026-02-15T08:09:28.465Z</atom:updated>
            <content:encoded><![CDATA[<p>Input validation is the unsung hero of robust applications. Without it, your carefully crafted NestJS services or Node.js APIs are just an open door to corrupted data, unexpected errors, and security vulnerabilities. While libraries like Joi and Yup have served us well, <strong>Zod</strong> has emerged as a modern, TypeScript-first schema declaration and validation library that truly levels up your development experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uUOQ0-7aczQh3bqH" /><figcaption>Photo by <a href="https://unsplash.com/@codzilla_swiss?utm_source=medium&amp;utm_medium=referral">AbsolutVision</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>But Zod is more than just a string().email()checker. Its true power lies in its advanced patterns, which can tackle complex data structures and common architectural headaches with elegant, type-safe solutions.</p><p>In this article, we’ll dive into <strong>6 Zod schema patterns</strong> that will transform your input validation from basic checks into an unyielding fortress, making your applications significantly more robust and your developer life a whole lot easier.</p><h3>Why Zod? A Quick Recap</h3><p>Before we jump into the patterns, let’s quickly touch on why Zod has gained so much traction:</p><ol><li><strong>TypeScript-First:</strong> It infers types directly from your schemas, providing unparalleled type safety throughout your application.</li><li><strong>Developer Experience:</strong> Clear, readable syntax and helpful error messages.</li><li><strong>Performance:</strong> Optimized for speed, especially with safeParse.</li><li><strong>Versatile:</strong> Handles everything from basic strings to complex nested objects and discriminated unions.</li></ol><h3>1. The “Discriminated Union” Pattern: Handling Polymorphic Data</h3><p>Many applications deal with data that changes shape based on a specific field. Think of a payment request: if the method is &quot;credit card,&quot; you need card details; if it&#39;s &quot;PayPal,&quot; you need an email. Imperative if/else checks quickly become messy and error-prone.</p><p>Zod’s z.discriminatedUnion() is built precisely for this. It allows you to define multiple schemas, and Zod intelligently picks the correct one based on a designated &quot;discriminator&quot; field.</p><pre>import { z } from &#39;zod&#39;;<br><br>// Define schemas for different payment methods<br>const CreditCardPaymentSchema = z.object({<br>  method: z.literal(&quot;credit_card&quot;),<br>  cardNumber: z.string().creditCard(&quot;Invalid credit card number&quot;),<br>  expiryDate: z.string().regex(/^\d{2}\/\d{2}$/, &quot;Invalid expiry date (MM/YY)&quot;),<br>  cvv: z.string().length(3, &quot;CVV must be 3 digits&quot;),<br>});<br><br>const PaypalPaymentSchema = z.object({<br>  method: z.literal(&quot;paypal&quot;),<br>  paypalEmail: z.string().email(&quot;Invalid PayPal email address&quot;),<br>});<br><br>const BankTransferPaymentSchema = z.object({<br>  method: z.literal(&quot;bank_transfer&quot;),<br>  accountNumber: z.string().min(8).max(17, &quot;Invalid account number length&quot;),<br>  routingNumber: z.string().length(9, &quot;Routing number must be 9 digits&quot;),<br>});<br><br>// Create the discriminated union<br>const PaymentSchema = z.discriminatedUnion(&quot;method&quot;, [<br>  CreditCardPaymentSchema,<br>  PaypalPaymentSchema,<br>  BankTransferPaymentSchema,<br>]);<br><br>type Payment = z.infer&lt;typeof PaymentSchema&gt;;<br><br>// --- Usage Examples ---<br><br>// Valid credit card payment<br>const validCardPayment: Payment = {<br>  method: &quot;credit_card&quot;,<br>  cardNumber: &quot;4111111111111111&quot;,<br>  expiryDate: &quot;12/25&quot;,<br>  cvv: &quot;123&quot;,<br>};<br>console.log(&quot;Valid Credit Card:&quot;, PaymentSchema.safeParse(validCardPayment).success); // true<br><br>// Valid PayPal payment<br>const validPaypalPayment: Payment = {<br>  method: &quot;paypal&quot;,<br>  paypalEmail: &quot;test@example.com&quot;,<br>};<br>console.log(&quot;Valid PayPal:&quot;, PaymentSchema.safeParse(validPaypalPayment).success); // true<br><br>// Invalid payment - missing field for credit card<br>const invalidCardPayment = {<br>  method: &quot;credit_card&quot;,<br>  cardNumber: &quot;4111111111111111&quot;,<br>  expiryDate: &quot;12/25&quot;,<br>  // cvv is missing!<br>};<br>console.log(&quot;Invalid (missing CVV):&quot;, PaymentSchema.safeParse(invalidCardPayment).success); // false<br><br>// Invalid payment - PayPal with credit card field<br>const invalidPaypalPayment = {<br>  method: &quot;paypal&quot;,<br>  paypalEmail: &quot;test@example.com&quot;,<br>  cardNumber: &quot;1234&quot;, // This field shouldn&#39;t be here for PayPal!<br>};<br>console.log(&quot;Invalid (extra field for PayPal):&quot;, PaymentSchema.safeParse(invalidPaypalPayment).success); // false</pre><p><strong>Why it’s robust:</strong> This pattern ensures that only relevant fields are present for a given type, eliminating logical errors and unexpected data shapes that often creep into applications handling dynamic data.</p><h3>2. The “Strict Environment Variable” Pattern: Bulletproof Configuration</h3><p>Environment variables (process.env in Node.js) are notoriously untyped strings. Misspellings, missing variables, or incorrect types (e.g., a port number as a string instead of a number) are common causes of production bugs.</p><p>Validate your environment variables <strong>once, at application startup</strong>, using Zod. This forces your app to fail fast and loudly if its configuration is incorrect, preventing subtle, hard-to-debug issues later.</p><pre>import { z } from &#39;zod&#39;;<br><br>// Define the schema for your environment variables<br>const EnvSchema = z.object({<br>  NODE_ENV: z.enum([&quot;development&quot;, &quot;production&quot;, &quot;test&quot;]).default(&quot;development&quot;),<br>  PORT: z.coerce.number().min(1024).max(65535).default(3000), // coerce ensures it&#39;s a number<br>  DATABASE_URL: z.string().url(https://medium.com/&quot;Invalid%20database%20URL%20format&quot;),<br>  API_KEY: z.string().min(1, &quot;API_KEY cannot be empty&quot;),<br>  FEATURE_FLAG_ANALYTICS: z.coerce.boolean().default(false), // coerce &quot;true&quot; | &quot;false&quot; to boolean<br>});<br><br>type Env = z.infer&lt;typeof EnvSchema&gt;;<br><br>// Validate and parse environment variables<br>// This should ideally run once at your application&#39;s entry point (e.g., main.ts)<br>export const env: Env = EnvSchema.parse(process.env);<br><br>// --- Example Usage (Conceptual - in your main app file) ---<br>// In a real app, you&#39;d assign process.env values to test this<br>// For demonstration, let&#39;s mock process.env<br>const mockProcessEnv = {<br>  NODE_ENV: &quot;production&quot;,<br>  PORT: &quot;8080&quot;, // Zod will coerce this to a number<br>  DATABASE_URL: &quot;postgresql://user:pass@host:5432/db&quot;,<br>  API_KEY: &quot;super-secret-key-123&quot;,<br>  FEATURE_FLAG_ANALYTICS: &quot;true&quot;, // Zod will coerce this to a boolean<br>};<br><br>try {<br>  const validatedEnv = EnvSchema.parse(mockProcessEnv);<br>  console.log(&quot;Environment variables are valid!&quot;);<br>  console.log(&quot;Port (number):&quot;, validatedEnv.PORT, typeof validatedEnv.PORT); // 8080, number<br>  console.log(&quot;Is Analytics enabled (boolean):&quot;, validatedEnv.FEATURE_FLAG_ANALYTICS, typeof validatedEnv.FEATURE_FLAG_ANALYTICS); // true, boolean<br><br>  // Test with invalid data<br>  const invalidMockEnv = {<br>    NODE_ENV: &quot;staging&quot;, // Not allowed by enum!<br>    PORT: &quot;abc&quot;, // Cannot coerce to number<br>    DATABASE_URL: &quot;not-a-url&quot;,<br>    API_KEY: &quot;&quot;, // Empty string<br>  };<br>  EnvSchema.parse(invalidMockEnv); // This would throw an error<br>} catch (error) {<br>  if (error instanceof z.ZodError) {<br>    console.error(&quot;Environment validation failed:&quot;, error.errors.map(e =&gt; e.message));<br>    // In a real application, you&#39;d likely exit the process here<br>    // process.exit(1);<br>  }<br>}</pre><p><strong>Why it’s robust:</strong> Catches critical configuration errors immediately, preventing runtime surprises and ensuring your application runs with the correct settings from the get-go.</p><h3>3. The “Branded Types” Pattern: Preventing Id Swaps and Enhancing Clarity</h3><p>Have you ever accidentally passed a userId where a productId was expected, or vice-versa, because both were just string types? TypeScript&#39;s structural typing allows this, but it can lead to subtle bugs.</p><p>Zod’s .brand&lt;T&gt;() method allows you to create &quot;branded&quot; or &quot;nominal&quot; types. This means that while the underlying type is still, say, a string, TypeScript will treat UserId and ProductId as distinct types, preventing accidental assignment errors.</p><pre>import { z } from &#39;zod&#39;;<br><br>// Define branded types for different IDs<br>const UserIdSchema = z.string().uuid(&quot;Invalid user ID format&quot;).brand&lt;&quot;UserId&quot;&gt;();<br>const ProductIdSchema = z.string().length(24, &quot;Invalid product ID length&quot;).brand&lt;&quot;ProductId&quot;&gt;();<br>const OrderIdSchema = z.string().regex(/^ORD-\d{6}$/, &quot;Invalid order ID format&quot;).brand&lt;&quot;OrderId&quot;&gt;();<br><br>type UserId = z.infer&lt;typeof UserIdSchema&gt;;<br>type ProductId = z.infer&lt;typeof ProductIdSchema&gt;;<br>type OrderId = z.infer&lt;typeof OrderIdSchema&gt;;<br><br>// A service function that expects specific IDs<br>function processOrder(userId: UserId, productId: ProductId, orderId: OrderId) {<br>  console.log(`Processing order ${orderId} for user ${userId} and product ${productId}`);<br>  // ... actual processing logic<br>}<br><br>// --- Usage Examples ---<br>const validUserId: UserId = UserIdSchema.parse(&quot;a1b2c3d4-e5f6-7890-1234-567890abcdef&quot;);<br>const validProductId: ProductId = ProductIdSchema.parse(&quot;654321098765432109876543&quot;);<br>const validOrderId: OrderId = OrderIdSchema.parse(&quot;ORD-123456&quot;);<br><br>processOrder(validUserId, validProductId, validOrderId);<br><br>// Attempting to pass the wrong type will result in a TypeScript error!<br>// const wrongOrder: OrderId = validUserId; // TypeScript error: Type &#39;UserId&#39; is not assignable to type &#39;OrderId&#39;.<br>// processOrder(validProductId, validUserId, validOrderId); // TypeScript error for argument types</pre><p><strong>Why it’s robust:</strong> Significantly improves type safety at compile-time, catching logic errors before your code even runs and making your API interfaces much clearer about expected parameters.</p><h3>4. The “Chained Refinements” Pattern: Complex, Contextual Validation</h3><p>Sometimes, validation logic depends on multiple fields or more complex business rules that simple Zod validators can’t express. Zod’s .refine() and .superRefine() methods allow you to add custom validation logic that runs after the base schema validation.</p><p>refine() is good for simple conditions, while superRefine() allows for multiple error messages and more complex logic.</p><pre>import { z } from &#39;zod&#39;;<br><br>// Example: User registration with conditional password rules<br>const UserRegistrationSchema = z.object({<br>  username: z.string().min(3, &quot;Username must be at least 3 characters&quot;),<br>  password: z.string().min(8, &quot;Password must be at least 8 characters&quot;),<br>  confirmPassword: z.string(),<br>  acceptTerms: z.boolean().refine(val =&gt; val === true, &quot;You must accept the terms and conditions&quot;),<br>}).refine(data =&gt; data.password === data.confirmPassword, {<br>  message: &quot;Passwords do not match&quot;,<br>  path: [&quot;confirmPassword&quot;], // Point error to confirmPassword field<br>});<br><br>// Example: Event creation with conditional end date<br>const EventSchema = z.object({<br>  title: z.string().min(5, &quot;Title too short&quot;),<br>  startDate: z.string().datetime(&quot;Invalid start date format&quot;),<br>  endDate: z.string().datetime(&quot;Invalid end date format&quot;).optional(), // Optional, but if present, must be after startDate<br>}).superRefine((data, ctx) =&gt; {<br>  if (data.endDate &amp;&amp; new Date(data.endDate) &lt; new Date(data.startDate)) {<br>    ctx.addIssue({<br>      code: z.ZodIssueCode.custom,<br>      message: &quot;End date cannot be before start date&quot;,<br>      path: [&quot;endDate&quot;],<br>    });<br>  }<br>});<br><br>// --- Usage Examples ---<br><br>// Valid registration<br>console.log(&quot;Valid Registration:&quot;, UserRegistrationSchema.safeParse({<br>  username: &quot;johndoe&quot;,<br>  password: &quot;StrongPassword123&quot;,<br>  confirmPassword: &quot;StrongPassword123&quot;,<br>  acceptTerms: true,<br>}).success); // true<br><br>// Invalid registration - passwords don&#39;t match<br>const invalidReg1 = UserRegistrationSchema.safeParse({<br>  username: &quot;janedoe&quot;,<br>  password: &quot;Password123&quot;,<br>  confirmPassword: &quot;DifferentPassword&quot;,<br>  acceptTerms: true,<br>});<br>console.log(&quot;Invalid (passwords mismatch):&quot;, invalidReg1.success, invalidReg1.error?.errors[0].message); // false, &quot;Passwords do not match&quot;<br><br>// Valid event<br>console.log(&quot;Valid Event:&quot;, EventSchema.safeParse({<br>  title: &quot;Team Meeting&quot;,<br>  startDate: &quot;2023-10-26T09:00:00Z&quot;,<br>  endDate: &quot;2023-10-26T10:00:00Z&quot;,<br>}).success); // true<br><br>// Invalid event - end date before start date<br>const invalidEvent1 = EventSchema.safeParse({<br>  title: &quot;Short Meeting&quot;,<br>  startDate: &quot;2023-10-27T10:00:00Z&quot;,<br>  endDate: &quot;2023-10-27T09:00:00Z&quot;,<br>});<br>console.log(&quot;Invalid (end date before start):&quot;, invalidEvent1.success, invalidEvent1.error?.errors[0].message); // false, &quot;End date cannot be before start date&quot;</pre><p><strong>Why it’s robust:</strong> Allows you to encode complex, context-dependent business rules directly into your schemas, centralizing validation logic and making your application’s data integrity bulletproof against nuanced edge cases.</p><h3>5. The “Schema Extends and Omit” Pattern: Reusing and Adapting Schemas</h3><p>It’s common to have slightly different validation requirements for different contexts (e.g., creating a resource vs. updating a resource). A create schema might require all fields, while an update schema might make all fields optional.</p><p>Instead of duplicating schemas, Zod allows you to reuse and adapt them with methods like .extend(), .omit(), .pick(), .partial(), and .merge().</p><pre>import { z } from &#39;zod&#39;;<br><br>// Base user schema<br>const BaseUserSchema = z.object({<br>  id: z.string().uuid(),<br>  name: z.string().min(2),<br>  email: z.string().email(),<br>  password: z.string().min(8),<br>  role: z.enum([&quot;admin&quot;, &quot;editor&quot;, &quot;viewer&quot;]).default(&quot;viewer&quot;),<br>  createdAt: z.string().datetime(),<br>  updatedAt: z.string().datetime(),<br>});<br><br>// --- Derived Schemas ---<br><br>// 1. Create User Schema: omit &#39;id&#39;, &#39;createdAt&#39;, &#39;updatedAt&#39;, and set default role<br>const CreateUserSchema = BaseUserSchema.omit({<br>  id: true,<br>  createdAt: true,<br>  updatedAt: true,<br>}).extend({<br>  // Override role to be required, or just confirm default<br>  role: z.enum([&quot;admin&quot;, &quot;editor&quot;, &quot;viewer&quot;]).default(&quot;viewer&quot;),<br>});<br>type CreateUserDto = z.infer&lt;typeof CreateUserSchema&gt;;<br><br>// 2. Update User Schema: all fields optional except for &#39;id&#39;<br>const UpdateUserSchema = BaseUserSchema.pick({ id: true }).extend(<br>  BaseUserSchema.omit({ id: true, createdAt: true, updatedAt: true }).partial().shape<br>);<br>type UpdateUserDto = z.infer&lt;typeof UpdateUserSchema&gt;;<br><br><br>// 3. User Login Schema: only needs email and password<br>const LoginSchema = BaseUserSchema.pick({<br>  email: true,<br>  password: true,<br>});<br>type LoginDto = z.infer&lt;typeof LoginSchema&gt;;<br><br>// 4. Admin User Schema: extend BaseUserSchema with admin-specific fields<br>const AdminUserSchema = BaseUserSchema.extend({<br>  adminPermissions: z.array(z.string()).optional(),<br>  lastLoginIp: z.string().ip().optional(),<br>});<br>type AdminUser = z.infer&lt;typeof AdminUserSchema&gt;;<br><br>// --- Usage Examples ---<br><br>// Valid create DTO<br>const createUser: CreateUserDto = {<br>  name: &quot;Alice&quot;,<br>  email: &quot;alice@example.com&quot;,<br>  password: &quot;SecurePassword456&quot;,<br>};<br>console.log(&quot;Valid Create User:&quot;, CreateUserSchema.safeParse(createUser).success); // true<br><br>// Valid update DTO (only updating name and email)<br>const updateUser: UpdateUserDto = {<br>  id: &quot;a1b2c3d4-e5f6-7890-1234-567890abcdef&quot;,<br>  name: &quot;Alicia&quot;,<br>  email: &quot;alicia@example.com&quot;,<br>};<br>console.log(&quot;Valid Update User:&quot;, UpdateUserSchema.safeParse(updateUser).success); // true<br><br>// Invalid create DTO (missing password)<br>const invalidCreateUser = {<br>  name: &quot;Bob&quot;,<br>  email: &quot;bob@example.com&quot;,<br>};<br>console.log(&quot;Invalid Create User (missing password):&quot;, CreateUserSchema.safeParse(invalidCreateUser).success); // false</pre><p><strong>Why it’s robust:</strong> Reduces schema duplication, makes your validation logic more maintainable, and ensures consistency across different API endpoints or data operations by building upon a single source of truth.</p><h3>6. The “Recursive Schema” Pattern: Handling Nested Hierarchies</h3><p>Many data structures are inherently recursive: a file system with nested folders, comments with nested replies, or a category tree. Validating these structures can be a nightmare with traditional methods.</p><p>Zod’s z.lazy() function is the elegant solution for defining recursive schemas. It delays the evaluation of a schema, allowing it to reference itself without causing circular dependency errors.</p><pre>import { z } from &#39;zod&#39;;<br><br>// Define a recursive schema for a folder structure<br>interface Folder {<br>  name: string;<br>  files: string[];<br>  subfolders: Folder[];<br>}<br><br>// Use z.lazy to allow the schema to reference itself<br>const FolderSchema: z.ZodSchema&lt;Folder&gt; = z.lazy(() =&gt;<br>  z.object({<br>    name: z.string().min(1, &quot;Folder name cannot be empty&quot;),<br>    files: z.array(z.string().min(1, &quot;File name cannot be empty&quot;)).default([]),<br>    subfolders: z.array(FolderSchema).default([]), // References itself!<br>  })<br>);<br><br>// --- Usage Examples ---<br><br>// Valid folder structure<br>const validFolderData = {<br>  name: &quot;root&quot;,<br>  files: [&quot;README.md&quot;],<br>  subfolders: [<br>    {<br>      name: &quot;src&quot;,<br>      files: [&quot;index.ts&quot;, &quot;utils.ts&quot;],<br>      subfolders: [<br>        {<br>          name: &quot;components&quot;,<br>          files: [&quot;Button.tsx&quot;],<br>          subfolders: [],<br>        },<br>      ],<br>    },<br>    {<br>      name: &quot;public&quot;,<br>      files: [&quot;index.html&quot;],<br>      subfolders: [],<br>    },<br>  ],<br>};<br>console.log(&quot;Valid Folder:&quot;, FolderSchema.safeParse(validFolderData).success); // true<br><br>// Invalid folder structure (empty subfolder name)<br>const invalidFolderData = {<br>  name: &quot;root&quot;,<br>  files: [&quot;README.md&quot;],<br>  subfolders: [<br>    {<br>      name: &quot;&quot;, // Invalid!<br>      files: [],<br>      subfolders: [],<br>    },<br>  ],<br>};<br>const invalidResult = FolderSchema.safeParse(invalidFolderData);<br>console.log(&quot;Invalid Folder (empty subfolder name):&quot;, invalidResult.success); // false<br>if (!invalidResult.success) {<br>  console.log(&quot;Error details:&quot;, invalidResult.error.errors[0].message); // Folder name cannot be empty<br>}</pre><p><strong>Why it’s robust:</strong> Provides a clean, type-safe way to validate arbitrarily deep nested data structures, ensuring the integrity of complex hierarchical data without complex manual recursion or external libraries.</p><h3>Conclusion: Elevate Your Validation Game</h3><p>Zod is a game-changer for input validation in TypeScript and Node.js. By moving beyond basic field checks and embracing these powerful schema patterns, you can drastically improve the robustness and reliability of your applications.</p><p>From handling dynamic polymorphic data with discriminated unions to ensuring bulletproof configuration with environment variable validation, and from preventing subtle type-based bugs with branded types to managing complex hierarchies with recursive schemas — these patterns empower you to build more resilient and maintainable systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffe0eab11b87" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>