<?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 Odunayo Mohammed on Medium]]></title>
        <description><![CDATA[Stories by Odunayo Mohammed on Medium]]></description>
        <link>https://medium.com/@factman60?source=rss-e42243fbfb3a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1ZK0-5tr3s-NCN0sBrWTmw.png</url>
            <title>Stories by Odunayo Mohammed on Medium</title>
            <link>https://medium.com/@factman60?source=rss-e42243fbfb3a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:31:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@factman60/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[Next.js Server Actions vs. tRPC: A 2026 Architect’s Guide]]></title>
            <link>https://medium.com/@factman60/next-js-server-actions-vs-trpc-a-2026-architects-guide-85cc4953bae4?source=rss-e42243fbfb3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/85cc4953bae4</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[trpc]]></category>
            <category><![CDATA[mutation]]></category>
            <category><![CDATA[server-action]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Odunayo Mohammed]]></dc:creator>
            <pubDate>Fri, 03 Apr 2026 12:52:32 GMT</pubDate>
            <atom:updated>2026-04-03T12:52:32.727Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Next.js Server Actions vs. tRPC: A 2026 Architect’s Guide" src="https://cdn-images-1.medium.com/max/1024/1*0Vyj1pGzN2THbYqamDh9qA.png" /><figcaption>A Senior Developer’s Perspective on Modern Data Mutation Patterns</figcaption></figure><p>As seasoned developers, we’ve witnessed the pendulum of web architecture swing from server-rendered pages to thick-client SPAs, and now to a sophisticated hybrid model. In 2026, the conversation around data mutations in the Next.js ecosystem has distilled down to two mature, powerful patterns: native Next.js Server Actions and the API-first approach of tRPC.</p><p>The debate is no longer about which is “better,” but which architectural philosophy aligns with your application’s core requirements. For those of us architecting complex systems, the choice has significant implications for developer experience, performance, and scalability. This article offers a comparative analysis based on the latest advancements in Next.js 16, React 19, and tRPC v11.</p><h3>The “Native” Pattern: Next.js Server Actions</h3><p>Server Actions represent the integration of the React programming model onto the server. They are a core primitive, deeply woven into the Next.js App Router and its caching mechanisms. Think of them not as API endpoints, but as server-side functions you can call directly from your components.</p><h4><strong>Core Evolution in 2026</strong></h4><p>With React 19 and Next.js 16, Server Actions have moved beyond simple form posts to a comprehensive state management solution:</p><ul><li><strong>useActionState:</strong> The evolution of <strong>useFormState</strong>, this hook is now the definitive way to manage the entire lifecycle of a mutation, initial, pending, and final state, all within a single, elegant hook.</li><li><strong>useOptimistic:</strong> Essential for fluid user interfaces, this hook allows you to apply an immediate, “optimistic” state update on the client while the server mutation is still in flight.</li><li><strong>useFormStatus:</strong> Provides granular, context-aware status of a form submission, perfect for disabling buttons or showing spinners within the scope of a specific <strong>&lt;form&gt;</strong>.</li></ul><h4><strong>Key Architectural Advantages</strong></h4><ul><li><strong>Progressive Enhancement:</strong> This is the killer feature. Forms built with Server Actions are fully functional without any client-side JavaScript. This is a massive win for accessibility, resilience, and core web vitals.</li><li><strong>Integrated Caching:</strong> Server Actions work seamlessly with the Next.js Data Cache. A simple <strong>revalidatePath(‘/’)</strong> or <strong>revalidateTag(‘products’)</strong> within an action is all that’s needed to trigger server-side data refetching, eliminating the complex client-side cache invalidation logic.</li></ul><h4>Performance Consideration for Senior Developers</h4><p>A critical point to understand is that Server Actions are <strong>executed sequentially</strong> from the client. While this design brilliantly prevents race conditions, it can be a bottleneck in highly interactive UIs where multiple, independent mutations need to fire in parallel.</p><h4>Code Example: Optimistic UI with Modern Hooks</h4><p>Here’s a practical example of how these new hooks work together to create a smooth, optimistic commenting experience.</p><pre>// app/actions.ts<br><br>&#39;use server&#39;;<br><br>import { revalidatePath } from &#39;next/cache&#39;;<br><br>interface Comment {<br>  id: number;<br>  text: string;<br>}<br><br>// In a real app, this would be a database.<br>const comments: Comment[] = [{ id: 1, text: &#39;First comment&#39; }];<br><br>export async function addComment(prevState: any, formData: FormData) {<br>  const text = formData.get(&#39;comment&#39;) as string;<br>  if (!text) {<br>    return { error: &#39;Comment cannot be empty.&#39; };<br>  }<br><br>  // Simulate database latency<br>  await new Promise(resolve =&gt; setTimeout(resolve, 1000));<br><br>  const newComment = { id: Date.now(), text };<br>  comments.push(newComment);<br><br>  revalidatePath(&#39;/&#39;);<br>  return { success: true };<br>}</pre><pre>// app/page.tsx<br><br>&#39;use client&#39;;<br><br>import { useActionState, useOptimistic } from &#39;react&#39;;<br>import { addComment } from &#39;./actions&#39;;<br><br>export default function CommentsPage({ initialComments }: { initialComments: Comment[] }) {<br>  const [state, formAction] = useActionState(addComment, null);<br>  const [optimisticComments, addOptimisticComment] = useOptimistic(<br>    initialComments,<br>    (currentComments, newCommentText: string) =&gt; [<br>      ...currentComments,<br>      { id: Math.random(), text: newCommentText },<br>    ]<br>  );<br><br>  return (<br>    &lt;div&gt;<br>      &lt;form<br>        action={async (formData) =&gt; {<br>          const newCommentText = formData.get(&#39;comment&#39;) as string;<br>          addOptimisticComment(newCommentText);<br>          await formAction(formData);<br>        }}<br>      &gt;<br>        &lt;input type=&quot;text&quot; name=&quot;comment&quot; /&gt;<br>        &lt;button type=&quot;submit&quot;&gt;Add Comment&lt;/button&gt;<br>        {state?.error &amp;&amp; &lt;p style={{ color: &#39;red&#39; }}&gt;{state.error}&lt;/p&gt;}<br>      &lt;/form&gt;<br><br>      &lt;ul&gt;<br>        {optimisticComments.map((comment) =&gt; (<br>          &lt;li key={comment.id}&gt;{comment.text}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>The “API-First” Pattern: tRPC</h3><p>tRPC remains the undisputed champion for building dedicated, type-safe API layers. It provides true end-to-end type safety without code generation, making it the preferred choice for complex, client-first applications where the API is a central, standalone entity.</p><h4>Core Strengths in v11+</h4><ul><li><strong>End-to-End Type Safety:</strong> tRPC’s signature feature is its ability to infer your Zod-validated API router schema directly on the client, providing compile-time error checking and flawless autocompletion.</li><li><strong>Request Batching:</strong> A key performance advantage, tRPC automatically batches multiple concurrent procedure calls into a single HTTP request, reducing network overhead in data-heavy UIs.</li><li><strong>TanStack Query Integration:</strong> The <strong>trpc/react-query</strong> package is the industry standard for managing sophisticated client-side state, offering powerful caching, optimistic updates, and background refetching capabilities.</li></ul><h4>Key Architectural Advantages</h4><ul><li><strong>Multi-Client Support:</strong> If your backend needs to serve more than just your Next.js app (e.g., a React Native mobile app), tRPC is the clear choice. First-party support for generating OpenAPI specs, it allows you to build a single API that serves multiple clients with full type safety.</li><li><strong>Mature Middleware:</strong> tRPC’s middleware and context system provides a robust, testable pattern for handling cross-cutting concerns like authentication, logging, and rate limiting.</li></ul><h4>Code Example: tRPC Mutation with TanStack Query</h4><p>This example demonstrates a standard tRPC mutation, showcasing its integration with TanStack Query for client-side state management.</p><pre>// server/trpc.ts<br><br>import { initTRPC } from &#39;@trpc/server&#39;;<br>import { z } from &#39;zod&#39;;<br><br>const t = initTRPC.create();<br><br>export const appRouter = t.router({<br>  updateProfile: t.procedure<br>    .input(z.object({ name: z.string(), bio: z.string() }))<br>    .mutation(async ({ input }) =&gt; {<br>      // In a real app, you would update the database here.<br>      console.log(`Updating profile for ${input.name} with bio: ${input.bio}`);<br>      return { success: true, name: input.name };<br>    }),<br>});<br><br>export type AppRouter = typeof appRouter;</pre><pre>// app/_trpc/client.ts<br><br>import { createTRPCReact } from &#39;@trpc/react-query&#39;;<br>import { AppRouter } from &#39;@/server/trpc&#39;;<br><br>export const trpc = createTRPCReact&lt;AppRouter&gt;();</pre><pre>// app/page.tsx<br><br>&#39;use client&#39;;<br><br>import { trpc } from &#39;./_trpc/client&#39;;<br><br>export default function ProfilePage() {<br>  const utils = trpc.useContext();<br>  const updateProfile = trpc.updateProfile.useMutation({<br>    onSuccess: () =&gt; {<br>      // Invalidate and refetch relevant queries<br>      utils.invalidate();<br>    },<br>  });<br><br>  const handleSubmit = (event: React.FormEvent&lt;HTMLFormElement&gt;) =&gt; {<br>    event.preventDefault();<br>    const formData = new FormData(event.currentTarget);<br>    const name = formData.get(&#39;name&#39;) as string;<br>    const bio = formData.get(&#39;bio&#39;) as string;<br>    updateProfile.mutate({ name, bio });<br>  };<br><br>  return (<br>    &lt;form onSubmit={handleSubmit}&gt;<br>      &lt;input type=&quot;text&quot; name=&quot;name&quot; /&gt;<br>      &lt;textarea name=&quot;bio&quot;&gt;&lt;/textarea&gt;<br>      &lt;button type=&quot;submit&quot; disabled={updateProfile.isLoading}&gt;<br>        {updateProfile.isLoading ? &#39;Saving...&#39; : &#39;Save Profile&#39;}<br>      &lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>}</pre><h3>Comparative Analysis &amp; The “Hybrid” Pattern</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FLELUj%2F2%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FLELUj%2F2%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FLELUj%2Fplain-s.png%3Fv%3D2&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="392" frameborder="0" scrolling="no"><a href="https://medium.com/media/e108b2e0a1091171a84f42ef5be9eeaf/href">https://medium.com/media/e108b2e0a1091171a84f42ef5be9eeaf/href</a></iframe><h4>The Emerging Best Practice: The Hybrid Approach</h4><p>For large-scale, enterprise applications, the most powerful pattern is to combine both. Use tRPC to define a robust, testable, and reusable API layer, then expose it to your React components via type-safe Server Actions.</p><pre>// server/trpc.ts<br><br>import { initTRPC } from &#39;@trpc/server&#39;;<br>import { z } from &#39;zod&#39;;<br><br>const t = initTRPC.create();<br><br>export const appRouter = t.router({<br>  updateProfile: t.procedure<br>    .input(z.object({ name: z.string(), bio: z.string() }))<br>    .mutation(async ({ input }) =&gt; {<br>      // In a real app, you would update the database here.<br>      console.log(`Updating profile for ${input.name} with bio: ${input.bio}`);<br>      return { success: true, name: input.name };<br>    }),<br>});<br><br>export type AppRouter = typeof appRouter;</pre><pre>// app/actions.ts<br><br>&#39;use server&#39;;<br>import { appRouter } from &#39;@/server/trpc&#39;;<br>import { z } from &#39;zod&#39;;<br><br>const updateProfileSchema = z.object({<br>  name: z.string().min(1, &quot;Name is required&quot;),<br>  bio: z.string().min(10, &quot;Bio must be at least 10 characters&quot;),<br>});<br><br>export async function updateProfile(prevState: any, formData: FormData) {<br>  const validatedFields = updateProfileSchema.safeParse({<br>    name: formData.get(&#39;name&#39;),<br>    bio: formData.get(&#39;bio&#39;),<br>  });<br><br>  if (!validatedFields.success) {<br>    return {<br>      errors: validatedFields.error.flatten().fieldErrors,<br>    };<br>  }<br><br>  // Create a server-side caller for our tRPC router<br>  const caller = appRouter.createCaller({});<br>  try {<br>    const result = await caller.updateProfile(validatedFields.data);<br>    revalidatePath(&#39;/&#39;); // Leverage Next.js caching<br>    return { success: true, data: result };<br>  } catch (error) {<br>    return { error: &#39;An unexpected error occurred.&#39; };<br>  }<br>}</pre><p>This hybrid pattern gives you the best of both worlds: the progressive enhancement and seamless Next.js integration of Server Actions, backed by the structured, reusable, and multi-client-ready API layer of tRPC.</p><h3>Conclusion: Strategic Recommendations</h3><p>The choice in 2026 is one of architectural intent:</p><ul><li><strong>For form-heavy, content-focused, or e-commerce applications,</strong> Next.js Server Actions are the clear default. Their simplicity, progressive enhancement, and deep integration with the Next.js ecosystem provide unmatched developer velocity.</li><li><strong>For complex, data-intensive dashboards, SaaS platforms, or applications supporting multiple clients (web and mobile),</strong> tRPC remains the superior choice. Its end-to-end type safety, request batching, and mature client-state management capabilities are essential for these use cases.</li><li><strong>For large-scale, enterprise-level projects,</strong> adopt the <strong>hybrid approach</strong>. It establishes a clean separation of concerns, enhances testability, and future-proofs your architecture by allowing you to leverage the unique strengths of both paradigms.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85cc4953bae4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End-to-End Type Safety: Bridging Nest.js and React with tRPC]]></title>
            <link>https://medium.com/@factman60/end-to-end-type-safety-bridging-nest-js-and-react-with-trpc-1a807683808f?source=rss-e42243fbfb3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a807683808f</guid>
            <category><![CDATA[zod-validation]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[trpc]]></category>
            <dc:creator><![CDATA[Odunayo Mohammed]]></dc:creator>
            <pubDate>Wed, 01 Apr 2026 13:04:36 GMT</pubDate>
            <atom:updated>2026-04-03T10:48:50.034Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Stop API contract drift in its tracks. A guide to achieving 100% type safety with a modern, production-grade TypeScript stack." src="https://cdn-images-1.medium.com/max/1024/1*HoUv5JXM2HwqTKXgWocR1g.png" /><figcaption><em>Stop API contract drift in its tracks. A guide to achieving 100% type safety with a modern, production-grade TypeScript stack.</em></figcaption></figure><p>As a senior developer, you’ve felt the pain. You’ve hunted down bugs that turned out to be a simple mismatch between the frontend’s expectation of an API response and the backend’s reality. You’ve seen REST endpoints and GraphQL schemas go stale, their documentation becoming a source of lies rather than truth. We’ve all wasted hours debugging issues that a compiler should have caught.</p><p>What if you could eliminate that entire class of problems?</p><p>Imagine a workflow where changing a database schema or a backend validation rule instantly throws a compile-time error directly in the frontend component that consumes it. No more <strong>“any”</strong> types. No more manual <strong>“interface”</strong> definitions for API payloads. Just seamless, end-to-end type safety, with autocompletion that feels like magic.</p><p>This isn’t a hypothetical dream. By combining Nest.js, React, Zod, and the star of the show, <strong>tRPC</strong>, within a monorepo, we can build a tightly-coupled, highly-productive development environment. This guide will walk you through the architecture and implementation, skipping the basics and focusing on the production-ready patterns you need.</p><h4>The Architectural Blueprint: The Monorepo is Non-Negotiable</h4><p>For this pattern to work, a monorepo isn’t just a nice-to-have; it’s the foundation. It allows our backend, frontend, and a shared “contracts” package to coexist, ensuring that any change to the shared code is immediately reflected across the entire stack. We’ll use <strong>pnpm</strong> workspaces for its efficiency.</p><p><strong>Our structure is simple and scalable:</strong></p><pre>/monorepo-trpc-nest<br>|-- /apps<br>|   |-- /backend         # Nest.js Application<br>|   |-- /frontend        # Vite + React Application<br>|-- /packages<br>|   |-- /trpc-shared     # Shared tRPC Router, Types, and Zod Schemas<br>|-- package.json<br>|-- pnpm-workspace.yaml</pre><p>The <strong>pnpm-workspace.yaml</strong> simply tells pnpm where to find the projects:</p><pre>packages:<br>  - &#39;apps/*&#39;<br>  - &#39;packages/*&#39;</pre><h4>Step 1: The Single Source of Truth (`trpc-shared`)</h4><p>This is the linchpin of the entire architecture. This package will export <strong>definitions and types</strong>, not implementations. It’s the contract that both the server and client will adhere to.</p><p>Initialize the shared workspace package first, then install the dependencies it needs:</p><pre>mkdir -p packages/trpc-shared/src<br>cd packages/trpc-shared<br>pnpm init<br>pnpm add zod @trpc/server</pre><p>First, we define our validation schemas using Zod. These schemas serve a dual purpose: they provide runtime validation on the backend, and TypeScript can infer their types.</p><pre>// packages/trpc-shared/src/zod-schemas.ts<br><br>import { z } from &#39;zod&#39;;<br><br>export const getUserInputSchema = z.object({<br>  userId: z.string().uuid(),<br>});<br><br>export const createUserSchema = z.object({<br>  email: z.string().email(),<br>  name: z.string().min(2),<br>});</pre><p>Next, we define the <strong>shape</strong> of our API router using tRPC. Notice the implementations are dummy functions; they exist only to satisfy TypeScript so it can infer the types of the inputs and outputs.</p><pre>// packages/trpc-shared/src/router.ts<br><br>import { initTRPC } from &#39;@trpc/server&#39;;<br>import { z } from &#39;zod&#39;;<br>import { getUserInputSchema, createUserSchema } from &#39;./zod-schemas&#39;;<br><br>// Define a context type. This will be populated by the server<br>// on each request. Great for user auth data.<br>export interface Context {<br>  // user: { id: string; email: string; name: string } | null;<br>}<br><br>const t = initTRPC.context&lt;Context&gt;().create();<br><br>export const router = t.router;<br>export const publicProcedure = t.procedure;<br><br>// DEFINE THE ROUTER SHAPE<br>export const appRouter = router({<br>  users: router({<br>    get: publicProcedure<br>      .input(getUserInputSchema)<br>      .query(() =&gt; ({})), // Dummy implementation for type inference<br>    create: publicProcedure<br>      .input(createUserSchema)<br>      .mutation(() =&gt; ({})), // Dummy implementation<br>  }),<br>});<br><br>// This is the magic. We export the *type* of the router.<br>// This is all the client needs to be fully type-safe.<br>export type AppRouter = typeof appRouter;</pre><h4>Step 2: Backend Implementation with Nest.js</h4><p>The core challenge on the backend is integrating tRPC’s functional style with Nest.js’s powerful dependency injection (DI) container. We need our tRPC procedures to call our Nest.js services.</p><p>Initialize the Nest.js backend app, then add the tRPC and shared-contract dependencies:</p><pre>pnpm dlx @nestjs/cli new apps/backend --package-manager pnpm<br>cd apps/backend<br>pnpm add @trpc/server zod trpc-shared@workspace:*</pre><p>We’ll start by creating a <strong>TrpcService</strong> that provides the basic tRPC building blocks.</p><pre>// apps/backend/src/trpc/trpc.service.ts<br><br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { initTRPC } from &#39;@trpc/server&#39;;<br>import { Context } from &#39;trpc-shared&#39;; // Import context from shared package<br><br>@Injectable()<br>export class TrpcService {<br>  private readonly t = initTRPC.context&lt;Context&gt;().create();<br><br>  public readonly router = this.t.router;<br>  public readonly publicProcedure = this.t.procedure;<br>}</pre><p>Now, let’s create a standard <strong>UserService</strong> that contains our business logic.</p><pre>// apps/backend/src/user/user.service.ts<br><br>import { Injectable, NotFoundException } from &#39;@nestjs/common&#39;;<br>import { createUserSchema } from &#39;trpc-shared/zod-schemas&#39;;<br>import { z } from &#39;zod&#39;;<br><br>// Mock DB for demonstration<br>const users = [{ id: &#39;123e4567-e89b-12d3-a456-426614174000&#39;, name: &#39;John Doe&#39;, email: &#39;john.doe@example.com&#39; }];<br><br>@Injectable()<br>export class UserService {<br>  findById(id: string) {<br>    const user = users.find((u) =&gt; u.id === id);<br>    if (!user) {<br>      throw new NotFoundException(`User with ID ${id} not found.`);<br>    }<br>    return user;<br>  }<br><br>  create(data: z.infer&lt;typeof createUserSchema&gt;) {<br>    const newUser = { id: crypto.randomUUID(), ...data };<br>    users.push(newUser);<br>    return newUser;<br>  }<br>}</pre><p>Here’s where it all comes together. The <strong>TrpcRouter</strong> class will inject our <strong>TrpcService</strong> and <strong>UserService</strong> and provide the <strong>real</strong> implementations for our router procedures.</p><pre>// apps/backend/src/trpc/trpc.router.ts<br><br>import { INestApplication, Injectable } from &#39;@nestjs/common&#39;;<br>import * as trpcExpress from &#39;@trpc/server/adapters/express&#39;;<br>import { appRouter, Context } from &#39;trpc-shared&#39;; // Import the TYPE from shared<br>import { createUserSchema, getUserInputSchema } from &#39;trpc-shared/zod-schemas&#39;;<br>import { UserService } from &#39;../user/user.service&#39;;<br>import { TrpcService } from &#39;./trpc.service&#39;;<br><br>@Injectable()<br>export class TrpcRouter {<br>  constructor(<br>    private readonly trpcService: TrpcService,<br>    private readonly userService: UserService, // Inject other services<br>  ) {}<br><br>  // This is the actual router implementation.<br>  private readonly router = this.trpcService.router({<br>    users: this.trpcService.router({<br>      get: this.trpcService.publicProcedure<br>        .input(getUserInputSchema)<br>        .query(({ input }) =&gt; {<br>          // Here we call our injected Nest.js service<br>          return this.userService.findById(input.userId);<br>        }),<br>      create: this.trpcService.publicProcedure<br>        .input(createUserSchema)<br>        .mutation(({ input }) =&gt; {<br>          return this.userService.create(input);<br>        }),<br>    }),<br>  });<br><br>  // Attach the tRPC router to the Nest.js Express server<br>  async applyMiddleware(app: INestApplication) {<br>    app.use(<br>      `/trpc`,<br>      trpcExpress.createExpressMiddleware({<br>        router: this.router,<br>        createContext: ({ req, res }): Context =&gt; {<br>          // Populate context from request, e.g., for auth<br>          return {};<br>        },<br>      }),<br>    );<br>  }<br><br>  // A crucial type-safety check. If our implementation here doesn&#39;t<br>  // match the shape of the `appRouter` type from the shared package,<br>  // TypeScript will throw a compile-time error.<br>  private _appRouter: typeof this.router = {} as typeof appRouter;<br>}</pre><p>Finally, we wire everything up in our main application module and bootstrap file.</p><pre>// apps/backend/src/app.module.ts<br><br>import { Module } from &#39;@nestjs/common&#39;;<br>import { TrpcService } from &#39;./trpc/trpc.service&#39;;<br>import { TrpcRouter } from &#39;./trpc/trpc.router&#39;;<br>import { UserService } from &#39;./user/user.service&#39;;<br><br>@Module({<br>  imports: [],<br>  providers: [TrpcService, TrpcRouter, UserService],<br>})<br>export class AppModule {}</pre><pre>// apps/backend/src/main.ts<br><br>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br>import { TrpcRouter } from &#39;./trpc/trpc.router&#39;;<br><br>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br>  app.enableCors(); // Don&#39;t forget CORS<br><br>  const trpcRouter = app.get(TrpcRouter);<br>  await trpcRouter.applyMiddleware(app);<br><br>  await app.listen(4000);<br>}<br>bootstrap();</pre><h4>Step 3: Frontend Bliss with React and react-query</h4><p>Now for the payoff. Start by initializing a Vite + React app, then install the necessary tRPC/react-query clients and the shared workspace package.</p><pre>pnpm create vite apps/frontend --template react-ts<br>cd apps/frontend<br>pnpm add @trpc/client @trpc/server @trpc/react-query @tanstack/react-query trpc-shared@workspace:*</pre><p>We configure a tRPC client, importing <strong>only the AppRouter type</strong> from our shared package. This is incredibly lightweight; no actual server code is bundled with the client.</p><pre>// apps/frontend/src/utils/trpc.ts<br><br>import { createTRPCReact } from &#39;@trpc/react-query&#39;;<br>import { httpBatchLink } from &#39;@trpc/client&#39;;<br>import type { AppRouter } from &#39;trpc-shared&#39;; // CRITICAL: Import only the TYPE<br><br>// Create a strongly-typed tRPC hook<br>export const trpc = createTRPCReact&lt;AppRouter&gt;();<br><br>export const trpcClient = trpc.createClient({<br>  links: [<br>    // Use httpBatchLink for performance. It batches multiple<br>    // requests in a short time window into a single HTTP request.<br>    httpBatchLink({<br>      url: &#39;http://localhost:4000/trpc&#39;,<br>    }),<br>  ],<br>});</pre><p>We wrap our application with the required providers for tRPC and React Query.</p><pre>// apps/frontend/src/main.tsx<br><br>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom/client&#39;;<br>import App from &#39;./App.tsx&#39;;<br>import { QueryClient, QueryClientProvider } from &#39;@tanstack/react-query&#39;;<br>import { trpc, trpcClient } from &#39;./utils/trpc.ts&#39;;<br><br>const queryClient = new QueryClient();<br><br>ReactDOM.createRoot(document.getElementById(&#39;root&#39;)!).render(<br>  &lt;React.StrictMode&gt;<br>    &lt;trpc.Provider client={trpcClient} queryClient={queryClient}&gt;<br>      &lt;QueryClientProvider client={queryClient}&gt;<br>        &lt;App /&gt;<br>      &lt;/QueryClientProvider&gt;<br>    &lt;/trpc.Provider&gt;<br>  &lt;/React.StrictMode&gt;,<br>);</pre><p>Now, consuming the API in a component is a dream. Watch what happens:</p><pre>// apps/frontend/src/App.tsx<br><br>import { trpc } from &#39;./utils/trpc&#39;;<br>import { useState } from &#39;react&#39;;<br><br>function UserComponent() {<br>  const [userId, setUserId] = useState(&#39;123e4567-e89b-12d3-a456-426614174000&#39;);<br>  <br>  // 1. Fully typed query hook.<br>  //    - As you type `trpc.`, you get autocompletion for `users`.<br>  //    - Then for `get`.<br>  //    - The input object is strictly typed against the Zod schema.<br>  //    - The returned `data` is fully typed.<br>  const { data, isLoading, error } = trpc.users.get.useQuery({ userId });<br><br>  // 2. Fully typed mutation hook.<br>  const createUser = trpc.users.create.useMutation({<br>    onSuccess: (newUser) =&gt; {<br>      // `newUser` is correctly typed as { id: string, name: string, email: string }<br>      alert(`Created user: ${newUser.name}`);<br>    },<br>  });<br><br>  const handleCreate = () =&gt; {<br>    // A typo like &#39;emial&#39; would cause an immediate compile-time error.<br>    createUser.mutate({<br>      email: &#39;jane.doe@example.com&#39;,<br>      name: &#39;Jane Doe&#39;,<br>    });<br>  };<br>  <br>  if (isLoading) return &lt;div&gt;Loading user...&lt;/div&gt;;<br>  if (error) return &lt;div&gt;Error: {error.message}&lt;/div&gt;;<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;User Details&lt;/h1&gt;<br>      &lt;p&gt;ID: {data?.id}&lt;/p&gt;<br>      &lt;p&gt;Name: {data?.name}&lt;/p&gt;<br>      &lt;p&gt;Email: {data?.email}&lt;/p&gt;<br><br>      &lt;button onClick={handleCreate} disabled={createUser.isLoading}&gt;<br>        Create New User<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>The developer experience is transformed. If a backend developer adds a required <strong>age: z.number()</strong> field to the <strong>createUserSchema</strong>, the frontend developer’s IDE will immediately light up with a TypeScript error on the <strong>createUser.mutate</strong> call, informing them that the <strong>age</strong> property is missing. The bug is caught before the code is even committed.</p><h4>Production-Grade Patterns</h4><p>For a real-world application, you’ll need more.</p><ul><li><strong>Authentication:</strong> Populate the <strong>Context</strong> using a standard Nest.js middleware that runs <strong>before</strong> the tRPC middleware. This middleware can verify a JWT, attach the user to the request object, and the <strong>createContext</strong> function can then place it in the tRPC context, making it available to all procedures. You can then create “<strong>protectedProcedures”</strong> that throw an <strong>UNAUTHORIZED</strong> error if the user isn’t present.</li><li><strong>Error Handling:</strong> Use tRPC’s <strong>errorFormatter</strong> in the server configuration to map Nest.js exceptions (like <strong>NotFoundException</strong>) to proper tRPC error codes. You can also use it to flatten Zod validation errors, providing detailed feedback to the client on which fields failed validation.</li></ul><h4>Final Words: Is It Better Than GraphQL or REST?</h4><ul><li><strong>vs. GraphQL + CodeGen:</strong> tRPC offers a zero-build-step experience. The types are inferred live, directly from your backend code. GraphQL requires a separate schema definition language and a code generation step to create TypeScript types and hooks. For internal APIs or tightly-coupled full-stack apps, tRPC is significantly simpler and faster.</li><li><strong>vs. REST + OpenAPI: </strong>This classic approach requires generating a spec file (like <strong>`swagger.json`</strong>) and then generating a client from it. This process is brittle and prone to drift. The implementation is the source of truth, not the spec. With tRPC, the implementation <strong>is</strong> the spec.</li></ul><p>By adopting this architecture, you are not just choosing a new library; you are fundamentally changing the contract between your frontend and backend. You are leveraging the full power of TypeScript to build more robust, more maintainable applications, faster. You are eliminating an entire category of bugs and creating a developer experience that is second to none.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a807683808f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Developer Experience Tug-of-War: Static vs. Dynamic Typing]]></title>
            <link>https://medium.com/@factman60/the-developer-experience-tug-of-war-static-vs-dynamic-typing-10194a503e3e?source=rss-e42243fbfb3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/10194a503e3e</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[developer-experience]]></category>
            <category><![CDATA[static-typing]]></category>
            <category><![CDATA[dynamic-typing]]></category>
            <dc:creator><![CDATA[Odunayo Mohammed]]></dc:creator>
            <pubDate>Wed, 12 Mar 2025 01:28:31 GMT</pubDate>
            <atom:updated>2025-03-12T01:28:31.191Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x-IpwoUCHMzPI28CkmIgxg.jpeg" /></figure><h4><strong>How We Went from Strict Rules to Total Chaos — and Found Balance with TypeScript</strong></h4><p>Picture this: You’re building a house. You can either have an architect carefully plan out every detail (statically typed languages), or you can wing it, add rooms as you go, and hope nothing collapses (dynamically typed languages). Both approaches <em>work</em> — but one of them might leave you with a bathtub in the living room.</p><p>For decades, programming languages have swung between these two extremes, all in the name of improving the developer experience (DX). Let’s take a ride through this evolution, explore what went wrong (cough, runtime errors), and how we ended up back where we started — except this time, with TypeScript as our knight in shining armor.</p><h4>The Static Beginnings: Order, Safety, and Boilerplate</h4><p>In the early days of programming, most languages were statically typed. C, Java, Pascal — you had to tell the computer exactly what type of data you were working with. While this provided safety and predictability, it also meant writing a <em>lot</em> of code just to get simple things done. Need a list of names? Great, declare an array, specify the type, initialize it, and don’t forget to allocate memory.</p><p>Developers, being the innovative (read: lazy) creatures we are, started craving something simpler. Enter dynamic typing.</p><h4>The Dynamic Revolution: Move Fast, Break Things (Literally)</h4><p>Languages like JavaScript, Python, and Ruby came along with a tempting proposition:</p><blockquote>“What if you didn’t have to tell the computer what type of data you’re using? Just assign a variable and let the interpreter figure it out!”</blockquote><p>Suddenly, development was faster. You didn’t have to deal with rigid type declarations, and everything felt lightweight and flexible. Web development, in particular, exploded thanks to JavaScript’s low entry barrier.</p><p>But… (and this is a big but)</p><p>Without type safety, developers started experiencing the wild west of runtime errors. You’d happily run your code, only to watch it explode because someone tried adding a number to a string. Debugging became a nightmare, and large projects turned into spaghetti bowls of unpredictable behavior.</p><h4>The TypeScript Redemption Arc: Best of Both Worlds?</h4><p>By the mid-2010s, JavaScript was running <em>everything</em>. Websites, servers, even robots. But as projects grew, so did the chaos. Developers needed a way to bring back order <em>without</em> losing JavaScript’s flexibility. Enter TypeScript.</p><p>TypeScript (created by Microsoft) took JavaScript and added optional static typing. It lets you gradually introduce types into your codebase, catching errors at compile-time instead of letting them crash in production. Think of it like auto-correct for your code — except it actually helps instead of ruining your sentences.</p><p>The adoption was <strong>massive</strong>. TypeScript skyrocketed in popularity because:</p><ul><li>It improved code confidence — less fear of “undefined is not a function.”</li><li>It made collaboration easier — developers knew what types to expect.</li><li>It scaled beautifully — big teams working on big projects had fewer surprises.</li></ul><p>Today, TypeScript is everywhere. It’s the default for most modern JavaScript projects, and its benefits are so undeniable that even die-hard JavaScript purists have given in.</p><h4>Where Are We Now? The Current State of DX</h4><p>So, have we settled the battle between static and dynamic typing? Not quite. Here’s where things stand:</p><p><strong>Statically Typed Languages (C, C++, Java, TypeScript, Rust)</strong><br>✅ Fewer runtime errors <br>✅ Better tooling and autocomplete <br>✅ Safer, more predictable code <br>❌ More boilerplate <br>❌ Slightly steeper learning curve</p><p><strong>Dynamically Typed Languages (Python, JavaScript, Ruby)</strong><br>✅ Faster prototyping and iteration <br>✅ Less code to write <br>✅ Easy for beginners <br>❌ Prone to runtime errors <br>❌ Harder to maintain in large projects</p><h4>Conclusion: The DX Balancing Act</h4><p>Developer experience isn’t just about static vs. dynamic — it’s about trade-offs. We started with safety, swung too far into flexibility, and are now finding middle ground. TypeScript is proof that DX can evolve to give us <strong>the best of both worlds</strong>: the speed of JavaScript with the safety of static typing.</p><p>So, the next time someone asks:</p><blockquote>“Should I use a statically or dynamically typed language?”</blockquote><p>you can confidently say:</p><blockquote><strong>”It depends — but TypeScript is a pretty sweet deal.”</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10194a503e3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>