<?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 Ben Jannet Ahmed on Medium]]></title>
        <description><![CDATA[Stories by Ben Jannet Ahmed on Medium]]></description>
        <link>https://medium.com/@benjannetahmed.03?source=rss-5d5731c8c6ef------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bcCuLRJdz54b6xEFvlbs3A.jpeg</url>
            <title>Stories by Ben Jannet Ahmed on Medium</title>
            <link>https://medium.com/@benjannetahmed.03?source=rss-5d5731c8c6ef------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 16:22:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@benjannetahmed.03/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[TypeScript Utility Types You Actually Use in Real Projects]]></title>
            <link>https://medium.com/@benjannetahmed.03/typescript-utility-types-you-actually-use-in-real-projects-73f3e395b148?source=rss-5d5731c8c6ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/73f3e395b148</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[typescript-tips]]></category>
            <category><![CDATA[utility-types]]></category>
            <category><![CDATA[react-typescript]]></category>
            <dc:creator><![CDATA[Ben Jannet Ahmed]]></dc:creator>
            <pubDate>Thu, 09 Apr 2026 13:23:43 GMT</pubDate>
            <atom:updated>2026-04-09T13:23:43.037Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YJuq-n0zWbKYYCLQcixRbQ.png" /></figure><p>Most articles about TypeScript utility types look like this :</p><blockquote>Partial&lt;T&gt; makes all properties optional.<br>Pick&lt;T, K&gt; selects specific properties.<br>Omit&lt;T, K&gt; removes properties.</blockquote><p>And technically, that’s correct, but if you’ve worked on a real codebase, you know the real questions are different:</p><ul><li>When is Partial&lt;T&gt; <strong>actually safe to use</strong>?</li><li>When does Omit&lt;T, K&gt; <strong>silently couple your API to your database schema</strong>?</li><li>Why do large codebases <strong>eventually stop deriving types from entities</strong>?</li><li>And why does a clever utility type sometimes make your system <strong>harder to maintain</strong>?</li></ul><p>The problem isn’t understanding what these utilities do.</p><p>The problem is understanding <strong>when they should exist at all</strong>.</p><p>This article is a <strong>practical guide to how TypeScript utility types are actually used in production codebases</strong> — frontend, backend, and the boundary between them.</p><p>We’ll look at:</p><ul><li>where they shine</li><li>where they quietly introduce bugs</li><li>and when an <strong>explicit interface is the better design choice</strong></li></ul><h3>The Utility Types We’ll Cover</h3><p>Instead of listing every TypeScript helper type, we’ll focus on the ones that appear constantly in real projects:</p><p>Partial&lt;T&gt;PATCH updates and optional state<br>DeepPartial&lt;T&gt;Nested updates<br>Omit&lt;T, K&gt;Removing fields and reshaping payloads<br>Pick&lt;T, K&gt;Intentional minimal API responses<br>Record&lt;K, V&gt;Typed maps and enum lookups<br>Readonly&lt;T&gt;Immutable function inputs<br>Required&lt;T&gt;Post-validation guarantees<br>ReturnType&lt;T&gt;Deriving types from functions<br>Parameters&lt;T&gt;Extracting function signatures</p><p>Along the way we’ll also look at <strong>intersection types (</strong><strong>&amp;)</strong>, which are often misunderstood but extremely powerful when used correctly.</p><h3>A Quick Visual Model of Utility Types</h3><p>Think of utility types as <strong>type transformers</strong>.</p><p>They take an existing shape and produce a <strong>new shape</strong>.</p><p>Example:</p><pre>interface User {<br>  id: string<br>  email: string<br>  password: string<br>}</pre><pre>Partial&lt;User&gt;<br>{<br>  id?: string<br>  email?: string<br>  password?: string<br>}</pre><pre>Omit&lt;User, &quot;password&quot;&gt;<br>{<br>  id: string<br>  email: string<br>}</pre><pre>Pick&lt;User, &quot;id&quot; | &quot;email&quot;&gt;<br>{<br>  id: string<br>  email: string<br>}</pre><p>These transformations look simple.</p><p>But when applied to <strong>large entities, nested relations, and API contracts</strong>, the consequences become much more interesting.</p><h3>Partial&lt;T&gt; — Useful, but More Dangerous Than It Looks</h3><p>The most common place Partial&lt;T&gt; appears is update operations.</p><pre>interface User {<br>  id: string;<br>  email: string;<br>  password: string;<br>  profile: {<br>    firstName: string;<br>    lastName: string;<br>  };<br>}<br>type UpdateUserDto = Partial&lt;User&gt;;</pre><p>At first glance, this looks reasonable.<br> For a PATCH /users/:id endpoint, everything should be optional — right?</p><p><strong>Not exactly.</strong></p><h3>The Hidden Problem</h3><p>Partial&lt;User&gt; only makes <strong>top-level properties optional</strong>. It does <strong>not recurse into nested objects</strong>.</p><pre>const update: UpdateUserDto = {<br>  profile: {}, // TypeScript allows this — your domain probably doesn&#39;t</pre><p>This compiles. But you’ve just passed an update that wipes firstName and lastName because profile is now a structurally valid but semantically empty object.</p><p>TypeScript won’t warn you. Your runtime might not either.</p><h3>A Second Problem: Entity Coupling</h3><p>Using Partial&lt;Entity&gt; as a public DTO couples your <strong>database schema directly to your API contract</strong>.</p><p>If you add a field to your entity, it automatically becomes <strong>updatable via the API</strong> — whether you intended that or not.</p><h3>A Better Mental Model</h3><p>Partial&lt;T&gt; works best for:</p><ul><li>Flat objects with no domain constraints</li><li>Temporary data structures (form state deltas, diff objects)</li><li>Internal helpers and utility functions</li></ul><p>It becomes risky when:</p><ul><li>Used directly as a public API contract</li><li>Applied to complex domain models</li><li>The entity contains fields that <strong>should never be client-updatable</strong> (createdAt, role, isAdmin)</li></ul><h3>A Real Anti-Pattern You’ll See in Codebases</h3><pre>// ❌ Common mistake<br>updateUser(id: string, data: Partial&lt;UserEntity&gt;)</pre><p>This one line:</p><ul><li>Exposes your database schema as an API contract</li><li>Makes every field optionally updatable</li><li>Gives no indication of which fields are actually expected</li><li>Fails silently on nested objects</li></ul><h3>The Better Approach (Especially in NestJS)</h3><p>Define an explicit CreateUserDto, then derive the update DTO from it.</p><pre>// ✅ NestJS pattern<br>export class UpdateUserDto extends PartialType(CreateUserDto) {}</pre><p>PartialType from @nestjs/swagger does more than Partial&lt;T&gt;:</p><ul><li>Preserves validation decorators</li><li>Makes them optional-aware</li><li>Keeps Swagger documentation consistent</li></ul><p>In real projects, this difference <strong>matters</strong>.</p><h3>DeepPartial&lt;T&gt; — Why TypeScript Doesn&#39;t Ship It</h3><p>Because Partial&lt;T&gt; only goes one level deep, many teams introduce a recursive type:</p><pre>type DeepPartial&lt;T&gt; = {<br>  [K in keyof T]?: T[K] extends object ? DeepPartial&lt;T[K]&gt; : T[K];<br>};</pre><p>Now you can write:</p><pre>const update: DeepPartial&lt;User&gt; = {<br>  profile: {<br>    firstName: &quot;Ahmed&quot;,<br>  },<br>};</pre><p>This is useful for <strong>PATCH request payloads</strong> that need partial nested updates.</p><h3>But Be Careful</h3><p>Deep utility types are <strong>powerful and dangerous</strong>.</p><p>They:</p><ul><li>Remove structural guarantees at every level</li><li>Make invalid states easy to represent</li><li>Hide domain constraints</li><li>Don’t integrate cleanly with validation libraries without extra work</li></ul><p><strong>Rule of thumb</strong></p><blockquote><em>Use </em><em>DeepPartial only at </em><strong><em>system input boundaries (</em></strong>is where <strong>data enters your system from the outside world )</strong><em> and always validate at runtime.</em></blockquote><h3>Omit&lt;T, K&gt; — More Than a Security Tool</h3><p>The most common example of Omit is hiding sensitive fields.</p><pre>type PublicUser = Omit&lt;User, &quot;password&quot;&gt;;</pre><p>Compared to manually redefining the type, Omit:</p><ul><li>Prevents accidental duplication</li><li>Adapts automatically when User changes</li><li>Makes security decisions visible in the type system</li></ul><p>But Omit is used for <strong>much more than security</strong>.</p><h3>The Real Use Case: Shape Transformation</h3><p>In frontend applications, your payload types often <strong>don’t match your entities</strong>.</p><p>For example:</p><pre>interface Order {<br>  id: string;<br>  orderNumber: string;<br>  status: OrderStatus;<br>  totalAmount: number;<br>  user: UserProfile;<br>  destination?: Destination;<br>  orderItems: OrderItem[];<br>}</pre><p>But your API payload might look like:</p><pre>interface OrderPayload extends Omit&lt;<br>  Order,<br>  &quot;id&quot; | &quot;user&quot; | &quot;destination&quot; | &quot;orderItems&quot;<br>&gt; {<br>  userId: string;<br>  destination: string | null;<br>  orderItems: Array&lt;<br>    Omit&lt;OrderItem, &quot;id&quot; | &quot;serviceCatalog&quot;&gt; &amp; { serviceCatalog: number }<br>  &gt;;<br>}</pre><p>Here Omit removes nested relations so they can be replaced with <strong>foreign keys</strong>.</p><p>This pattern is powerful — but it has risks.</p><h3>The Implicit Coupling Problem</h3><p>When your payload derives from your entity using Omit, you&#39;ve created a <strong>dependency</strong>.</p><p>Every new field added to the entity <strong>automatically appears in the payload type</strong>.</p><p>If your backend adds a new field like deletedAt and you forget to exclude it, your payload type now includes it silently.</p><p>For small entities this is manageable.<br> For large ones, it becomes a liability.</p><h3>A Subtle Mistake: Chaining Omits</h3><pre>// ❌ Avoid<br>type SafeUser = Omit&lt;Omit&lt;User, &quot;password&quot;&gt;, &quot;token&quot;&gt;;</pre><pre>// ✅ Prefer<br>type SafeUser = Omit&lt;User, &quot;password&quot; | &quot;token&quot;&gt;;</pre><p>Clarity matters when types express <strong>security or API boundaries</strong>.</p><h3>Pick&lt;T, K&gt; vs Omit&lt;T, K&gt;</h3><p>These types look symmetrical, but they communicate <strong>different intent</strong>.</p><pre>type UserPreview = Pick&lt;User, &quot;id&quot; | &quot;email&quot;&gt;;</pre><ul><li>Pick → <em>Only these fields matter.</em></li><li>Omit → <em>Everything except these fields is acceptable.</em></li></ul><h3>API Design Guidelines</h3><p>Use <strong>Pick</strong> for:</p><ul><li>Minimal response shapes</li><li>Search results</li><li>Dropdown lists</li><li>Intentional projections</li></ul><p>Use <strong>Omit</strong> for:</p><ul><li>Full objects minus a few exclusions</li><li>Removing sensitive or server-managed fields</li></ul><h3>Intersection Types (&amp;) — Composition, Not Merging</h3><p>Intersection types are often misunderstood.</p><pre>type Auditable = {<br>  createdAt: Date;<br>  updatedAt: Date;<br>};<br>type UserEntity = User &amp; Auditable;</pre><p>This does <strong>not merge objects at runtime</strong>.</p><p>It simply means:</p><blockquote><em>A </em><em>UserEntity must satisfy </em><strong><em>both </em></strong><strong><em>User and </em></strong><strong><em>Auditable</em></strong><em>.</em></blockquote><h3>Where &amp; Shines</h3><p>Intersection types work well for:</p><ul><li>Metadata mixins (Auditable, SoftDeletable)</li><li>Cross-cutting concerns</li><li>Extending an Omit result</li></ul><p>Example:</p><pre>type OrderPayload =<br>  Omit&lt;Order, &quot;user&quot; | &quot;destination&quot;&gt; &amp; {<br>    userId: string;<br>    destinationId: string | null;<br>  };</pre><h3>Where It Breaks</h3><p>Conflicting properties create never.</p><pre>type A = { id: string };<br>type B = { id: number };<br>type C = A &amp; B; // id becomes never</pre><p>A value cannot be both string <strong>and</strong> number.</p><h3>Required&lt;T&gt; and Readonly&lt;T&gt; — The Underused Ones</h3><p>These types appear less often in tutorials but are very useful.</p><h3>Required&lt;T&gt;</h3><p>Makes optional properties mandatory.</p><pre>interface Config {<br>  timeout?: number;<br>  retries?: number;<br>  baseUrl?: string;<br>}<br><br>function executeWithConfig(config: Required&lt;Config&gt;) {<br>  // here we know everything exists<br>}</pre><p>Useful when <strong>defaults and validation already ran</strong>.</p><h3>Readonly&lt;T&gt;</h3><p>Prevents mutation.</p><pre>function processUser(user: Readonly&lt;User&gt;) {<br>  user.email = &quot;changed&quot;; // ❌ error<br>}</pre><p>Great for:</p><ul><li>Immutable parameters</li><li>External data</li><li>Defensive APIs</li></ul><h3>Record&lt;K, V&gt; — A Typed Map</h3><p>Record&lt;K, V&gt; is one of the most underrated utility types.</p><pre>type RolePermissions = Record&lt;string, boolean&gt;;</pre><p>Better than:</p><pre>{ [key: string]: boolean }</pre><p>It becomes powerful when K is a union.</p><pre>type FeatureFlags = Record&lt;<br>  &quot;darkMode&quot; | &quot;betaCheckout&quot; | &quot;newCalendar&quot;,<br>  boolean<br>&gt;;</pre><p>Now the object <strong>must contain exactly those keys</strong>.</p><h3>ReturnType&lt;T&gt; and Parameters&lt;T&gt;</h3><p>These utility types work with <strong>functions as types</strong>.</p><h3>ReturnType</h3><pre>async function fetchUser(id: string) {<br>  return { id, email: &quot;user@example.com&quot;, role: &quot;admin&quot; };<br>}<br><br>type User = Awaited&lt;ReturnType&lt;typeof fetchUser&gt;&gt;;</pre><p>This derives the type <strong>from the function itself</strong>, avoiding duplication.</p><h3>Parameters</h3><pre>function createDestination(number: string, floor: string, <br>destinationTypeId: number) {}<br><br>type CreateDestinationArgs = Parameters&lt;typeof createDestination&gt;;<br>// [string, string, number]</pre><p>Useful when writing:</p><ul><li>wrappers</li><li>middleware</li><li>decorators</li></ul><h3>Practical Guidelines</h3><ol><li>Never use Partial&lt;Entity&gt; as a public API contract</li><li>Use Partial sparingly — mainly for flat objects and helpers</li><li>Reserve DeepPartial for system input boundaries</li><li>Use Omit for shape transformation — but watch for coupling</li><li>Use Pick for minimal, intentional response shapes</li><li>Prefer explicit interfaces over complex Omit + &amp; chains</li><li>Never write complex utility types inline in component generics</li><li>Use Record&lt;EnumKey, V&gt; to enforce exhaustive mappings</li><li>Always validate data at runtime — types disappear after compilation</li></ol><h3>The Mistakes You’ll Actually See When Working on Projects</h3><h3>Mistake 1: Omit&lt;Entity, &quot;id&quot;&gt; as a create DTO</h3><pre>type CreateDestination = Omit&lt;Destination, &quot;id&quot; | &quot;created_at&quot;&gt;;</pre><p>Works — until destinationType becomes a nested object instead of an ID.</p><p>Now your payload silently changes shape.</p><h3>Mistake 2: Complex utility types inside React components</h3><pre>const [formData, setFormData] = useState&lt;<br>  Omit&lt;Destination, &quot;features&quot; | &quot;id&quot; | &quot;created_at&quot; | &quot;destinationType&quot;&gt;<br>  &amp; { destinationType: string }<br>&gt;();</pre><p>If you count more than <strong>three omitted fields</strong>, extract a named type.</p><h3>Mistake 3: Deriving payloads from large entities</h3><p>When entities reach <strong>20+ fields</strong>, Omit lists become fragile.</p><p>Explicit interfaces scale better.</p><h3>Mistake 4: Relying on TypeScript for runtime validation</h3><pre>function updateDestination(id: string, data: Partial&lt;DestinationPayload&gt;) {<br>  destinationRepository.update(id, data);<br>}</pre><p>{} satisfies Partial&lt;T&gt;.</p><p>Your runtime may accept an <strong>empty update</strong>.</p><p>Always validate data at system boundaries.</p><h3>Final Thoughts</h3><p>Utility types are not just shortcuts.</p><p>They are a <strong>design language</strong> for describing how data moves through your system.</p><p>The real skill isn’t knowing that Partial&lt;T&gt; makes fields optional.</p><p>It’s knowing when a type transformation:</p><ul><li><strong>clarifies a contract</strong></li><li><strong>hides an important constraint</strong></li><li>or <strong>creates invisible coupling</strong></li></ul><p>A good rule of thumb I use in large TypeScript codebases:</p><blockquote><em>If a utility type expression becomes hard to read, it has stopped communicating.</em></blockquote><p>At that point:</p><ul><li>Extract it</li><li>Name it</li><li>Or replace it with an explicit interface</li></ul><p>Because good types aren’t just about correctness.</p><p>They’re about <strong>making the architecture obvious to the next engineer who reads your code</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73f3e395b148" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Token Handling Best Practices: Lessons From My Journey]]></title>
            <link>https://medium.com/@benjannetahmed.03/token-handling-best-practices-lessons-from-my-journey-138866f4d24c?source=rss-5d5731c8c6ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/138866f4d24c</guid>
            <category><![CDATA[cookies]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[token-rotation]]></category>
            <category><![CDATA[jwt-token]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Ben Jannet Ahmed]]></dc:creator>
            <pubDate>Fri, 03 Oct 2025 00:49:51 GMT</pubDate>
            <atom:updated>2025-10-03T00:49:51.441Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*ld1CINq1Iej_7uT2vyZ_Uw.png" /></figure><p>When I started building authentication for my app, I thought it would be straightforward: generate a JWT, send it to the frontend, and done. But very quickly, I realized token handling is not as simple as it looks.</p><p>I’m still a junior developer, and I wouldn’t call myself an expert, but through trial, error, and a lot of reading, I learned a few things about how tokens should (and shouldn’t) be handled in modern applications. This post is both a recap of my research and my own journey. Hopefully, it helps someone who’s struggling with the same questions.</p><h3>Sessions vs Tokens</h3><p>At first, I wasn’t sure if I should stick to <strong>server-side sessions</strong> or go with <strong>tokens (JWTs)</strong>.</p><ul><li><strong>Sessions (server-side):</strong> The server stores the session, and the client just gets a session ID (usually in a cookie). This is secure and simple for classic web apps, but it doesn’t scale easily for APIs or mobile apps.</li><li><strong>Tokens (client-side):</strong> The server issues a signed token (JWT or similar) that the client stores and sends with each request. This works better for APIs and distributed systems, since the server doesn’t need to store state.</li></ul><p>👉 <strong>Best practice today:</strong> Tokens (JWTs) are the modern standard for SPAs, mobile apps, and microservices. Sessions are still fine for old-school server-rendered apps, but if you’re building an API or anything cross-platform, use tokens.</p><h3>Where to Store Tokens?</h3><p>This was another rabbit hole. Should tokens go in localStorage, sessionStorage, or cookies?</p><ul><li><strong>LocalStorage / SessionStorage</strong>: Easy to use, but vulnerable to XSS (malicious scripts can read them).</li><li><strong>Cookies</strong>: More secure if set with httpOnly (JS can’t access them). But you need to handle CSRF carefully.</li></ul><p>👉 <strong>Best practice today:</strong> Always store access and refresh tokens in <strong>httpOnly secure cookies</strong>.</p><ul><li><strong>Access tokens</strong> → short-lived (e.g. 15min — 1h), best stored in memory or httpOnly cookies.</li><li><strong>Refresh tokens</strong> → longer-lived (e.g. 7d), best stored in httpOnly cookies.</li></ul><p>So in my project, I store both access and refresh tokens in cookies, marked httpOnly and secure (in production).</p><h3>Bearer Header vs Cookies</h3><p>Another confusion point: should the client send tokens in an Authorization: Bearer &lt;token&gt; header, or let the cookie handle it?</p><ul><li><strong>Bearer header</strong>: Explicit, works best for APIs exposed to third parties.</li><li><strong>Cookies</strong>: Automatic, more convenient for first-party apps, but requires CSRF protection.</li></ul><p>👉 <strong>What I learned:</strong></p><ul><li>If you’re exposing a public API → Bearer headers are usually preferred.</li><li>If you control both frontend and backend → cookies with CSRF protection are the safer and cleaner choice.</li></ul><p>In my app, since I control both frontend and backend, I went with cookies.</p><h3>Refresh Tokens: Backend vs Frontend Logic</h3><p>One of the trickiest parts was deciding <em>where the refresh flow should happen</em>.</p><ul><li><strong>Backend refresh logic (inside guards/middleware):</strong></li><li>Pro: Transparent for the frontend.</li><li>Con: Can be harder to debug, and you risk complexity in guards.</li><li><strong>Frontend refresh logic (interceptors):</strong></li><li>Pro: More explicit control, retries can be queued.</li><li>Con: Slightly more work in the frontend.</li></ul><p>👉 <strong>What I learned:</strong><br> Both approaches are valid. Personally, I started with refresh in the backend, but later realized that handling it in the frontend with Axios interceptors gave me more control.</p><p>In my frontend, I built an Axios interceptor that:</p><ol><li>Catches 401 Unauthorized responses.</li><li>Pauses other requests.</li><li>Calls the refresh endpoint once.</li><li>Retries all pending requests with the new token.</li></ol><p>This flow felt much more predictable.</p><h3>Example From My Project (Axios + NestJS)</h3><p>Since theory is great but examples help, here’s how I applied this in my stack:</p><ul><li><strong>Frontend (Axios):</strong> I added a response interceptor that automatically retries requests after refreshing.</li><li><strong>Backend (NestJS with Passport):</strong> I used a JwtStrategy for access tokens and a guard that tries to refresh if the token is expired.</li></ul><p>Was it perfect? No. I broke it many times 😅 But I learned a lot about how important it is to handle edge cases, like revoked tokens or device-specific refresh logic.</p><h3>Should You Build It Yourself or Use a Provider?</h3><p>I also asked myself: should I reinvent the wheel, or use something like <strong>Keycloak</strong>, <strong>Auth0</strong>, or <strong>Clerk</strong>?</p><p>👉 <strong>What I learned:</strong></p><ul><li>If you’re <strong>a small team or early-stage project</strong>, building it yourself can be okay (as long as you follow best practices).</li><li>If you’re <strong>scaling or need enterprise features (SSO, identity federation, user management, audit logs, compliance)</strong> → using a third-party provider like Keycloak or Auth0 makes more sense.</li></ul><p>In my project, I built it myself because I wanted to learn. But if I were running a production SaaS with thousands of users, I’d probably consider outsourcing authentication to a battle-tested solution.</p><h3>Security Threats to Keep in Mind</h3><p>While researching, I also realized how tokens can be abused if not handled carefully:</p><ul><li><strong>XSS (Cross-Site Scripting):</strong> Can steal tokens if stored in localStorage.</li><li><strong>CSRF (Cross-Site Request Forgery):</strong> Can trick users into sending requests with their cookies.</li><li><strong>Token theft / reuse:</strong> Refresh tokens should be tied to a device and rotated.</li></ul><p>👉 <strong>Best practices I found helpful:</strong></p><ul><li>Always use httpOnly + secure cookies.</li><li>Rotate refresh tokens on each use.</li><li>Revoke tokens if suspicious activity is detected.</li><li>Set reasonable expiration times (short for access, longer for refresh).</li></ul><h3>Closing Thoughts</h3><p>I’m still learning, and I’ll probably refine my setup again in the future. But here are the takeaways I now follow:</p><p>✅ Use <strong>tokens (JWTs)</strong>, not sessions, for modern apps.<br> ✅ Store them in <strong>httpOnly secure cookies</strong>, not localStorage.<br> ✅ Use <strong>cookies</strong> for first-party apps, <strong>Bearer headers</strong> for public APIs.<br> ✅ Handle refresh with <strong>frontend interceptors</strong> (my preference) or backend guards.<br> ✅ Don’t be afraid to use <strong>Keycloak/Auth0</strong> if your project needs enterprise auth.</p><p>If you’re going through the same struggle, I hope this article saves you some headaches. And if you’re more experienced, I’d love to hear your thoughts and what worked for you? What mistakes should I avoid next?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=138866f4d24c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using http-proxy-middleware in NestJS: A Complete Guide]]></title>
            <link>https://medium.com/@benjannetahmed.03/using-http-proxy-middleware-in-nestjs-a-complete-guide-3b73dd777ab5?source=rss-5d5731c8c6ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b73dd777ab5</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[http-proxy-middleware]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Ben Jannet Ahmed]]></dc:creator>
            <pubDate>Thu, 11 Sep 2025 00:55:22 GMT</pubDate>
            <atom:updated>2025-10-12T18:30:59.728Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*lA1dPcoIKu3YQc4aVgluXw.png" /></figure><p>Sometimes your NestJS app doesn’t need to handle requests itself — it just needs to forward them to another service. This is common in microservice setups, where a gateway routes traffic to specialized services like authentication, payments, or file storage.</p><p>That’s where <strong>http-proxy-middleware</strong> comes in. It lets you drop a proxy into your NestJS app with just a few lines of code.</p><p>When I first tried this, it seemed straightforward. But I quickly ran into unexpected issues: routes getting eaten, bodies disappearing, path rewrites not working, and online examples using outdated options.</p><p>In this guide, I’ll show you two clean ways to integrate http-proxy-middleware in NestJS, the pitfalls I hit, and the fixes that made it all work.</p><h3>🔧 Option 1: Using http-proxy-middleware in main.ts</h3><p>Let’s say my gateway needs to proxy calls to an authentication microservice running at http://localhost:5010. A first attempt might look like this:</p><pre>// main.ts<br>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br>import { createProxyMiddleware } from &#39;http-proxy-middleware&#39;;<br><br>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br>  const authServiceUrl = &#39;http://localhost:5010&#39;;<br>  app.use(<br>    &#39;/auth&#39;, // all requests starting with /auth<br>    createProxyMiddleware({<br>      target: authServiceUrl,<br>      changeOrigin: true,<br>      logger: console,<br>      pathRewrite: { &#39;/oauth&#39;: &#39;/auth/oauth&#39; },<br>      on: {<br>        proxyRes(proxyRes, req, res) {<br>          res.header(&#39;Access-Control-Allow-Origin&#39;, req.headers.origin || &#39;*&#39;);<br>          res.header(&#39;Access-Control-Allow-Credentials&#39;, &#39;true&#39;);<br>        },<br>      },<br>    }),<br>  );<br>  await app.listen(3000);<br>}<br>bootstrap();</pre><h3>📝 Tips for main.ts usage</h3><ul><li>If you proxy /auth, be careful: app.use(&#39;/auth&#39;, ...) consumes everything under /auth.</li><li>For example, /auth/oauth/token might need a pathRewrite like above to work correctly.</li><li>Always apply pathRewrite before the middleware, or filter with an extra prefix like /gateway/auth/... → /auth/...</li><li>You can also conditionally rewrite paths with pathRewrite , which is useful if only one or two routes need special treatment.</li></ul><pre>pathRewrite: (path, req) =&gt; {<br>        // Example: handle only status differently<br>        if (path.startsWith(&#39;/auth/status&#39;)) {<br>          return path.replace(/^\/auth/, &#39;&#39;);<br>        }<br>        // otherwise keep it as is<br>        return path;<br>      },</pre><ul><li>Always use the on: { proxyRes(...) } style. Many examples online still show onProxyRes, which is deprecated.</li></ul><h3>🔧 Option 2: A Dedicated Proxy Controller</h3><p>Another approach is to put the proxy inside a controller. This is often <strong>cleaner</strong> .</p><pre>// proxy.controller.ts<br>import { Controller, Get, All, Inject } from &#39;@nestjs/common&#39;;<br>import { Request, Response } from &#39;express&#39;;<br>import { createProxyMiddleware, fixRequestBody } from &#39;http-proxy-middleware&#39;;<br><br>@Controller(&#39;auth&#39;)<br>export class ExternalAuthenticationController {<br>  private readonly proxy;<br>  constructor(<br>    @Inject(&#39;AUTHENTICATION_SERVICE&#39;) private authServiceUrl: string,<br>  ) {<br>    this.proxy = createProxyMiddleware({<br>      target: authServiceUrl,<br>      changeOrigin: true,<br>      logger: console,<br>      on: {<br>        proxyRes(proxyRes, req:Request, res:Response) {<br>          res.header(&#39;Access-Control-Allow-Origin&#39;, req.headers.origin || &#39;*&#39;);<br>          res.header(&#39;Access-Control-Allow-Credentials&#39;, &#39;true&#39;);<br>        },<br>        proxyReq: fixRequestBody, // fix body-parser conflicts<br>      },<br>    });<br>  }<br>  // Example of a normal endpoint (must come BEFORE @All)<br>  @Get(&#39;status&#39;)<br>  status() {<br>    return { message: &#39;Gateway is alive&#39; };<br>  }<br>  // Proxy everything else<br>  @All(&#39;*&#39;)<br>  proxyRequests(req, res, next) {<br>    return this.proxy(req, res, next);<br>  }<br>}</pre><h3>📝 Tips for controller usage</h3><ul><li>Regular endpoints like GET /auth/status still work, but they must be declared <strong>before</strong> the @All(&#39;*&#39;) catch-all proxy.</li><li>No need for path rewrites here — NestJS routing ensures your controller scope (@Controller(&#39;auth&#39;)) is preserved.</li><li>Using proxyReq: fixRequestBody solves a common issue where NestJS’s body-parser consumes the body before the proxy can forward it.</li></ul><h3>⚠️ Body Parser Conflicts Explained</h3><p>This was the biggest stumbling block.</p><p>By default, NestJS (via Express) uses body-parser, which consumes the request body before the proxy sees it. As a result, the proxied request often arrives with an empty body. Symptoms I saw:</p><ul><li>JSON payloads disappearing</li><li>application/x-www-form-urlencoded requests not reaching the backend properly</li></ul><h3>✅ Solution 1: Use fixRequestBody</h3><p>The recommended fix is to use fixRequestBody, which re-encodes the request before it’s sent:</p><pre>on: { proxyReq: fixRequestBody }</pre><p>This is usually enough and keeps body parsing intact for the rest of your NestJS routes.</p><h3>✅ Solution 2: Disable the Global Body Parser</h3><p>Another solution I explored was disabling NestJS’s body-parser entirely when bootstrapping:</p><pre>const app = await NestFactory.create&lt;NestExpressApplication&gt;(<br>  AppModule,<br>  { bodyParser: false },<br>);</pre><p>This avoids the conflict because the proxy receives the raw request body.</p><p>But there’s a big trade-off:</p><ul><li>It works well if your app is <strong>only</strong> acting as a proxy.</li><li>If you also have standard NestJS routes that need req.body, you’ll need to <strong>manually re-enable body-parser</strong> for those routes using a middleware</li></ul><p>This approach quickly became messy in my project. That’s why I went back to fixRequestBody, which is cleaner and more maintainable.</p><h3>⚙️ Commonly Used Options</h3><p>Here are some useful http-proxy-middleware options I found myself reaching for:</p><ul><li><strong>target</strong>: The destination server (required).</li><li><strong>changeOrigin</strong>: Changes the Host header to match the target (fixes many CORS issues).</li><li><strong>pathRewrite</strong>: Rewrite URL paths, either with an object or a function.</li><li><strong>logger</strong>: Set to console for easy debugging.</li><li><strong>secure</strong>: Set to false if your backend uses self-signed HTTPS certs.</li><li><strong>ws</strong>: Enable proxying WebSocket connections.</li><li><strong>cookieDomainRewrite</strong>: Rewrites cookies from the proxied response so they match your app’s domain.</li><li><strong>proxyTimeout</strong>: Timeout for proxy requests (useful for long-running APIs).</li><li><strong>on.proxyRes</strong>: Modify headers or log data from the response.</li><li><strong>on.proxyReq</strong>: Adjust the request before it’s sent (e.g., add headers, fix body).</li></ul><p>👉 For the full list, check : <a href="https://www.npmjs.com/package/http-proxy-middleware">https://www.npmjs.com/package/http-proxy-middleware</a>.</p><h3>✅ Conclusion</h3><p>Integrating http-proxy-middleware in NestJS lets your application act as a <strong>gateway</strong> to external services.</p><p>Two patterns are:</p><ul><li><strong>main.ts approach</strong> → fine, leans heavily on Express-style middleware. It’s quick, but it breaks the mental model of NestJS (modules, controllers, providers). It’s useful when you just need a couple of proxy routes without much structure.</li><li><strong>A dedicated controller approach</strong> →cleaner, fits right into NestJS’s philosophy. You keep your proxy logic inside a module/controller, it plays well with DI, and you can mix proxied endpoints with normal routes. It also avoids the messy path rewrite tricks that main.ts often needs.</li></ul><p>The biggest gotcha is body parsing — and in most cases, simply adding proxyReq: fixRequestBody saves you from days of debugging.</p><p>With these patterns, you can confidently set up a proxy layer in your NestJS app and avoid the same traps I fell into.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b73dd777ab5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parent vs. Child: Where to Handle Conditional Rendering in React?]]></title>
            <link>https://medium.com/@benjannetahmed.03/parent-vs-child-where-to-handle-conditional-rendering-in-react-3a42eb384c3e?source=rss-5d5731c8c6ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a42eb384c3e</guid>
            <category><![CDATA[conditional-rendering]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend-best-practices]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ben Jannet Ahmed]]></dc:creator>
            <pubDate>Sun, 23 Mar 2025 12:40:02 GMT</pubDate>
            <atom:updated>2025-03-24T20:46:46.611Z</atom:updated>
            <content:encoded><![CDATA[<p>Conditional rendering is a fundamental concept in React development, allowing components to appear based on specific states or conditions. However, where you place those conditions — whether in the parent or the child component — can have a significant impact on your app’s behavior, performance, and reliability.</p><p>In this article, we will explore the differences between handling rendering conditions in the parent component versus passing them as props to the child. We’ll also use an example to showcase how the DOM behaves in each scenario and highlight the implications of these choices. This will help us understand how background logic, such as lifecycle methods or useEffect, can still run even when a component is not visibly rendered.</p><p>Whether you’re new to React or looking to refine your development practices, this guide will help you make informed decisions about conditional rendering and avoid hidden bugs in your applications.</p><h3>The Concept of Conditional Rendering:</h3><p>Conditional rendering is a technique in React that determines whether a component or part of a component should be rendered based on a specific condition. This is achieved by using JavaScript expressions directly within JSX, enabling dynamic and flexible UI updates.</p><p>For example:</p><pre>function Greeting({ isLoggedIn }) {<br>  return (<br>    &lt;div&gt;<br>      {isLoggedIn ? &lt;h1&gt;Welcome back!&lt;/h1&gt; : &lt;h1&gt;Please sign in.&lt;/h1&gt;}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Here, the Greeting component dynamically renders a message depending on the value of the isLoggedIn prop.</p><p>This approach is essential for building interactive and user-friendly applications, but the way these conditions are applied — either at the parent or child level — can have significant implications. Let’s explore these differences in detail through a practical example.</p><h3>Example Scenario:</h3><p>Consider two similar components: UpdateUserForm for editing a user&#39;s details and CreateUserForm for creating a new user. These components highlight the importance of choosing where to handle conditional rendering.</p><h4>UpdateUserForm: Parent-Level Conditional Rendering</h4><p>The UpdateUserForm component relies on data passed from the parent, such as the selectedUser object. To avoid errors, it’s better to conditionally render this component in the parent based on the availability of the selectedUser:</p><p><strong>Parent Component:</strong></p><pre>{isOpenUserForm &amp;&amp; (<br>  &lt;UpdateUserForm<br>    onClose={handleCloseUserForm}<br>    user={selectedUser}<br>  /&gt;<br>)}</pre><p><strong>Child Component:</strong></p><pre>function UpdateUserForm({ onClose, user }) {<br>  const [formData, setFormData] = useState({ firstName: &#39;&#39;, lastName: &#39;&#39;, role: &#39;&#39; });<br><br>  useEffect(() =&gt; {<br>    if (user) {<br>      setFormData({<br>        firstName: user.firstName || &#39;&#39;,<br>        lastName: user.lastName || &#39;&#39;,<br>        role: user.role || &#39;&#39;,<br>      });<br>    }<br>  }, [user]);<br><br>  return (<br>    &lt;form onSubmit={(e) =&gt; e.preventDefault()}&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        name=&quot;firstName&quot;<br>        value={formData.firstName}<br>        onChange={(e) =&gt; setFormData({ ...formData, firstName: e.target.value })}<br>        placeholder=&quot;First Name&quot;<br>      /&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        name=&quot;lastName&quot;<br>        value={formData.lastName}<br>        onChange={(e) =&gt; setFormData({ ...formData, lastName: e.target.value })}<br>        placeholder=&quot;Last Name&quot;<br>      /&gt;<br>      &lt;button type=&quot;button&quot; onClick={onClose}&gt;Cancel&lt;/button&gt;<br>      &lt;button type=&quot;submit&quot;&gt;Update&lt;/button&gt;<br>    &lt;/form&gt;<br>  )<br>}</pre><p>By rendering the UpdateUserForm only when selectedUser is available, we avoid unnecessary logic execution in the child, such as setting formData for a null or undefined user.</p><h4>CreateUserForm: Prop-Based Conditional Rendering</h4><p>In contrast, the CreateUserForm component does not depend on external data. It can preload information (like fetching roles) even when it’s not visible, making it a good candidate for prop-based conditional rendering:</p><p><strong>Parent Component:</strong></p><pre>&lt;CreateUserForm isOpen={isOpenCreateForm} onClose={handleCloseCreateForm} /&gt;</pre><p><strong>Child Component</strong>:</p><pre>function CreateUserForm({ isOpen, onClose }) {<br>  const [roles, setRoles] = useState([]);<br>  const [formData, setFormData] = useState({ firstName: &#39;&#39;, lastName: &#39;&#39;, role: &#39;&#39; });<br><br>  useEffect(() =&gt; {<br>    const fetchRoles = async () =&gt; {<br>      const response = await fetch(&#39;/api/roles&#39;);<br>      const data = await response.json();<br>      setRoles(data);<br>    };<br>    fetchRoles();<br>  }, []);<br><br>  return isOpen ? (<br>    &lt;form onSubmit={(e) =&gt; e.preventDefault()}&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        name=&quot;firstName&quot;<br>        value={formData.firstName}<br>        onChange={(e) =&gt; setFormData({ ...formData, firstName: e.target.value })}<br>        placeholder=&quot;First Name&quot;<br>      /&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        name=&quot;lastName&quot;<br>        value={formData.lastName}<br>        onChange={(e) =&gt; setFormData({ ...formData, lastName: e.target.value })}<br>        placeholder=&quot;Last Name&quot;<br>      /&gt;<br>      &lt;select<br>        name=&quot;role&quot;<br>        value={formData.role}<br>        onChange={(e) =&gt; setFormData({ ...formData, role: e.target.value })}<br>      &gt;<br>        {roles.map((role) =&gt; (<br>          &lt;option key={role.id} value={role.name}&gt;{role.name}&lt;/option&gt;<br>        ))}<br>      &lt;/select&gt;<br>      &lt;button type=&quot;button&quot; onClick={onClose}&gt;Cancel&lt;/button&gt;<br>      &lt;button type=&quot;submit&quot;&gt;Create&lt;/button&gt;<br>    &lt;/form&gt;<br>  ) : null;<br>}</pre><p>By keeping CreateUserForm mounted, roles are fetched in the background, ensuring a smooth user experience when the form becomes visible.</p><h3>How the DOM Reacts:</h3><p>The way the DOM behaves in these two approaches differs significantly, especially in how React manages the lifecycle of components.</p><h4>Parent-Level Conditional Rendering:</h4><p>When the parent conditionally renders the UpdateUserForm, it is not mounted in the DOM until the condition (isOpenUserForm) becomes true. This means:</p><ul><li><strong>No </strong><strong>useEffect Execution</strong>: Any useEffect hooks, API calls, or other logic in the child component are completely skipped until the component is mounted.</li><li><strong>Performance Efficiency</strong>: By not rendering unnecessary components, React optimizes resource usage.</li><li><strong>Predictable Behavior</strong>: No unexpected background logic runs while the component is hidden.</li></ul><h4>Prop-Based Conditional Rendering:</h4><p>When the CreateUserForm is always mounted and its visibility is controlled via props:</p><ul><li><strong>Background Logic Runs</strong>: Even if the component is not visible, any useEffect hooks or logic inside the child will execute.</li><li><strong>Preloading</strong>: Data like roles can be pre-fetched, reducing delays when the form becomes visible.</li><li><strong>Potential Bugs</strong>: If logic depends on uninitialized data from the parent, it could fail.</li></ul><h3>When to Use Each Approach:</h3><p>The choice between parent-level conditional rendering and prop-based conditional rendering depends on the specific requirements of your application. Here are some guidelines:</p><h4>Use Parent-Level Conditional Rendering When:</h4><ol><li><strong>Performance Is Critical</strong>: Avoid mounting components that are not needed to conserve resources.</li><li><strong>Background Logic Must Be Skipped</strong>: Prevent API calls or other logic from running unnecessarily.</li><li><strong>Parent Provides Dynamic Data</strong>: Ensure all required parameters are set before mounting the child.</li></ol><h4>Use Prop-Based Conditional Rendering When:</h4><ol><li><strong>Preloading Is Beneficial</strong>: If the child component needs to prepare data or perform operations in the background, this approach is ideal.</li><li><strong>Independent Logic</strong>: When the child does not depend heavily on dynamic data from the parent.</li><li><strong>Immediate Rendering Is Required</strong>: For better user experience, where delays in rendering are not acceptable.</li></ol><p>By understanding these scenarios, you can choose the approach that best suits your application’s needs and avoid common pitfalls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZqYn2XEwz3KKCPqeIJgIpw.png" /></figure><h3>Conclusion</h3><p>Choosing where to place your rendering condition — in the parent or child — can significantly affect your app’s behavior and performance. Understanding the implications of each approach allows you to make informed decisions tailored to your specific use case. By analyzing the dependencies and behavior of your components, you can strike a balance between efficiency and functionality, ensuring a seamless user experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a42eb384c3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>