<?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 Muhammad Khoirudin on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Khoirudin on Medium]]></description>
        <link>https://medium.com/@mk.muhammadkhoirudin?source=rss-ea3f3bfa423c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MPMQewJoPOV1n4Pp5Y81aA.jpeg</url>
            <title>Stories by Muhammad Khoirudin on Medium</title>
            <link>https://medium.com/@mk.muhammadkhoirudin?source=rss-ea3f3bfa423c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 17:05:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mk.muhammadkhoirudin/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[React — Implementing Hybrid Authorization Using NET Core API]]></title>
            <link>https://medium.com/@mk.muhammadkhoirudin/react-implementing-hybrid-authorization-using-net-core-api-7f3b7cbf8a8c?source=rss-ea3f3bfa423c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f3b7cbf8a8c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Muhammad Khoirudin]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 06:45:16 GMT</pubDate>
            <atom:updated>2026-04-10T06:45:16.373Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*sHLks5KmEhSpxghRyyZgKA.png" /></figure><p>Pre-Requirite</p><ul><li>Understanding about NET Core (Minimal API)</li><li>Understanding about Authentication using JWT (Refer to <a href="https://medium.com/@mk.muhammadkhoirudin/jwt-and-refresh-token-management-a039ca3e04fd"><strong><em>first article</em></strong></a> then <a href="https://medium.com/@mk.muhammadkhoirudin/react-jwt-authentication-refresh-token-179df9f8d8b6"><strong><em>second article</em></strong></a>)</li><li>Understanding about Authorization using Role-Based &amp; Policy-Based. (Refer to <a href="https://medium.com/@mk.muhammadkhoirudin/rbac-and-policy-based-authorization-approaches-92c8a266c3ac"><strong><em>this article</em></strong></a>)</li></ul><p>When you have done with those knowledge, let’s code.</p><p><strong><em>React Repository </em></strong>: <a href="https://github.com/khoirmuhammad/website/tree/react-role">https://github.com/khoirmuhammad/website/tree/react-role</a></p><p><strong><em>Net Core API Repository</em></strong> : <a href="https://github.com/khoirmuhammad/ReactApi/tree/react-role">https://github.com/khoirmuhammad/ReactApi/tree/react-role</a></p><h3>BACKEND API — NET CORE</h3><h4>1. Detailed Explanation: Authorization Classes — PermissionRequirement, PermissionHandler, PermissionPolicyProvider</h4><p>These classes implement a custom authorization system. In a simple implementation, programmer can only put this attribute to every endpoint method</p><pre>[HttpPost]<br>[Authorize(Policy = &quot;NewsCreate&quot;)]<br>public IActionResult Create()<br>{<br>    return Ok(&quot;News created&quot;);<br>}<br><br>//.......<br><br>options.AddPolicy(&quot;NewsCreate&quot;, policy =&gt;<br>        policy.RequireClaim(&quot;permission&quot;, &quot;news.create&quot;));</pre><p>Flow</p><ul><li>PermissionRequirement : It defines a specific permission (e.g., “user.read”)</li><li>PermissionHandler : It checks if the current user has that permission</li><li>PermissionPolicyProvider : dynamically provides authorization policies when you ask for “Permission:xxx”</li></ul><p><strong>1️⃣ PermissionRequirement</strong></p><pre>public class PermissionRequirement : IAuthorizationRequirement<br>{<br>    public string Permission { get; }<br>    <br>    // PermissionRequirement(&quot;user.read&quot;)<br>    public PermissionRequirement(string permission)<br>    {<br>        Permission = permission;<br>    }<br>}</pre><p><strong>2️⃣ PermissionHandler</strong></p><pre>public class PermissionHandler : AuthorizationHandler&lt;PermissionRequirement&gt;<br>{<br>    protected override Task HandleRequirementAsync(<br>        AuthorizationHandlerContext context,<br>        PermissionRequirement requirement)<br>    {<br>        // Read all permissions claims from JWT.<br>        var permissions = context.User.FindAll(&quot;permissions&quot;)<br>                                      .Select(c =&gt; c.Value);<br><br>        // Check if the required permission exists<br>        if (permissions.Contains(requirement.Permission))<br>        {<br>            // Marks authorization as successful.<br>            context.Succeed(requirement);<br>        }<br><br>        return Task.CompletedTask;<br>    }<br>}</pre><p><strong>3️⃣ PermissionPolicyProvider</strong></p><pre>public class PermissionPolicyProvider : DefaultAuthorizationPolicyProvider<br>{<br>    public PermissionPolicyProvider(IOptions&lt;AuthorizationOptions&gt; options)<br>    : base(options)<br>    {<br>    }<br><br>    public override Task&lt;AuthorizationPolicy?&gt; GetPolicyAsync(string policyName)<br>    {<br>        // If policy name starts with &quot;Permission:&quot;, extract the actual permission string.<br>        // &quot;Permission:user.read&quot;<br>        if (policyName.StartsWith(&quot;Permission:&quot;))<br>        {<br>            // &quot;user.read&quot;<br>            var permission = policyName.Split(&#39;:&#39;)[1];<br><br>            var policy = new AuthorizationPolicyBuilder()<br>                .AddRequirements(new PermissionRequirement(permission))<br>                .Build();<br><br>            return Task.FromResult&lt;AuthorizationPolicy?&gt;(policy);<br>        }<br><br>        return base.GetPolicyAsync(policyName);<br>    }<br>}</pre><p>Register to DI</p><pre>builder.Services.AddSingleton&lt;IAuthorizationPolicyProvider, PermissionPolicyProvider&gt;();<br>builder.Services.AddScoped&lt;IAuthorizationHandler, PermissionHandler&gt;();</pre><h4>2. Authentication / Token Generation</h4><p><strong>1️. Login Endpoint</strong></p><pre>app.MapPost(&quot;/login&quot;, (LoginRequest req, HttpResponse res, TokenHelper tokenHelper, FileHelper fileHelper) =&gt;<br>{<br>    // Validates username/password. Hardcoded example for demo purposes.<br>    // Could be replaced with a DB check<br>    string[] usernameList = [&quot;president&quot;, &quot;vicePresident&quot;, &quot;governor&quot;];<br>    if (!usernameList.Contains(req.Username) || req.Password != &quot;password&quot;)<br>        return Results.Unauthorized();<br><br>    // Check role, Could be replaced with a DB check<br>    string role = string.Empty;<br>    if (req.Username == &quot;president&quot;) { role = &quot;president&quot;; }<br>    else if (req.Username == &quot;vicePresident&quot;) { role = &quot;vicePresident&quot;; }<br>    else if (req.Username == &quot;governor&quot;) { role = &quot;governor&quot;; }<br><br></pre><p><strong>2. Refresh Endpoint</strong></p><pre>var token = req.Cookies[&quot;refreshToken&quot;];<br>if (string.IsNullOrEmpty(token)) return Results.Unauthorized();<br><br>var tokens = fileHelper.Read&lt;RefreshTokenRecord&gt;(RefreshFile);<br>var record = tokens.FirstOrDefault(t =&gt;<br>    t.RefreshTokenHash == tokenHelper.HashToken(token) &amp;&amp; !t.Revoked);<br><br>if (record == null || record.ExpiresAt &lt; DateTime.UtcNow)<br>    return Results.Unauthorized();<br><br>// In login section, we can put role info into record data, to reduce role checking into DB<br>// Or once yo get username/id, then call query to get user role<br>string role = string.Empty;<br>if (record.UserId == &quot;president&quot;)<br>{<br>    role = &quot;president&quot;;<br>}<br>else if (record.UserId == &quot;vicePresident&quot;)<br>{<br>    role = &quot;vicePresident&quot;;<br>}<br>else if (record.UserId == &quot;governor&quot;)<br>{<br>    role = &quot;governor&quot;;<br>}</pre><p><strong>3. Protected Endpoints Example</strong></p><pre>// Implement permission policies, not just roles.<br><br>// PermissionPolicyProvider creates policy &quot;Permission:user.read&quot;<br>// PermissionHandler checks if user has user.read claim.<br>userGroup.MapGet(&quot;/&quot;, () =&gt; Results.Ok(&quot;Read Successful&quot;))<br>    .RequireAuthorization(&quot;Permission:user.read&quot;);<br><br>userGroup.MapPost(&quot;/&quot;, () =&gt; Results.Created(&quot;&quot;, &quot;Created&quot;))<br>    .RequireAuthorization(&quot;Permission:user.create&quot;);</pre><p><strong>4. Generate Token &amp; Claims</strong></p><pre>    // We can move this config into database, so be more scalable and maintainable<br>    var permissions = role switch<br>    {<br>        &quot;president&quot; =&gt; new[]<br>        {<br>            &quot;post.create&quot;,&quot;post.read&quot;,&quot;post.update&quot;,&quot;post.delete&quot;,&quot;post.detail&quot;,<br>            &quot;user.create&quot;,&quot;user.read&quot;,&quot;user.update&quot;,&quot;user.delete&quot;,&quot;user.detail&quot;,<br>            &quot;news.create&quot;,&quot;news.read&quot;,&quot;news.update&quot;,&quot;news.delete&quot;,&quot;news.detail&quot;,<br>            &quot;article.create&quot;,&quot;article.read&quot;,&quot;article.update&quot;,&quot;article.delete&quot;,&quot;article.detail&quot;<br>        },<br>        &quot;governor&quot; =&gt; new[]<br>        {<br>            &quot;user.read&quot;,&quot;news.read&quot;,&quot;article.read&quot;<br>        },<br>        &quot;vicePresident&quot; =&gt; new[]<br>        {<br>            &quot;user.read&quot;,&quot;user.detail&quot;,<br>            &quot;post.read&quot;,&quot;post.detail&quot;,<br>            &quot;news.create&quot;,&quot;news.read&quot;,&quot;news.update&quot;,&quot;news.delete&quot;,&quot;news.detail&quot;,<br>            &quot;article.create&quot;,&quot;article.read&quot;,&quot;article.update&quot;,&quot;article.delete&quot;,&quot;article.detail&quot;<br>        },<br>        _ =&gt; Array.Empty&lt;string&gt;()<br>    };<br><br>    // (Optional) Data Scope example<br>    var scopes = role switch<br>    {<br>        &quot;president&quot; =&gt; new[] { &quot;Province 1&quot;, &quot;Province 2&quot;, &quot;Province 3&quot; },<br>        &quot;vicePresident&quot; =&gt; new[] { &quot;Province 1&quot;, &quot;Province 2&quot;, &quot;Province 3&quot; },<br>        &quot;governor&quot; =&gt; new[] { &quot;Province 1&quot; }, // example: user belongs to Province 1<br>        _ =&gt; Array.Empty&lt;string&gt;()<br>    };<br><br>    // Base claims<br>    var claims = new List&lt;Claim&gt;<br>    {<br>        new Claim(ClaimTypes.Name, username),<br>        new Claim(&quot;role&quot;, role)<br>    };<br><br>    // Add permissions<br>    claims.AddRange(permissions.Select(p =&gt; new Claim(&quot;permissions&quot;, p)));<br><br>    // Add scope (important for data filtering)<br>    claims.AddRange(scopes.Select(s =&gt; new Claim(&quot;data_scope&quot;, s)));</pre><h3>CLIENT — REACT JS</h3><h4>File utils/parseToken</h4><p>This code resposible for</p><ul><li>Decode the JWT token in the React app</li><li>Extract important user info (role, permissions, scopes, username) and mapping data into a clean object (UserInfo)</li></ul><pre>import { jwtDecode } from &quot;jwt-decode&quot;;<br><br>// Define Token Shape (DecodedToken)<br>// It&#39;s TypeScript type defines the structure of an object<br>type DecodedToken = {<br>  role?: string;<br>  permissions?: string[] | string; // It can be [&quot;READ&quot;, &quot;WRITE&quot;] or &quot;READ&quot;<br>  data_scope?: string[] | string;<br>  &quot;http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name&quot;?: string; // This is a standard .NET claim key<br>};<br><br>// FInal format shape that used by React UI<br>export type UserInfo = {<br>  username: string;<br>  role: string;<br>  permissions: string[]; // Backend may return string / array, but client will always show in array<br>  scopes: string[];<br>};<br><br>// input param should be string, return UserInfo (success), null (error)<br>export const parseToken = (token: string): UserInfo | null =&gt; {<br>  try {<br>    const decoded = jwtDecode&lt;DecodedToken&gt;(token);<br><br>    return {<br>      // Gets username from token, if missing return empty string<br>      username:<br>        decoded[&quot;http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name&quot;] ||<br>        &quot;&quot;,<br>      role: decoded.role || &quot;&quot;,<br>      // If already in array use it directy<br>      // If in string, convert to array<br>      // If null/empty/missing, return empty array<br>      permissions: Array.isArray(decoded.permissions)<br>        ? decoded.permissions<br>        : decoded.permissions<br>          ? [decoded.permissions]<br>          : [],<br>      scopes: Array.isArray(decoded.data_scope)<br>        ? decoded.data_scope<br>        : decoded.data_scope<br>          ? [decoded.data_scope]<br>          : [],<br>    };<br>  } catch {<br>    return null;<br>  }<br>};</pre><h4>File provider/AuthProvider.ts</h4><p>In <a href="https://medium.com/@mk.muhammadkhoirudin/react-jwt-authentication-refresh-token-179df9f8d8b6"><strong><em>previous article</em></strong></a>, it has explained in detail about this file’s responsibilities, i.e. :</p><ol><li>Managing authentication globally : Is user logged-in? , What permissions do they have?</li><li>Providing auth functions : login and logout.</li><li>Restoring session after refresh (F5 / CTR + Shift + R)</li></ol><pre>import { createContext, useEffect, useState } from &quot;react&quot;;<br>import apiClient, {<br>  setAccessToken,<br>  setExpAccessToken,<br>  registerAuthHandlers,<br>} from &quot;../api/client&quot;;<br>// Converts JWT to clean user object<br>import { parseToken, type UserInfo } from &quot;../utils/parseToken&quot;;<br><br>type AuthContextType = {<br>  isAuthenticated: boolean;<br>  isLoading: boolean;<br>  user: UserInfo | null;<br>  login: (username: string, password: string) =&gt; Promise&lt;void&gt;;<br>  logout: () =&gt; Promise&lt;void&gt;;<br>};<br><br>// createContext : it like a global storage/state for an app<br>// Without this, we have to passing props : &lt;App user={user}&gt;<br>// eslint-disable-next-line react-refresh/only-export-components<br>export const AuthContext = createContext&lt;AuthContextType | null&gt;(null);<br><br>// eslint-disable-next-line @typescript-eslint/no-explicit-any<br>export const AuthProvider = ({ children }: any) =&gt; {<br>  const [isAuthenticated, setIsAuthenticated] = useState(false);<br>  const [isLoading, setIsLoading] = useState(true);<br>  const [user, setUser] = useState&lt;UserInfo | null&gt;(null); // No user initially<br><br>  useEffect(() =&gt; {<br>    registerAuthHandlers(<br>      () =&gt; {<br>        setIsAuthenticated(true);<br><br>        const token = sessionStorage.getItem(&quot;accessToken&quot;);<br><br>        if (token) {<br>          const parsed = parseToken(token); // Rebuild user info after refresh<br>          setUser(parsed); // UPDATE USER INFO AFTER REFRESH / F5<br>        }<br>      },<br>      () =&gt; {<br>        setIsAuthenticated(false);<br>        setUser(null); // CLEAR USER INFO<br>      },<br>    );<br><br>    const initAuth = async () =&gt; {<br>      try {<br>        await apiClient.get(&quot;/me&quot;); // Is this user still logged in?<br>        // if browser reload (React state (useState&lt;UserInfo&gt;) is lost on refresh), we still get userInfo<br>        const token = sessionStorage.getItem(&quot;accessToken&quot;);<br><br>        if (token) {<br>          const parsed = parseToken(token);<br>          setUser(parsed); // ✅ restore user<br>        }<br><br>        setIsAuthenticated(true);<br>        // eslint-disable-next-line @typescript-eslint/no-explicit-any<br>      } catch (error: any) {<br>        // FULL DEBUG INFO<br>        if (error.response) {<br>          console.log(&quot;Status:&quot;, error.response.status);<br>          console.log(&quot;Data:&quot;, error.response.data);<br>        }<br><br>        if (error.request) {<br>          console.log(&quot;No response received:&quot;, error.request);<br>        }<br><br>        console.log(&quot;Message:&quot;, error.message);<br><br>        setIsAuthenticated(false);<br>      } finally {<br>        setIsLoading(false);<br>      }<br>    };<br><br>    initAuth();<br>  }, []);<br><br>  //........................................................<br>};</pre><p>Based on above piece of code, we learn two things</p><ol><li>State : actual data stored inside a component</li><li>Context : a way to share state across many components</li></ol><pre>// State : <br>const [isAuthenticated, setIsAuthenticated] = useState(false);<br>const [isLoading, setIsLoading] = useState(true);<br>const [user, setUser] = useState&lt;UserInfo | null&gt;(null);<br><br>// Context<br>export const AuthContext = createContext&lt;AuthContextType | null&gt;(null);</pre><h4>File Hooks — hooks/auth/useScope &amp; usePermission</h4><p>Both are custom React hooks. It like a reusable logic we can plug into any component. Without this, code will be messy, since it must be implemented on each component.</p><p>What Do These Hooks Do? First, getting user data from AuthContext and provide a simple function to check authorization.</p><pre>import { useContext } from &quot;react&quot;;<br>import { AuthContext } from &quot;../../provider/AuthProvider&quot;;<br><br>export const usePermission = () =&gt; {<br>  const context = useContext(AuthContext);<br>  const user = context?.user;<br><br>  // Does user have this permission?<br>  const can = (permission: string) =&gt; {<br>    return user?.permissions?.includes(permission);<br>  };<br><br>  return { can };<br>};<br><br>export const useScope = () =&gt; {<br>  const context = useContext(AuthContext);<br>  const user = context?.user;<br><br>  // Does user have this scope?<br>  const hasScope = (scope: string) =&gt; {<br>    return user?.scopes?.includes(scope);<br>  };<br><br>  return { hasScope };<br>};</pre><h4>File config/permission.ts</h4><p>This is a constant object, instead of hardcoded, better use this approach. It prevents from typo, inconsistent format etc.</p><pre>// Convention for constants (Uppercase)<br>// Why Uppercase? Easy to recognize &amp; Not meant to change<br>export const PERMISSIONS = {<br>  POST_READ: &quot;post.read&quot;,<br>  POST_CREATE: &quot;post.create&quot;,<br>  POST_UPDATE: &quot;post.update&quot;,<br>  POST_DELETE: &quot;post.delete&quot;,<br>  POST_DETAIL: &quot;post.detail&quot;,<br><br>  //.....................<br>} as const;</pre><h4>File router/ProtectedRouter.tsx</h4><p>This is a component wrapper, that must pass children component and string permission.</p><pre>export default function ProtectedRoute({ children, permission }: ProtectedRouteProps)<br><br>// How to use -&gt; Implemented to AppRouter<br>&lt;ProtectedRoute permission={PERMISSIONS.USER_READ}&gt;<br>  &lt;UserPage /&gt;<br>&lt;/ProtectedRoute&gt;</pre><pre>// If route requires permission AND user does NOT have its permission<br>f (permission &amp;&amp; !user?.permissions.includes(permission)) {<br>  return &lt;div&gt;403 - Forbidden&lt;/div&gt;;<br>}</pre><h4>File component/auth/PermissionComponent.tsx</h4><p>This is a conditional rendering component based on permission. It means only show this component if he user has a permission which are desired.</p><p>Why we still need this one? While ProtectedRoute protects cmponent (pages), this component protects small component like button, link, card, action (edit, delete, view)</p><pre>import { useAuth } from &quot;../../hooks/auth/useAuth&quot;;<br><br>type CanProps = {<br>  permission?: string;<br>  children: React.ReactNode; // what to show if allowed<br>  fallback?: React.ReactNode; // what to show if NOT allowed,  optional (for disable case)<br>};<br><br>export const PermissionComponent = ({<br>  permission,<br>  children,<br>  fallback = null,<br>}: CanProps) =&gt; {<br>  const { user } = useAuth();<br><br>  if (!permission) return &lt;&gt;{children}&lt;/&gt;;<br><br>  const hasPermission = user?.permissions.includes(permission);<br><br>  // Show fallback (default = null → show nothing) when user doesn&#39;t have permission<br>  if (!hasPermission) return &lt;&gt;{fallback}&lt;/&gt;;<br><br>  return &lt;&gt;{children}&lt;/&gt;;<br>};</pre><pre>if (!permission) return &lt;&gt;{children}&lt;/&gt;;</pre><p>Why do we still render the children when no permission is given?<br> Because PermissionComponent is designed to be flexible and only enforce authorization when a permission is provided. It means :</p><pre>// Both are equals<br><br>&lt;PermissionComponent&gt;<br>  &lt;button&gt;View&lt;/button&gt;<br>&lt;/PermissionComponent&gt;<br><br>&lt;button&gt;View&lt;/button&gt;</pre><p><strong>How to use</strong></p><pre>// Hide Button if user doesn&#39;t have PERMISSIONS.USER_DELETE<br>&lt;PermissionComponent permission={PERMISSIONS.USER_DELETE}&gt;<br>  &lt;button&gt;Delete User&lt;/button&gt;<br>&lt;/PermissionComponent&gt;<br><br>// Show Alternative UI : Text &quot;No access&quot;<br>&lt;PermissionComponent<br>  permission={PERMISSIONS.USER_DELETE}<br>  fallback={&lt;span&gt;No access&lt;/span&gt;}<br>&gt;<br>  &lt;button&gt;Delete User&lt;/button&gt;<br>&lt;/PermissionComponent&gt;<br><br>// Disabled instead of hide<br>&lt;PermissionComponent<br>  permission={PERMISSIONS.USER_UPDATE}<br>  fallback={&lt;button disabled&gt;Edit&lt;/button&gt;}<br>&gt;<br>  &lt;button&gt;Edit&lt;/button&gt;<br>&lt;/PermissionComponent&gt;</pre><h4>File config/navigation.ts</h4><p>This is a configuration array for our navigation menu. We can set menu label (Text shown in UI), path (Route URL) and permission (Required permission to see it). Instead of hardcoded menu, we create dynamic and permission-based menu.</p><p>Example : User can only access /users if only has “user.read” permission.</p><pre>export const navItems = [<br>  {<br>    label: &quot;Posts&quot;,<br>    path: &quot;/&quot;,<br>    permission: &quot;post.read&quot;,<br>  },<br>  {<br>    label: &quot;Users&quot;,<br>    path: &quot;/users&quot;,<br>    permission: &quot;user.read&quot;,<br>  },<br>  {<br>    label: &quot;News&quot;,<br>    path: &quot;/news&quot;,<br>    permission: &quot;news.read&quot;,<br>  },<br>  {<br>    label: &quot;Articles&quot;,<br>    path: &quot;/articles&quot;,<br>    permission: &quot;article.read&quot;,<br>  },<br>];</pre><h4>File components/common/Layout.tsx</h4><ul><li>Dynamically renders menu items</li><li>Filters them based on user permissions</li></ul><pre>&lt;nav className=&quot;flex items-center gap-6&quot;&gt;<br>        {navItems<br>          .filter((item) =&gt; can(item.permission))<br>          .map((item) =&gt; (<br>            &lt;NavLink<br>              key={item.path}<br>              to={item.path}<br>              className={({ isActive }) =&gt; // isActive is automatically provided by NavLink from react-router-dom<br>                `<br>                  text-sm font-medium transition<br>                  ${<br>                    isActive<br>                      ? &quot;text-blue-600 border-b-2 border-blue-600 pb-1&quot;<br>                      : &quot;text-gray-600 hover:text-blue-600&quot;<br>                  }<br>                `<br>              }<br>            &gt;<br>              {item.label}<br>            &lt;/NavLink&gt;<br>          ))}<br>      &lt;/nav&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f3b7cbf8a8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RBAC and Policy-Based Authorization Approaches]]></title>
            <link>https://medium.com/@mk.muhammadkhoirudin/rbac-and-policy-based-authorization-approaches-92c8a266c3ac?source=rss-ea3f3bfa423c------2</link>
            <guid isPermaLink="false">https://medium.com/p/92c8a266c3ac</guid>
            <category><![CDATA[rbac-access-control]]></category>
            <category><![CDATA[auth-policy]]></category>
            <dc:creator><![CDATA[Muhammad Khoirudin]]></dc:creator>
            <pubDate>Tue, 07 Apr 2026 14:28:45 GMT</pubDate>
            <atom:updated>2026-04-07T14:28:45.766Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*kVFqSfFG4o20U8JacuiPdg.png" /><figcaption><a href="https://dev.to/karimelghamry/authentication-and-authorization-a-comprehensive-guide-47e9">https://dev.to/karimelghamry/authentication-and-authorization-a-comprehensive-guide-47e9</a></figcaption></figure><p>By reading <a href="https://medium.com/@mk.muhammadkhoirudin/jwt-and-refresh-token-management-a039ca3e04fd"><strong>this article</strong></a>, we gain insight into implementing authentication using JWT, as well as how to implement refresh tokens. Authentication answers the question, “Who are you?” But is that enough? No.</p><p>As applications grow rapidly and more users interact with them, we often need to control which users can access certain resources. Some users should be allowed to perform specific actions, while others should not.</p><p>If an application is only used by a few users, we might take a simple approach like this</p><pre>if (user.Name == &quot;admin1&quot;) { ... }<br><br>if (user.Name == &quot;admin2&quot;) { ... }<br><br>if (user.Name == &quot;admin3&quot;) { ... }</pre><p>But as systems grow, either in features or in the number of users. We can no longer rely on hardcoded checks like that. This approach makes the application difficult to scale and maintain. Therefore, we need structured authorization models. This is where RBAC and Policy-Based Authorization come in.</p><h3>RBAC (Role-Based Access Control)</h3><p><strong>RBAC (Role-Based Access Control)</strong> is a way to manage permissions in a system by assigning users to roles, and roles to permissions.</p><p>RBAC = Users → Roles → Permissions</p><p>Basic Example :</p><h4>Roles:</h4><ul><li><strong>Admin</strong> : can manage system (CRUD)</li><li><strong>Editor</strong> : can view create/edit content</li><li><strong>Viewer </strong>: can view content</li></ul><h4>User assignment:</h4><ul><li>Khoir as an admin</li><li>Beryl as an editor</li><li>Naskala an an viewer</li></ul><pre>How It Works (Conceptually), When a user tries to do something:<br><br>1. User logs in<br>2. System knows their role(s)<br>3. System checks if the role has permission<br>4. Allow or deny access</pre><p>Based on our scenario, in .NET we can set as below</p><pre>[Authorize(Roles = &quot;Admin,Editor,Viewer&quot;)]<br>// [Authorize] --&gt; Simply like this<br>public IActionResult Get()<br>{<br>    return View();<br>}<br><br>[Authorize(Roles = &quot;Admin,Editor&quot;)]<br>public IActionResult Insert()<br>{<br>    return View();<br>}<br><br>[Authorize(Roles = &quot;Admin,Editor&quot;)]<br>public IActionResult Update()<br>{<br>    return View();<br>}<br><br>[Authorize(Roles = &quot;Admin&quot;)]<br>public IActionResult Delete()<br>{<br>    return View();<br>}</pre><p>By implementing RBAC, it ease to understand, rapid development and built-in function if you are using .NET Framework.</p><p>But, the biggest real-world problems with RBAC is <strong>role explosion. What it is?</strong></p><p>Role explosion happens when the number of roles grows uncontrollably because we keep creating new roles to represent slight variations in permissions.</p><p>Instead of a few clean roles like: Admin, Editor, Editor. We end up with dozens (or hundreds) like : AdminButNoDelete, UserPremiumWithDownload, UserPremiumWithoutDownload. If we wan’t to remove or add 1 permission we have to create new roles, excample user premium with download and upload, it might add UserPremiumWithDownloadAndUpload.</p><p>If users and roles keep growing, it causes</p><ol><li>Hard to maintain : No one remembers what each role does anymore.</li><li>Hard to assign users : Should this person be EditorLimitedRegionA or EditorRegionAWithoutPublish?</li><li>Bug-prone / Security Risk : Set wrong role (unauthorized user can still access), Set missing role (authorized user blocked from features)</li></ol><p><strong>When Roles Still Make Sense?</strong> We have clear group / role (Admin, Editor, Viewer) and most likely doesn’t grow (rarely change)</p><h3>Policy-Based Authorization</h3><p>In RBAC, If user is Editor then allow access this resource. That’s simple but limited.</p><pre>[Authorize(Roles = &quot;Editor&quot;)]</pre><p>We assign permissions (e.g., news.create, news.read) to users. These permission are mapped to specific resource. We assign permissions (claims) to users, and policies evaluate those permissions, and access is granted if the user has the required permission for a resource.</p><p>Example</p><h4>Create Policy</h4><p>This is the basic way to implement policy based authorization. But later in our code we will create the more dynamic.</p><pre>builder.Services.AddAuthorization(options =&gt;<br>{<br>    options.AddPolicy(&quot;NewsCreate&quot;, policy =&gt;<br>        policy.RequireClaim(&quot;permission&quot;, &quot;news.create&quot;));<br><br>    options.AddPolicy(&quot;NewsRead&quot;, policy =&gt;<br>        policy.RequireClaim(&quot;permission&quot;, &quot;news.read&quot;));<br><br>    options.AddPolicy(&quot;NewsUpdate&quot;, policy =&gt;<br>        policy.RequireClaim(&quot;permission&quot;, &quot;news.update&quot;));<br><br>    options.AddPolicy(&quot;NewsDelete&quot;, policy =&gt;<br>        policy.RequireClaim(&quot;permission&quot;, &quot;news.delete&quot;));<br>});</pre><h4>Apply Policy in Resource</h4><pre>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class NewsController : ControllerBase<br>{<br>    [HttpPost]<br>    [Authorize(Policy = &quot;NewsCreate&quot;)]<br>    public IActionResult Create()<br>    {<br>        return Ok(&quot;News created&quot;);<br>    }<br><br>    [HttpGet]<br>    [Authorize(Policy = &quot;NewsRead&quot;)]<br>    public IActionResult GetAll()<br>    {<br>        return Ok(&quot;News list&quot;);<br>    }<br><br>    [HttpPut(&quot;{id}&quot;)]<br>    [Authorize(Policy = &quot;NewsUpdate&quot;)]<br>    public IActionResult Update(int id)<br>    {<br>        return Ok($&quot;News {id} updated&quot;);<br>    }<br><br>    [HttpDelete(&quot;{id}&quot;)]<br>    [Authorize(Policy = &quot;NewsDelete&quot;)]<br>    public IActionResult Delete(int id)<br>    {<br>        return Ok($&quot;News {id} deleted&quot;);<br>    }<br>}</pre><h4>Assign policy/rules to user when logged-in</h4><pre>User A = &quot;news.create&quot;, &quot;news.read&quot;, &quot;news.update&quot;, &quot;news.delete&quot;.<br><br>var claims = new List&lt;Claim&gt;<br>    {<br>        new Claim(ClaimTypes.Name, username),<br>        new Claim(ClaimTypes.Role, role)<br>    };<br><br>claims.AddRange(permissions.Select(p =&gt; new Claim(&quot;permission&quot;, p)));</pre><p>Since user A has several permission, so they allowed to access permission resource.</p><p>System that implementing policy-based authorization more scalable and flexible where it grows, either features or users. See the diagram below</p><pre>User A → news.read, news.create  <br>User B → news.read only  <br>User C → news.read + news.delete <br>User D, E, F, G.................</pre><p>Beside benefits we get, there are downside after implementing this approach.</p><ol><li>Harder to manage manually : Since every user might have different permission. It means hard to set and visualize permission.</li><li>Needs good UI / DB design : It likes need permission tables and admin UI to assign permissions</li></ol><p>When This Approach Is Best for</p><ol><li>Fine-grained control and permissions vary per user</li><li>System is dynamic (not fixed roles)</li></ol><h3>Hybrid Solution</h3><p>In modern system we keep need roles. However, due to system be more dynamic we required to have rules/permission. Then we can map between Role and Permission as default</p><h4>Permission</h4><pre>&quot;post.create&quot;,&quot;post.read&quot;,&quot;post.update&quot;,&quot;post.delete&quot;,&quot;post.detail&quot;,<br>&quot;user.create&quot;,&quot;user.read&quot;,&quot;user.update&quot;,&quot;user.delete&quot;,&quot;user.detail&quot;,<br>&quot;news.create&quot;,&quot;news.read&quot;,&quot;news.update&quot;,&quot;news.delete&quot;,&quot;news.detail&quot;,<br>&quot;article.create&quot;,&quot;article.read&quot;,&quot;article.update&quot;,&quot;article.delete&quot;,&quot;article.detail&quot;</pre><h4>Role</h4><pre>Admin, Editor, Viewer</pre><h4>Map between Role &amp; Permission</h4><pre>&quot;Admin&quot; =&gt; new[]<br>{<br>    &quot;post.create&quot;,&quot;post.read&quot;,&quot;post.update&quot;,&quot;post.delete&quot;,&quot;post.detail&quot;,<br>    &quot;user.create&quot;,&quot;user.read&quot;,&quot;user.update&quot;,&quot;user.delete&quot;,&quot;user.detail&quot;,<br>    &quot;news.create&quot;,&quot;news.read&quot;,&quot;news.update&quot;,&quot;news.delete&quot;,&quot;news.detail&quot;,<br>    &quot;article.create&quot;,&quot;article.read&quot;,&quot;article.update&quot;,&quot;article.delete&quot;,&quot;article.detail&quot;<br>},<br>&quot;Viewer&quot; =&gt; new[]<br>{<br>    &quot;user.read&quot;,&quot;news.read&quot;,&quot;article.read&quot;<br>},<br>&quot;Editor&quot; =&gt; new[]<br>{<br>    &quot;user.read&quot;,&quot;user.detail&quot;,<br>    &quot;post.read&quot;,&quot;post.detail&quot;,<br>    &quot;news.create&quot;,&quot;news.read&quot;,&quot;news.update&quot;,&quot;news.detail&quot;,<br>    &quot;article.create&quot;,&quot;article.read&quot;,&quot;article.update&quot;,&quot;article.detail&quot;<br>},</pre><p>By implementing this approach, we can assign role to specific role. For instance</p><ul><li>User 1 (Admin) — So, user 1 will have these admin permission</li><li>User 2 (Editor) — So, user 2 will have these editor permission</li><li>User 3 (Viewer) — So, user 3 will have these viewer permission</li></ul><p>We can also set custom permission to specific user, or introduce new role with different permission mapping.</p><p>Policy-based authorization does not replace RBAC, it enhances it by allowing more flexible and fine-grained control.</p><h4>Advanced Upgrade (Optional but Powerful)</h4><ol><li>Move all configurations like user, role, permission, role-permission into database</li><li>Data Scope. It’s a boundary of data a user is allowed to access. Permission answer “this action is allowed to you”. But on which data record?</li></ol><pre>Manager 1 → only can read employee data from department 1<br>Manager 2 → only can read employee data from department 2</pre><pre>// 🔹 (Optional) Data Scope example<br>var scopes = role switch<br>{<br>    &quot;manager 1&quot; =&gt; new[] { &quot;Department 1&quot; },<br>    &quot;manager 2&quot; =&gt; new[] { &quot;Department 2&quot; },<br>    _ =&gt; Array.Empty&lt;string&gt;()<br>};<br><br>claims.AddRange(scopes.Select(s =&gt; new Claim(&quot;data_scope&quot;, s)));</pre><p>Later, when manager 1 opens the employee data table, we can filter to display employees in department 1.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92c8a266c3ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React — JWT Authentication & Refresh Token]]></title>
            <link>https://medium.com/@mk.muhammadkhoirudin/react-jwt-authentication-refresh-token-179df9f8d8b6?source=rss-ea3f3bfa423c------2</link>
            <guid isPermaLink="false">https://medium.com/p/179df9f8d8b6</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Muhammad Khoirudin]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 01:28:43 GMT</pubDate>
            <atom:updated>2026-04-06T01:28:43.017Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*2mI84aDvZ3hxxSO2AjNLCg.png" /></figure><p><strong>Pre-Requisite</strong> : For better understanding please read this article, <a href="https://medium.com/@mk.muhammadkhoirudin/jwt-and-refresh-token-management-a039ca3e04fd">https://medium.com/@mk.muhammadkhoirudin/jwt-and-refresh-token-management-a039ca3e04fd</a></p><p>GitHub Backend : <a href="https://github.com/khoirmuhammad/ReactApi/tree/react-auth">https://github.com/khoirmuhammad/ReactApi/tree/react-auth</a></p><p>GitHub Frontend : <a href="https://github.com/khoirmuhammad/website/tree/react-authentication">https://github.com/khoirmuhammad/website/tree/react-authentication</a></p><h3>Explanation</h3><p>In this react app, we have several conditions</p><ol><li>Before user authenticated, it will be redirected to login page</li><li>Once logged in sucessfully, client retrieve access token and expiration from backend service and will be stored on session storage</li><li>Once user authenticated, it doesn’t allowed to return back to login page</li><li>Access token will be expired at certain period (backend set to 10 minutes for instance). However we will set token refresh buffer in 10 seconds (It means 10 seconds before token really expired, it will all refresh token endpoint).</li><li>Despite system set refresh buffer, we still put fallback, in case token is expired before refresh buffer. If request return 401 — Unauthorized, it will invoke refresh token endpoint and then call previous API.</li></ol><h3>Let’s Code</h3><h4>File src/api/client.ts</h4><p>This code is about managing authentication tokens in react API call. Since, before hitting backend service, all API configuration from client should pass here.</p><p>This code solves</p><ul><li>Automatically attach access tokens to every API request (Authorization header).</li><li>Automatically refresh the token if it’s about to expire.</li><li>Queue multiple requests that happen while a token refresh is in progress. Without queue Request 1 (401) → Triger rfresh, Request 2,3 (401) also trigger refresh. So we have multiple refresh API at the same time. It causes race condition (which token will be used), server may be overload. With queue once request 1 trigger refresh, the next request will be queued and waiting until getting new token</li><li>Handle errors like 401 (unauthorized) cleanly.</li><li>Avoid infinite loops when refreshing tokens. It means, our app keeps trying to refresh the token foreve and never stops. It makes freeze our app and spam backend service with requests. How it happens?</li></ul><pre>API request → returns 401 (Unauthorized)<br>Interceptor → calls /refresh<br>/refresh ALSO returns 401 (refresh token expired)<br>Interceptor sees 401 again → tries /refresh again<br><br>Request → 401 → refresh<br>        → 401 → refresh<br>        → 401 → refresh<br>        → infinite loop</pre><p>Why does this happen? beacuse our logic says, if I see 401 try refreshing new token.</p><p>Benefits implementing this code</p><ul><li>Better <strong>user experience</strong>: users stay logged in without manual refresh or re login.</li><li><strong>Security</strong>: short-lived tokens reduce attack risk and refresh token doesn’t maintain by client app</li><li><strong>Cleaner API handling</strong>: centralizes token logic instead of repeating it everywhere.</li></ul><pre>// Both are initialized from sessionStorage, which persists tokens across page reloads.<br>let accessToken: string | null = sessionStorage.getItem(&quot;accessToken&quot;);<br>let expAccessToken: string | null = sessionStorage.getItem(&quot;expAccessToken&quot;);</pre><pre>// Token is not null -&gt; set token in memory<br>// Token is null -&gt; remove it<br>export const setAccessToken = (token: string | null) =&gt; {<br>  accessToken = token;<br>  if (token) sessionStorage.setItem(&quot;accessToken&quot;, token);<br>  else sessionStorage.removeItem(&quot;accessToken&quot;);<br>};</pre><pre>// Creating API layer, When auth succeeds or fails, let the app decide what to do.<br>let onAuthSuccess: (() =&gt; void) | null = null;<br>let onAuthFailure: (() =&gt; void) | null = null;<br><br>export const registerAuthHandlers = (<br>  success: () =&gt; void,<br>  failure: () =&gt; void,<br>) =&gt; {<br>  onAuthSuccess = success;<br>  onAuthFailure = failure;<br>};<br><br>//EXPLANATION<br><br>// variables will hold functions, initially they are null (no function yet)<br>let onAuthSuccess: (() =&gt; void) | null = null;<br><br>// It&#39;s a void function, no argument and return<br>() =&gt; void<br><br>// It can be used by other component/part<br>registerAuthHandlers<br><br>//FLOW<br><br>// In Auth Provider<br>registerAuthHandlers(<br>  () =&gt; setIsAuthenticated(true),<br>  () =&gt; setIsAuthenticated(false),<br>);<br><br>// If success set to true, else set to false<br><br>// If onAuthSuccess exists then execute it, set to TRUE<br>onAuthSuccess?.();<br><br>// If onAuthFailureexists then execute it, set to FALSE<br>onAuthFailure?.();</pre><pre>// apiClient → main Axios instance for API requests.<br>// withCredentials → sends cookies with requests.<br>const apiClient = axios.create({<br>  baseURL: import.meta.env.VITE_API_URL,<br>  timeout: 10000,<br>  withCredentials: true,<br>});<br><br>// Separate client for refresh requests.<br>// Avoids infinite loops if the refresh endpoint returns 401 and triggers interceptors again.<br>const refreshClient = axios.create({<br>  baseURL: import.meta.env.VITE_API_URL,<br>  withCredentials: true,<br>});<br><br>// withCredentials: true,<br>// Include cookies (and other credentials) when making this request<br>// Since /refresh endpoint should retrieve refreshToken from cookie</pre><pre>let isRefreshing = false;<br>let failedQueue: {<br>  resolve: (token: string) =&gt; void;<br>  reject: (err: unknown) =&gt; void;<br>}[] = [];<br><br>const processQueue = (error: unknown, token: string | null) =&gt; {<br>  failedQueue.forEach((p) =&gt; (token ? p.resolve(token) : p.reject(error)));<br>  failedQueue = [];<br>};<br><br>// EXPLANATION<br>// When multiple API requests happen while the token is expired<br>// We want only one refresh request, others should wait<br><br>// false : No refresh happening<br>// true : refresh is happening, other requests will wait<br>let isRefreshing = false;<br><br>// array list that stores waiting request<br>failedQueue<br><br>// pause request now, resume later when token ready<br>// If refresh is happenning then stop call /refresh API and store request in queue<br>return new Promise&lt;string&gt;((resolve, reject) =&gt; {<br>      failedQueue.push({ resolve, reject });<br>    });<br><br>// It releases all waiting requests<br>const processQueue<br><br>// If token ready, resolve/exec waiting request<br>// If token not available, stop and throw error<br>(token ? p.resolve(token) : p.reject(error))<br><br>// Clear queue, avoids memory leaks<br>failedQueue = [];<br><br>//FLOW<br>// Request A → starts refresh, isRefreshing = true<br>// Request B, C → pushed to queue --&gt; failedQueue = [B, C]<br>// call method processQueue(null, newToken);<br><br>// B.resolve(newToken) -&gt; If success<br>// C.resolve(newToken) -&gt; If success<br>// B.reject(newToken) -&gt; If fail<br>// C.reject(newToken) -&gt; If fail<br><br></pre><pre>// Refresh token 10 seconds before expiration to prevent using expired tokens.<br>const TOKEN_REFRESH_BUFFER = 10 * 1000; // 10 seconds</pre><pre>// pause request now, resume later when token ready<br>// If refresh is happenning then stop call /refresh API and store request in queue<br>async function refreshToken(): Promise&lt;string&gt; {<br>  if (isRefreshing) {<br>    return new Promise&lt;string&gt;((resolve, reject) =&gt; {<br>      failedQueue.push({ resolve, reject });<br>    });<br>  }</pre><pre>// Make a POST request to /refresh to get new token + expiration timestamp.  <br>isRefreshing = true;<br>  try {<br>    const res = await refreshClient.post(&quot;/refresh&quot;); // bare client<br>    const newToken = res.data.accessToken;<br>    const newExp = res.data.exp;<br><br>// Update tokens in memory and sessionStorage.<br>setAccessToken(newToken);<br>setExpAccessToken(newExp);</pre><pre>// Ensure Valid Token Before Request<br>// Checks if token is near expiration.<br>// If yes → refresh token preemptively.<br>async function ensureValidToken(): Promise&lt;void&gt; {<br>  if (!accessToken || !expAccessToken) return;<br><br>  const expiresAt = Number(expAccessToken) * 1000;<br>  const now = Date.now();<br><br>  if (now &gt; expiresAt - TOKEN_REFRESH_BUFFER) {<br>    await refreshToken();<br>  }<br>}</pre><pre>// Runs before every request.<br>// Ensures token is valid and attaches it in Authorization header.<br>// Catches any token refresh errors but still sends the request.<br>apiClient.interceptors.request.use(async (config) =&gt; {<br>  try {<br>    await ensureValidToken(); // preemptive refresh<br>    if (accessToken) config.headers.Authorization = `Bearer ${accessToken}`;<br>  } catch (err) {<br>    console.warn(&quot;[RequestInterceptor] Token refresh failed&quot;, err);<br>  }<br>  return config;<br>});</pre><pre>// Runs after every response.<br>// If request fails, error contains the response info.<br>apiClient.interceptors.response.use(<br>  (response) =&gt; response,<br>  async (error) =&gt; {<br>    const originalRequest = error.config;<br><br>// If there’s no response (network error), reject with normalized error.<br>if (!error.response) return Promise.reject(normalizeError(error));</pre><pre>// Skip /login and /refresh endpoints (don’t retry if error comes from 2 endpoint).    <br>if (error.response.status === 401 &amp;&amp; !originalRequest._retry) {<br>      if (<br>        originalRequest.url?.includes(&quot;/login&quot;) ||<br>        originalRequest.url?.includes(&quot;/refresh&quot;)<br>      ) {<br>        return Promise.reject(normalizeError(error));<br>      }<br><br>      originalRequest._retry = true;<br>      try {<br>        const newToken = await refreshToken();<br>        originalRequest.headers.Authorization = `Bearer ${newToken}`;<br>        return apiClient(originalRequest);<br>      } catch (refreshError) {<br>        return Promise.reject(normalizeError(refreshError));<br>      }<br>    }</pre><pre>import axios from &quot;axios&quot;;<br>import { normalizeError } from &quot;./errorHandler&quot;;<br>import { logError } from &quot;./logger&quot;;<br><br>// =========================<br>// TOKEN STORAGE<br>// =========================<br><br>let accessToken: string | null = sessionStorage.getItem(&quot;accessToken&quot;);<br>let expAccessToken: string | null = sessionStorage.getItem(&quot;expAccessToken&quot;);<br><br>export const setAccessToken = (token: string | null) =&gt; {<br>  accessToken = token;<br>  if (token) sessionStorage.setItem(&quot;accessToken&quot;, token);<br>  else sessionStorage.removeItem(&quot;accessToken&quot;);<br>};<br><br>export const setExpAccessToken = (exp: string | null) =&gt; {<br>  expAccessToken = exp;<br>  if (exp) sessionStorage.setItem(&quot;expAccessToken&quot;, exp.toString());<br>  else sessionStorage.removeItem(&quot;expAccessToken&quot;);<br>};<br><br>// =========================<br>// AUTH HANDLERS<br>// =========================<br><br>let onAuthSuccess: (() =&gt; void) | null = null;<br>let onAuthFailure: (() =&gt; void) | null = null;<br><br>export const registerAuthHandlers = (<br>  success: () =&gt; void,<br>  failure: () =&gt; void,<br>) =&gt; {<br>  onAuthSuccess = success;<br>  onAuthFailure = failure;<br>};<br><br>// =========================<br>// AXIOS INSTANCE<br>// =========================<br><br>const apiClient = axios.create({<br>  baseURL: import.meta.env.VITE_API_URL,<br>  timeout: 10000,<br>  withCredentials: true,<br>});<br><br>// Bare client for refresh (avoids interceptor recursion)<br>const refreshClient = axios.create({<br>  baseURL: import.meta.env.VITE_API_URL,<br>  withCredentials: true,<br>});<br><br>// =========================<br>// REFRESH STATE<br>// =========================<br><br>let isRefreshing = false;<br>let failedQueue: {<br>  resolve: (token: string) =&gt; void;<br>  reject: (err: unknown) =&gt; void;<br>}[] = [];<br><br>const processQueue = (error: unknown, token: string | null) =&gt; {<br>  failedQueue.forEach((p) =&gt; (token ? p.resolve(token) : p.reject(error)));<br>  failedQueue = [];<br>};<br><br>// =========================<br>// TOKEN REFRESH HELPER<br>// =========================<br><br>const TOKEN_REFRESH_BUFFER = 10 * 1000; // 10 seconds<br><br>async function refreshToken(): Promise&lt;string&gt; {<br>  if (isRefreshing) {<br>    return new Promise&lt;string&gt;((resolve, reject) =&gt; {<br>      failedQueue.push({ resolve, reject });<br>    });<br>  }<br><br>  isRefreshing = true;<br>  try {<br>    const res = await refreshClient.post(&quot;/refresh&quot;); // bare client<br>    const newToken = res.data.accessToken;<br>    const newExp = res.data.exp;<br><br>    setAccessToken(newToken);<br>    setExpAccessToken(newExp);<br><br>    processQueue(null, newToken);<br>    onAuthSuccess?.();<br><br>    return newToken;<br>  } catch (err) {<br>    processQueue(err, null);<br>    setAccessToken(null);<br>    setExpAccessToken(null);<br>    onAuthFailure?.();<br>    throw err;<br>  } finally {<br>    isRefreshing = false;<br>  }<br>}<br><br>// =========================<br>// TOKEN VALIDATION BEFORE REQUEST<br>// =========================<br><br>async function ensureValidToken(): Promise&lt;void&gt; {<br>  if (!accessToken || !expAccessToken) return;<br><br>  const expiresAt = Number(expAccessToken) * 1000;<br>  const now = Date.now();<br><br>  if (now &gt; expiresAt - TOKEN_REFRESH_BUFFER) {<br>    await refreshToken();<br>  }<br>}<br><br>// =========================<br>// REQUEST INTERCEPTOR<br>// =========================<br><br>apiClient.interceptors.request.use(async (config) =&gt; {<br>  try {<br>    await ensureValidToken(); // preemptive refresh<br>    if (accessToken) config.headers.Authorization = `Bearer ${accessToken}`;<br>  } catch (err) {<br>    console.warn(&quot;[RequestInterceptor] Token refresh failed&quot;, err);<br>  }<br>  return config;<br>});<br><br>// =========================<br>// RESPONSE INTERCEPTOR<br>// =========================<br><br>apiClient.interceptors.response.use(<br>  (response) =&gt; response,<br>  async (error) =&gt; {<br>    const originalRequest = error.config;<br><br>    if (!error.response) return Promise.reject(normalizeError(error));<br><br>    // Handle 401<br>    if (error.response.status === 401 &amp;&amp; !originalRequest._retry) {<br>      // Skip login/refresh endpoints<br>      if (<br>        originalRequest.url?.includes(&quot;/login&quot;) ||<br>        originalRequest.url?.includes(&quot;/refresh&quot;)<br>      ) {<br>        return Promise.reject(normalizeError(error));<br>      }<br><br>      originalRequest._retry = true;<br><br>      try {<br>        const newToken = await refreshToken();<br>        originalRequest.headers.Authorization = `Bearer ${newToken}`;<br>        return apiClient(originalRequest);<br>      } catch (refreshError) {<br>        return Promise.reject(normalizeError(refreshError));<br>      }<br>    }<br><br>    const normalized = normalizeError(error);<br>    logError(normalized);<br>    return Promise.reject(normalized);<br>  },<br>);<br><br>export default apiClient;</pre><h4>File src/provider/AuthProvider.tsx</h4><ol><li>What it is? This is auth context provider. In simple terms, it stores and share authentication state (isAuthenticated, isLoading) across entire application.</li><li>Why do we need this? In react app, many components need to know “is user has logged in?”</li><li>Benefits? Global auth state, centralized login logout logic</li></ol><pre>type AuthContextType = {<br>  isAuthenticated: boolean; // logged in or not<br>  isLoading: boolean; // still checking auth<br>  login: (username: string, password: string) =&gt; Promise&lt;void&gt;;<br>  logout: () =&gt; Promise&lt;void&gt;; // function to log out<br>};</pre><pre>// createContext → creates global state<br>// useState → manage local state<br>import { createContext, useEffect, useState } from &quot;react&quot;;</pre><pre>// create global container. Initially null, later will be filled<br>export const AuthContext = createContext&lt;AuthContextType | null&gt;(null);</pre><pre>// isAuthenticated → user login state<br>// isLoading → prevents UI from rendering too early<br>const [isAuthenticated, setIsAuthenticated] = useState(false);<br>const [isLoading, setIsLoading] = useState(true);</pre><pre>// run once when app start / reloaded<br>useEffect(() =&gt; {<br><br>// If refresh succeeds → setIsAuthenticated(true)<br>// If refresh fails → setIsAuthenticated(false)<br>registerAuthHandlers(<br>  () =&gt; setIsAuthenticated(true),<br>  () =&gt; setIsAuthenticated(false),<br>);</pre><pre>// this will check, Is the user already logged in?<br>const initAuth = async () =&gt; {<br><br>// It just make sure our API calls successfully or not, You can use other secure endpoint<br>await apiClient.get(&quot;/me&quot;);</pre><pre>import { createContext, useEffect, useState } from &quot;react&quot;;<br>import apiClient, {<br>  setAccessToken,<br>  setExpAccessToken,<br>  registerAuthHandlers,<br>} from &quot;../api/client&quot;;<br><br>type AuthContextType = {<br>  isAuthenticated: boolean;<br>  isLoading: boolean;<br>  login: (username: string, password: string) =&gt; Promise&lt;void&gt;;<br>  logout: () =&gt; Promise&lt;void&gt;;<br>};<br><br>// eslint-disable-next-line react-refresh/only-export-components<br>export const AuthContext = createContext&lt;AuthContextType | null&gt;(null);<br><br>// eslint-disable-next-line @typescript-eslint/no-explicit-any<br>export const AuthProvider = ({ children }: any) =&gt; {<br>  const [isAuthenticated, setIsAuthenticated] = useState(false);<br>  const [isLoading, setIsLoading] = useState(true);<br><br>  useEffect(() =&gt; {<br>    registerAuthHandlers(<br>      () =&gt; setIsAuthenticated(true),<br>      () =&gt; setIsAuthenticated(false),<br>    );<br><br>    const initAuth = async () =&gt; {<br>      try {<br>        await apiClient.get(&quot;/me&quot;);<br><br>        setIsAuthenticated(true);<br>        // eslint-disable-next-line @typescript-eslint/no-explicit-any<br>      } catch (error: any) {<br>        // FULL DEBUG INFO<br>        if (error.response) {<br>          console.log(&quot;Status:&quot;, error.response.status);<br>          console.log(&quot;Data:&quot;, error.response.data);<br>        }<br><br>        if (error.request) {<br>          console.log(&quot;No response received:&quot;, error.request);<br>        }<br><br>        console.log(&quot;Message:&quot;, error.message);<br><br>        setIsAuthenticated(false);<br>      } finally {<br>        setIsLoading(false);<br>      }<br>    };<br><br>    initAuth();<br>  }, []);<br><br>  const login = async (username: string, password: string) =&gt; {<br>    const res = await apiClient.post(&quot;/login&quot;, { username, password });<br><br>    setAccessToken(res.data.accessToken);<br>    setExpAccessToken(res.data.exp);<br>    setIsAuthenticated(true);<br>  };<br><br>  const logout = async () =&gt; {<br>    await apiClient.post(&quot;/logout&quot;);<br>    setAccessToken(null);<br>    setExpAccessToken(null);<br>    setIsAuthenticated(false);<br>  };<br><br>  // CRITICAL FIX: block app until auth ready<br>  if (isLoading) {<br>    return (<br>      &lt;div className=&quot;flex items-center justify-center h-screen&quot;&gt;<br>        &lt;span&gt;Initializing authentication...&lt;/span&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br><br>  return (<br>    &lt;AuthContext.Provider value={{ isAuthenticated, isLoading, login, logout }}&gt;<br>      {children}<br>    &lt;/AuthContext.Provider&gt;<br>  );<br>};</pre><h4>File src/hooks/auth/useAuth.ts</h4><p>If we don’t create useAuth hook, may be every component should do this one</p><pre>const context = useContext(AuthContext);<br><br>if (!context) {<br>  throw new Error(&quot;...&quot;);<br>}<br><br>const { isAuthenticated } = context;</pre><p>With custom hook (just use the functionality in each component)</p><pre>import { useAuth } from &quot;../../hooks/auth/useAuth&quot;;<br><br>const { isAuthenticated , login, logout } = useAuth();</pre><h4>File src/router/ — PublicRoute.tsx &amp; ProtectedRoute.tsx</h4><ol><li>Public Route : For pages like login. It blocks access to page if user aready logged in</li><li>Protected Route : It blocks access to certain pages if user not logged in yet</li></ol><p>Why do we need them?</p><ul><li>Loggen-in users should not access login page, logged-out users should not access protected pages.</li><li>Without his, user could access protected data and page without login.</li></ul><p>Benefits</p><ul><li>Centralized route protection</li><li>Better user experience. If user already logged-in unable to see login page, otherwise unable to access protected page</li></ul><pre>type PublicRouteProps = {<br>  children: React.ReactNode;<br>};<br><br>// This component wraps another component<br>export default function PublicRoute({ children }: PublicRouteProps) {<br>  const auth = useContext(AuthContext);<br><br>  // If authenticated, redirect to home page<br>  if (auth?.isAuthenticated) {<br>    // login is replaced, if user clicks Back button, does NOT go back to /login<br>    return &lt;Navigate to=&quot;/&quot; replace /&gt;;<br>  }<br><br>  // Otherwise, show the children (e.g., login page)<br>  return children;<br>}<br><br>//------------------------------------------------------------------------<br><br>type ProtectedRouteProps = {<br>  children: React.ReactNode;<br>};<br><br>// This component wraps another component<br>export default function ProtectedRoute({ children }: ProtectedRouteProps) {<br>  const { isAuthenticated, isLoading } = useAuth();<br>  const location = useLocation();<br><br>  // WAIT until auth check finished<br>  if (isLoading) {<br>    return (<br>      &lt;div className=&quot;flex items-center justify-center h-screen&quot;&gt;<br>        &lt;span&gt;Loading...&lt;/span&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br><br>  if (!isAuthenticated) {<br>    // Save current page in state<br>    // user redirected to previous url path that accessed before logged-in<br>    return &lt;Navigate to=&quot;/login&quot; replace state={{ from: location.pathname }} /&gt;;<br>  }<br><br>  return children;<br>}</pre><pre>export default function AppRouter() {<br>  return (<br>    &lt;Layout&gt;<br>      &lt;Routes&gt;<br>        &lt;Route<br>          path=&quot;/login&quot;<br>          element={<br>            &lt;PublicRoute&gt;<br>              &lt;LoginPage /&gt;<br>            &lt;/PublicRoute&gt;<br>          }<br>        /&gt;<br><br>        &lt;Route<br>          path=&quot;/&quot;<br>          element={<br>            &lt;ProtectedRoute&gt;<br>              &lt;PostsPage /&gt;<br>            &lt;/ProtectedRoute&gt;<br>          }<br>        /&gt;<br><br>        &lt;Route<br>          path=&quot;/create&quot;<br>          element={<br>            &lt;ProtectedRoute&gt;<br>              &lt;CreatePostPage /&gt;<br>            &lt;/ProtectedRoute&gt;<br>          }<br>        /&gt;<br><br>        &lt;Route<br>          path=&quot;/edit/:id&quot;<br>          element={<br>            &lt;ProtectedRoute&gt;<br>              &lt;EditPostPage /&gt;<br>            &lt;/ProtectedRoute&gt;<br>          }<br>        /&gt;<br><br>        &lt;Route<br>          path=&quot;/detail/:id&quot;<br>          element={<br>            &lt;ProtectedRoute&gt;<br>              &lt;DetailPostPage /&gt;<br>            &lt;/ProtectedRoute&gt;<br>          }<br>        /&gt;<br>      &lt;/Routes&gt;<br>    &lt;/Layout&gt;<br>  );<br>}</pre><h4>File App.tsx</h4><p>Wrapping our app with multiple providers. Each provider gives different functionality</p><ol><li>QueryProvider : API calls, caching, background re-fetch</li><li>AuthProvider : isAuthenticated, login, logout</li><li>BrowserRouter : Provides routing like URL handling, Navigation</li></ol><p>Why is AuthProvider here? Since, entire app needs access to authentication state.</p><p>Why QueryProvider at the top? because everyhting might need data fetching. For instance in AuthProvider we call “/me” endpoint. If AuthProvider put first, then AuthProvider can’t use React Query</p><p>Why AuthProvider before BrowserRouter? becuase routing depends on auth state. We can see at ProtectedRoute and PublicRoute.</p><p>Why BrowserRouter wraps AppRouter? because route, navigate only works inside BrowserRouter.</p><pre>function App() {<br>  return (<br>    &lt;QueryProvider&gt;<br>      &lt;AuthProvider&gt;<br>        &lt;BrowserRouter&gt;<br>          &lt;main&gt;<br>            &lt;AppRouter /&gt;<br>          &lt;/main&gt;<br>        &lt;/BrowserRouter&gt;<br>      &lt;/AuthProvider&gt;<br>    &lt;/QueryProvider&gt;<br>  );<br>}</pre><h3>Correlation Between ApiClient, AuthProvider &amp; UseAuth</h3><ol><li>API Client : Talks to backend (Axios, tokens, refresh logic)</li><li>Auth Provider : Store auth state in React</li><li>Use Auth : Let’s component use state easily</li></ol><pre>API Client  →  AuthProvider  →  useAuth  →  Components<br>   (backend)     (state)         (access)      (UI)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=179df9f8d8b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JWT and Refresh Token Management]]></title>
            <link>https://medium.com/@mk.muhammadkhoirudin/jwt-and-refresh-token-management-a039ca3e04fd?source=rss-ea3f3bfa423c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a039ca3e04fd</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[refresh-token]]></category>
            <category><![CDATA[jwt-authentication]]></category>
            <dc:creator><![CDATA[Muhammad Khoirudin]]></dc:creator>
            <pubDate>Sat, 04 Apr 2026 04:17:41 GMT</pubDate>
            <atom:updated>2026-04-04T04:17:41.704Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*omyvdkxb6GiEuCg2qAOkuA.png" /></figure><h3>Study Case</h3><p>I have learned about JWTs, including how to generate tokens, validate them, and use refresh tokens. We know that once a token is stolen, it cannot be revoked and can be used until it expires. One solution is to make the access token short-lived (around 10–15 minutes) and use a refresh token to obtain a new one.</p><p>From an engineering perspective, there are a few approaches:</p><ol><li><strong>Returning the token with a fixed expiration time</strong> (e.g., “expires at 10:15 PM”). <em>The problem with this is that users in different time zones may see inconsistent times, which can cause confusion.</em></li><li><strong>Returning the token with a duration</strong> (e.g., valid for 15 minutes). The issue here is that if the user switches browser tabs, timers like setTimeout may pause, making the refresh less reliable.</li><li><strong>Letting the token expire naturally</strong> and handling 401 Unauthorized responses. In this case, the client can automatically call the refresh token API and retry the request. However, this can clutter the console with 401 errors, which looks messy.</li></ol><h4>Problem in poin 1</h4><p>One of the huge problem is timezone confusion. Suppose our backend is in UTC and our client is in New York (UTC-4)</p><p>If backend return</p><pre>{<br>  &quot;accessToken&quot;: &quot;...&quot;,<br>  &quot;expiresAt&quot;: &quot;2026-04-04T22:15:00&quot;  // Assume : 10:15 PM UTC<br>}</pre><p>Issue :</p><ul><li>10:15 PM UTC = 6:15 PM in New York.</li><li>Client see 22:15, client tmay thinks it has 4 extra hours. Since it should be expired at 10:15 PM UTC or 6:15 PM New York, Not 10:15 OM New York.</li></ul><p>But if backend returns</p><pre>{<br>  &quot;accessToken&quot;: &quot;...&quot;,<br>  &quot;expiresAt&quot;: &quot;2026-04-04T22:15:00Z&quot;  // Z = UTC<br>}</pre><p>No confusion if frontend handles timezones properly or just uses duration</p><h4>Problem in Poin 2</h4><p>We need to know how timer works in frontend. Suppose our backend returns</p><pre>{<br>  &quot;accessToken&quot;: &quot;...&quot;,<br>  &quot;expiresIn&quot;: 900  // 15 minutes<br>}</pre><p>On the front end, we might do this, to refresh token</p><pre>setTimeout(() =&gt; {<br>  refreshToken();<br>}, 900 * 1000); // refresh after 15 minutes</pre><p>The problem : most modern browsers throttle background tabs to save CPU resources. Chrome, safari, firefox reduce timer precission when the tab is inactive (It means timer might be stopped when tab is inactive).</p><p>Example</p><ul><li>Token valid for 15 minutes</li><li>User switches tab after 5 minutes (Timer is paused untl they switch back)</li><li>User comes back, but token already expired (The user returns, but the token has already expired (while setTimeout is not considered executed because of the interval lag)</li></ul><h4>Problem in Poin 3</h4><p>Scenario : Access token is short-lived (15 min). AFter that, ser makes an API request. Since, token already expired then backend will return “UnAuthorized (401)”.</p><p>In ur client, we handle like this. If return “401”, client should refresh token and re try api call to previous resource.</p><pre>if (error.response.status === 401) {<br>    await refreshToken();     // Call refresh endpoint<br>    return retryOriginalRequest(error.config); // Retry API request<br>}</pre><p>It actually safe and common, but sometimes people complain “Console is messy” due to catch UnAuthorized error. For me it doesn’t matter, it’s a normal operation not a bug.</p><h3>My Solution</h3><p>We can use a hybrid approach</p><ol><li>Keep short-lived access token (arround 10 to 15 minutes). I’m not recommend you to store token in local storage, In memory is OK or in session storage.</li><li>Long-lived refresh token (arround 7 days). Once log in successfully store it securly to HTTP-only cookie</li><li>Refresh strategy : Refresh before expiration (if token expired in 10 minutes, then 10 seconds before we can call refresh token), but also we handle fallback on 401 (like condition in poin 3)</li></ol><h3>How token rotation actually works</h3><h4>1. User logs in</h4><ul><li>Generate access token (short-lived, sent to client, client store in memory or session storage)</li><li>Generate refresh token (long-lived, set to cookie directly, never sent to client). Don’t forget to store in DB/redis in hash shape (it can be validate later, when refresh token API is invoked)</li></ul><h4>2. Access token expires, client calls refresh endpoint</h4><ul><li>Client just need to call refresh endpoint. When it hits to refresh controller/method, it will obtain the refresh token from cookie.</li></ul><h4>3. Backend Flow</h4><ul><li>Retrieve refresh token from cookie</li><li>Hash refresh token and lookup to database/redis. If not found then rejected. If found but the refresh token has expired also rejected. If not expired then check is it revoked or not.</li></ul><pre>RefreshTokenRecord GenerateRefreshToken(string userId, string refreshToken)<br>{<br>    return new RefreshTokenRecord<br>    {<br>        Id = Guid.NewGuid().ToString(),<br>        UserId = userId,<br>        RefreshTokenHash = HashToken(refreshToken),<br>        ExpiresAt = DateTime.UtcNow.AddMinutes(5),<br>        Revoked = false,<br>        ReplacedByTokenId = null<br>    };<br>}</pre><ul><li>Then, generate Access Token, dont forget to set previous refresh token (revoked = true)</li></ul><h3>How to Remove Authentication</h3><p><strong>Backend side :</strong> We only need to create logout endpoint. It will revoke current refresh token and remove refresh toke from cookie.</p><pre>app.MapPost(&quot;/logout&quot;, (HttpRequest request, HttpResponse response) =&gt;<br>{<br>    var token = request.Cookies[&quot;refreshToken&quot;];<br>    if (!string.IsNullOrEmpty(token))<br>    {<br>        var tokens = ReadRefreshTokens();<br>        var record = tokens.FirstOrDefault(t =&gt; t.RefreshTokenHash == HashToken(token));<br>        if (record != null) record.Revoked = true;<br>        WriteRefreshTokens(tokens);<br>    }<br><br>    response.Cookies.Delete(&quot;refreshToken&quot;);<br>    return Results.Ok();<br>});</pre><p><strong>Frontend side : </strong>Remove access token from memory or session storage. Then, we can redirect to login page manually or set it auto if unauthorized then auto redirect.</p><pre>const logout = async () =&gt; {<br>    await apiClient.post(&quot;/logout&quot;);<br>    setAccessToken(null);<br>    setExpAccessToken(null);<br>    setIsAuthenticated(false);<br>  };</pre><h3>Refresh Token Data in Database/Redis</h3><p><strong>A. Active Session (fresh login) :</strong> It means : user just logged in, token still valid (expires_at and revoked is false)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OQVB6aj88ZmTWtdfApEJAQ.png" /><figcaption>Current Data</figcaption></figure><p>B. <strong>After Token Refresh (Rotation Happened)</strong> : It means old token is now invalid, the nreplaced by new token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mDQA_L9xOrySSCk9-G4u_Q.png" /><figcaption>Old Data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ein1IUlG0Fe7RGXCu2CqXA.png" /><figcaption>New Data</figcaption></figure><p>What if attack scenario happens? If attacker obtain access token in session 1. It will be safe since refresh token in session one has revoked despite has not expired yet.</p><p><strong>C. Logout Scenario :</strong> We able to see “replaced_by_token_id” is NULL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0XaBNKW0LFgPeSIishu2-Q.png" /></figure><p>Addition : If we allow multiple device, we can add device info (It means each device will have different session)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*47YbpHJEvMOv3vCEw1jccA.png" /></figure><h3>Why don’t we remove data physically?</h3><p>We have seen that in previous data, it just set revoked to true (use soft removal). The problem with hard delete is no multi device support and harder logout control.</p><p>Imagine :</p><ol><li>You log in on laptop (username / userid : admin) — Log refresh token into database</li><li>You log in on phone (username / userid : admin) — Invalidate refresh token created by laptop (create new one)</li><li>You log in on tablet (username / userid : admin) — Invalidate refresh token created by phone (create new one)</li></ol><p>It’s bad for user experience design.</p><p>Or, it be harder logout control</p><pre>DELETE FROM user_sessions WHERE user_id = &#39;user_123&#39;;</pre><p>It will logout all devices.</p><h3>What if data growth?</h3><p>Let’s simulate user behavior. In normal user :</p><ol><li>Active user in application : 30 minutes</li><li>Idel user : No refresh token re-generated</li><li>User logout : No refresh token re-generated</li></ol><p>Example</p><ol><li>09:00 : User log in -&gt; Session 1 created and stored in DB</li><li>09:15 : Refresh token -&gt; Session 2 created and stored in DB (Session 1 revoked)</li><li>09:30 : Refresh token -&gt; Session 3created and stored in DB (Session 2 revoked)</li></ol><p>Total data : 3 rows only</p><p>How about worst scenario? Example user very active it uses apps for 8 hours not stop. If every 15 minutes refreshed, then per hour will refresh 4 times. In a day it will create 32 rows data</p><pre>8 hours × 4 refresh/hour = 32 rows/day</pre><p>It still manageable.</p><p>How database handle messy data? We can use scheduller to clean up</p><pre>DELETE FROM user_sessions<br>WHERE expires_at &lt; NOW() - INTERVAL &#39;7 days&#39;;</pre><p>Keep only recent sessions. Or another mechanism or SQL logic you can put it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a039ca3e04fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React — Scalable API Integration]]></title>
            <link>https://medium.com/@mk.muhammadkhoirudin/react-scalable-api-integration-c1f1e7630406?source=rss-ea3f3bfa423c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1f1e7630406</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Muhammad Khoirudin]]></dc:creator>
            <pubDate>Thu, 02 Apr 2026 06:32:06 GMT</pubDate>
            <atom:updated>2026-04-02T06:32:06.365Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*rC6b8KeIeGdZOM8WZ3i28A.png" /></figure><p><strong><em>GitHub Repository :</em></strong> <a href="https://github.com/khoirmuhammad/website/tree/react-apicall">https://github.com/khoirmuhammad/website/tree/react-apicall</a></p><p>More code learners learn how to call API in react, but not how to do it safely, scalably and maintainably, That learning gap is where real-world problems happen.</p><p>Here are couple of vulnerabilities when integrating to API Services</p><h4>1. Treating API Calls as “Just fetch in useEffect”</h4><pre>useEffect(() =&gt; {<br>  fetch(&#39;/api/data&#39;).then(res =&gt; res.json()).then(setData);<br>}, []);</pre><p>Why it leads problem in the future? We see that :</p><ol><li>No error handling</li><li>No loading state</li><li>No retry logic</li><li>No cancelation (causing memory leaks)</li></ol><p>Actually, we can absolutely fetch inside useEffect. But you will face the next problem like code be harder to read, repetition every component, it may causing inconsistent behaviour between each component.</p><p><strong><em>Solution </em></strong>: Abstract API calls into service layer / separate file, so UI, logic and data fetching don’t mixed in single component.</p><h4>2. No Centralized API Layer</h4><p>The second mistake, Calling APIs directly inside multiple components. Why it’s not recommended? If we need update base URL or header request can be more difficult, Duplicate logic everywhere, when backend changes we will update multiple files.</p><p><strong><em>Solution </em></strong>: Create central API Client, then it will be called by service layer.</p><h4>3. Poor Error Handling Strategy</h4><pre>catch(err =&gt; console.log(err))</pre><p>We have caught the error in console log, but it’s still bad because users see nothing (readable error message), no logging and retry mechanism. If it happens in production, we lose visibility into failures.</p><p><strong><em>Solution </em></strong>: Implement Error Hanlding with defining error categories like network | server | validation | client errors. Don’t forget to show meaningful error message to UI and integrate to log.</p><h4>4. Ignoring Loading &amp; Race Conditions</h4><p>For example multiple API calls overwrite each other. It can be found where user type something in search box. If we implement onChange and every character changed system triggers to API (user types “a” call to API, continue types “ab” call to API), it causing api calls overwrite.</p><p><strong><em>Solution </em></strong>: We can implement debouncing mechanism.</p><h4>5. Tight Coupling to API Response Shape</h4><p>If UI depends on object of API response, then backend changes, causing frontend breaks every where.</p><p>Solution : Introduce data mapping layer. API Response — Client Object — UI (based on Client Object)</p><pre>const mapUser = (apiData) =&gt; ({<br>  name: apiData.user.profile.name,<br>});<br><br>// UI will show data from mapUser.name, not apiData.user.profile.name</pre><h4>6. No Optimistic UI Handling</h4><p>Problem will come when UI waits for API before updating. Example : user click save button, likes nothing happens immediately, wait for miliseconds/seconds, then I update (It feels slow and unresponsive).</p><p><strong><em>Solution</em></strong> : Implement optimistic UI (instead of waiting, we assume success and update the UI <em>immediately).</em></p><p>It makes a temporary lie, the new data updated to UI before server confirms it, right? We can save previous data state for rollback if server calls error.</p><pre>const handleAdd = async () =&gt; {<br>  const previousItems = items;<br><br>  setItems(prev =&gt; [...prev, newItem]); // optimistic update<br><br>  try {<br>    await fetch(&#39;/api/items&#39;, {<br>      method: &#39;POST&#39;,<br>      body: JSON.stringify(newItem),<br>    });<br>  } catch (err) {<br>    setItems(previousItems); // rollback<br>  }<br>};</pre><p>However use it for adding items, likes (in media social for instance), deleting item or simple update. Don’t use for payments or critical data.</p><h4>7. No Pagination / Infinite Scroll Strategy</h4><p>The next mistake is fetching data at once. It can make impact to UI like slow rendering and memory issue.</p><p><strong><em>Solution </em></strong>: Implement pagination, lazy load, infinite scroll, add load more button (to load more data)</p><h3>Architectural Example</h3><pre>UI Components<br>     ↓<br>Custom Hooks (useUsers)<br>     ↓<br>Service Layer (api/users.js)<br>     ↓<br>API Client (axios instance)<br>     ↓<br>Backend Service</pre><ol><li><strong>UI Components </strong>: “How things look and interact”. It uses for rendering UI and handling user interactions. It doesn’t need to know API URLs, handle fetch logic.</li><li><strong>Custom Hooks</strong> : “How data flows into UI”. It uses for managing state (like is loading? is error? data itself). It doesn’t need to know HTTP details</li><li><strong>Service Layer</strong> : “What data we need”. It will define API endpoints also shape the request and response data. It doesn’t need to manage UI state or even care about react.</li><li><strong>API Client (Axios instance)</strong> : “How we talk to the server”. We can put base URL, headers (for token as instance), interceptors (log, error handle)</li><li><strong>Backend Service</strong> : “Source of truth”. Data it self.</li></ol><h3>Project Structure Example</h3><p><em>Disclaimer : this is not the best structure. But it can create a picture how arrange structure project in react.</em></p><ol><li>We can create services folder and move “posts.api.ts” from api folder to the folder</li><li>We can create pages folder and move posts folder inside components. Since, something within component are “reusable component”.</li></ol><pre>src/<br>│<br>├── api/<br>│   ├── client.ts             # API client - axios instance + interceptors<br>│   ├── errorHandler.ts       # error normalization<br>│   ├── logger.ts             # logging abstraction<br>│   └── posts.api.ts          # post entity (centralized). If we have another entity (user) just add users.api.tsx<br>│<br>├── hooks/<br>│   └── posts/                  # represent entity<br>│       ├── usePostQueries.ts   # infinite query / query data<br>│       └── usePostMutations.ts # create/update/delete<br>│<br>├── components/<br>│   ├── common/<br>│   │   ├── Spinner.tsx<br>│   │   ├── ErrorState.tsx<br>│   │   └── EmptyState.tsx<br>│   │<br>│   └── posts/<br>│       ├── CreatePostPage.tsx<br>│       ├── EditPostPage.tsx<br>│       └── PostPage.tsx<br>│<br>├── providers/<br>│   └── QueryProvider.tsx<br>│<br>├── utils/<br>│   ├── debounce.ts<br>│   └── mapper.tsx            # loose coupling, map API response to client object before consumed by UI<br>│<br>├── types/<br>│   ├── api.types.ts     # common typefor api client<br>│   └── post.types.ts    # represent each entity<br>|<br>├── router/<br>│   ├── AppRouter.tsx     # application navigation<br>|<br>└── App.tsx</pre><h4>File types/api.types.ts</h4><p>This is a central contract that defines how your frontend communicates with the backend and also make standardization.</p><pre>export type ApiErrorType =<br>  | &quot;NETWORK&quot; // Network can be treated as server error, but we may need different behavior between internet lose and server unavailable<br>  | &quot;SERVER&quot; // backend failure<br>  | &quot;CLIENT&quot; // bad request<br>  | &quot;VALIDATION&quot; // User Input // Client error for global error from client, but validation for field-level errors<br>  | &quot;UNKNOWN&quot;; // unexpected // Real errors are messy, i.e. Unexpected throw | Third-party library error | Backend sends garbage (null value)<br><br>export interface ApiError {<br>  type: ApiErrorType; // It can be used for behavior decisions. If network error then retry, if validation error then show validation<br>  message: string; // Human-readable error message. Use directly in UI<br>  statusCode?: number;<br>  details?: unknown; // Extra data from backend or mostly for validation errors<br>  originalError?: unknown; // The RAW error for logging, debugging<br>}</pre><h4>File types/post.types.ts</h4><p>Architectural</p><ol><li>Create a file per entity i.e. post, this is scalable if new entitiy comes, just add new type</li><li>It prevents tight coupling to API response</li></ol><p>Later, we need to create mapper. So, API response model can be mapped to UI model</p><pre>// RAW/ORIGINAL API RESPONSE for Create/Update (see on post.api.ts)<br>export interface PostApiResponse {<br>  userId: number;<br>  id: number;<br>  title: string;<br>  body: string;<br>}<br><br>// RAW/ORIGINAL API RESPONSE for data retrieval (see on post.api.ts)<br>export interface PaginatedPostApiResponse {<br>  data: PostApiResponse[];<br>  total: number;<br>}<br><br>// UI MODEL (decoupled), UI depends on this<br>export interface Post {<br>  id: number;<br>  title: string;<br>  body: string;<br>}<br><br>// Frontend sends to backend<br>export interface CreatePostPayload {<br>  title: string;<br>  body: string;<br>  userId: number;<br>}</pre><h4>File utils/debounce.ts</h4><p>Without debounce :</p><p>Type “react”<br>→ r → API service call<br>→ re → API service call<br>→ rea → API service call<br>→ reac → API service call<br>→ react → API service call</p><p>It bad performance and might giving unexpected result.</p><p>By using debounce, e.g. 500ms (it means after user stop typing in 0.5 second then API call will do). It delays updating value until user stops changing it.</p><p><strong>clearTimeout</strong></p><ul><li>“r” → start timer</li><li>“re” → cancel previous, start new timer</li><li>“rea” → cancel previous, start new timer</li><li>“react” → cancel previous, start new timer (wait 500 ms) → update debounced = “react”</li></ul><pre>import { useEffect, useState } from &quot;react&quot;;<br><br>export const useDebounce = (value: string, delay = 500) =&gt; {<br>  // state : The delayed version of value<br>  const [debounced, setDebounced] = useState(value);<br><br>  useEffect(() =&gt; {<br>    const timer = setTimeout(() =&gt; {<br>      // Wait X ms, then update debounced value”<br>      setDebounced(value);<br>    }, delay);<br><br>    // If user types again or component re-renders, then cancel previous timer<br>    return () =&gt; clearTimeout(timer);<br>  }, [value, delay]);<br><br>  return debounced;<br>};</pre><h4>File utils/mapper.ts</h4><p>This is your mapping layer (a.k.a adapter / transformer). In order to <em>Convert </em><strong><em>API model → UI model. </em></strong>UI depends on our own stable model. Once frontend retrieve the data, it will be converted to UI model</p><pre>import type { PostApiResponse, Post } from &quot;../types/post.types&quot;;<br><br>export const mapPost = (apiPost: PostApiResponse): Post =&gt; ({<br>  id: apiPost.id,<br>  title: apiPost.title,<br>  body: apiPost.body,<br>});<br></pre><h4>File api/client.ts</h4><p>This file creates a centralized HTTP client for our entire app. It acts as a gateway between our frontend and backend, handling: Configuration (API URL, timeout), Authentication via interceptors, error handling and logging.</p><ol><li>Request Interceptors : Before API call, Modify request</li><li>Response Interceptors : After API call, Result/Error handle</li></ol><pre>// Library to make HTTP requests<br>import axios from &quot;axios&quot;;<br>// Converts raw Axios errors into your standardized ApiError<br>import { normalizeError } from &quot;./errorHandler&quot;;<br>// Sends errors to a logging system<br>import { logError } from &quot;./logger&quot;;<br><br>const apiClient = axios.create({<br>  baseURL: import.meta.env.VITE_API_URL,<br>  timeout: 10000, // Request will fail after 10 seconds. Prevent hanging request<br>});<br><br>// Request interceptor : Runs BEFORE hitting backend <br>// Without this we have to repeat everywhere<br>apiClient.interceptors.request.use((config) =&gt; {<br>  const token = localStorage.getItem(&quot;token&quot;);<br><br>  if (token) {<br>    config.headers.Authorization = `Bearer ${token}`;<br>  }<br><br>  return config;<br>});<br><br>// Response interceptor : Runs AFTER backend responds<br>apiClient.interceptors.response.use(<br>  (response) =&gt; response,<br>  (error) =&gt; {<br>    const normalized = normalizeError(error);<br><br>    logError(normalized);<br><br>    return Promise.reject(normalized);<br>  },<br>);<br><br>export default apiClient;</pre><h4>File api/logger.ts</h4><p>It provides a single place to handle all error logging.</p><pre>import type { ApiError } from &quot;../types/api.types&quot;;<br><br>export const logError = (error: ApiError): void =&gt; {<br>  console.error(&quot;[API ERROR]:&quot;, error); // Outputs error to browser console<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*21_QQI-DN-EhML-0ZYBJCw.png" /></figure><h4>File api/errorHandler.ts</h4><p>This function converts raw error into a predictable, typed object “ApiError”. Since error may come from axios, network and backend, they have variety of error. With this, error looks have the same pattern/format and make it easier for debugging.</p><p>Type of errors</p><ol><li><strong>NETWORK ERROR</strong> : no response means request never reached server. e.g. : Network Error, DNS issue, Timeout, CORS policy issue</li><li><strong>SERVER ERROR</strong> : Backend failed</li><li><strong>VALIDATION ERROR</strong></li><li><strong>CLIENT ERROR</strong></li><li><strong>UNKNOWN FALLBACK</strong> : It’s a fallback mechanism, if primary options never catch the error we still have backup/default handler.</li></ol><pre>import type { ApiError } from &quot;../types/api.types&quot;;<br><br>// unknown : safest input type, always ApiError shape<br>export const normalizeError = (error: unknown): ApiError =&gt; {<br>  // eslint-disable-next-line @typescript-eslint/no-explicit-any<br>  const err = error as any; // can&#39;t infer exactly/safely, safe use any<br><br>  // NETWORK ERROR : no response means request never reached server<br><br>  if (!err?.response) {<br>    return {<br>      type: &quot;NETWORK&quot;,<br>      message: &quot;Network error. Check your connection.&quot;,<br>      originalError: err,<br>    };<br>  }<br><br>  const status = err.response.status;<br>  const data = err.response.data;<br><br>  // SERVER ERROR<br>  if (status &gt;= 500) {<br>    return {<br>      type: &quot;SERVER&quot;,<br>      message: &quot;Server error. Try again later.&quot;,<br>      statusCode: status,<br>      originalError: err,<br>    };<br>  }<br><br>  // VALIDATION ERROR<br>  if (status === 422) {<br>    return {<br>      type: &quot;VALIDATION&quot;,<br>      message: data?.message || &quot;Validation error&quot;,<br>      statusCode: status,<br>      details: data?.errors,<br>      originalError: err,<br>    };<br>  }<br><br>  // CLIENT ERROR<br>  if (status &gt;= 400) {<br>    return {<br>      type: &quot;CLIENT&quot;,<br>      message: data?.message || &quot;Invalid request.&quot;,<br>      statusCode: status,<br>      originalError: err,<br>    };<br>  }<br><br>  return {<br>    type: &quot;UNKNOWN&quot;,<br>    message: &quot;Something went wrong.&quot;,<br>    originalError: err,<br>  };<br>};</pre><h4>File api/posts.api.ts</h4><p>This is a service layer. Each entity should has this file and necessary endpoints.</p><pre>// Configured axios instance<br>import apiClient from &quot;./client&quot;;<br>import type {<br>  PostApiResponse, // raw backend response for create/update<br>  CreatePostPayload, // request body<br>  PaginatedPostApiResponse, // resonse for data retrieval<br>} from &quot;../types/post.types&quot;;<br><br>export const getPosts = async (<br>  page: number = 1, //current page<br>  limit: number = 10, // total items per page<br>  query: string = &quot;&quot;, // search keyword<br>): Promise&lt;PaginatedPostApiResponse&gt; =&gt; {<br>  // Converted to GET /posts?_page=1&amp;_limit=10&amp;_query=react<br>  const res = await apiClient.get(<br>    `/posts?_page=${page}&amp;_limit=${limit}&amp;_query=${query}`,<br>  );<br><br>  const responseData = res.data;<br>  return {<br>    data: responseData.data ?? responseData,<br>    total: responseData.total ?? 0, // fallback to 0<br>  };<br>};<br><br>export const getPostById = async (id: number): Promise&lt;PostApiResponse&gt; =&gt; {<br>  const res = await apiClient.get&lt;PostApiResponse&gt;(`/posts/${id}`);<br>  return res.data;<br>};<br><br>export const createPost = async (<br>  data: CreatePostPayload,<br>): Promise&lt;PostApiResponse&gt; =&gt; {<br>  const res = await apiClient.post&lt;PostApiResponse&gt;(&quot;/posts&quot;, data);<br>  return res.data;<br>};<br><br>export const updatePost = async (<br>  id: number,<br>  data: CreatePostPayload,<br>): Promise&lt;PostApiResponse&gt; =&gt; {<br>  const res = await apiClient.put&lt;PostApiResponse&gt;(`/posts/${id}`, data);<br>  return res.data;<br>};<br><br>export const deletePost = async (id: number): Promise&lt;void&gt; =&gt; {<br>  await apiClient.delete(`/posts/${id}`);<br>};</pre><h4>File hooks/post/usePostQuery.ts</h4><p>We are entering to hooks. At upfront, we have deal that Component should not know how to fetch data. By implementing this one, It easier to manage fetch, cache, pagination, and transfom entity(post) data</p><pre>// Special hook for infinite scrolling / pagination<br>import { useInfiniteQuery } from &quot;@tanstack/react-query&quot;;<br>// Calls service layer<br>import { getPosts } from &quot;../../api/post.api&quot;;<br>// Decouples/maps API response → UI model<br>import { mapPost } from &quot;../../utils/mapper&quot;;<br>// UI-friendly model<br>import type { Post } from &quot;../../types/post.types&quot;;<br><br>const LIMIT = 5; // Total items per page<br><br>// accept search keyword parameter<br>export const usePostQueries = (query: string) =&gt; {<br>  return useInfiniteQuery({<br>    // React Query stores API result in memory, keyed by queryKey<br>    // By this, react query auto check data in memory/cache first<br>    // If query value changed, then it go to new data<br>    queryKey: [&quot;posts&quot;, query],<br>    //REQUIRED in v5, Defines starting page, if we put 2, then data 6 to 10 will be retrieved<br>    initialPageParam: 1,<br>    // pageParam : Used for pagination<br>    // API call will be done here<br>    queryFn: ({ pageParam = 1 }) =&gt; getPosts(pageParam, LIMIT, query),<br>    // Do something if there another/next page<br>    getNextPageParam: (lastPage, pages) =&gt; {<br>      // Cunt total items loaded<br>      const totalLoaded = pages.flatMap((p) =&gt; p.data).length;<br><br>      // If all data loaded, stop fetching<br>      if (totalLoaded &gt;= lastPage.total) return undefined;<br><br>      //Load next page<br>      return pages.length + 1;<br>    },<br>    // transforms data BEFORE it reaches UI<br>    select: (data): { pages: Post[][]; pageParams: unknown[] } =&gt; ({<br>      pages: data.pages.map((page) =&gt; page.data.map(mapPost)), // Transform pages<br>      pageParams: data.pageParams, // Required for React Query internals<br>    }),<br>  });<br>};<br><br>// Get By Id<br>export const usePostDetail = (id: number) =&gt; {<br>  return useQuery({<br>    queryKey: [&quot;post&quot;, id],<br>    queryFn: () =&gt; getPostById(id),<br>    select: (data): Post =&gt; mapPost(data),<br>    enabled: !!id, // prevent call api if id undefined<br>  });<br>};</pre><p>“usePostQueries” will be invoked when component that call this query hooks render/re-render.</p><pre>export const usePostQueries = (query: string) =&gt; {<br>  console.log(&quot;test test test test&quot;);<br>  return useInfiniteQuery({</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*kh2dsl9b9a-zuPS8s5AxfQ.png" /></figure><p>However, no API call until user change search key or reload page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*W9Hx3RmKIAlOQK4QHQubsA.png" /></figure><p>Since we use React Query, every time user switches browser tab, and then back to react apps, it will call the API again (it’s expected behavior). The Real Reason is refetch based on Window Focus (React Query automatically refetches data)</p><pre>refetchOnWindowFocus: true</pre><p>Because your data might be <strong>stale</strong>. For instance, if user leave react page for 2 minutes, it might new data are inserted. When React Query refetches, UI stays fresh.</p><p>We can handle by set it false</p><pre>refetchOnWindowFocus: false</pre><p>or the another approach by adding several stale time</p><pre>staleTime: 1000 * 60, // 1 minute</pre><h4>File hooks/post/usePostMutation.ts</h4><p>Mutation will handle create update and delete operations. Mental model (since we are using optimistic approach). We will to make better user experience without wiating response from API services.</p><pre>1. Stop queries<br>2. Save old data (backup) : prevent if error happen then rollback<br>3. Update UI instantly (fake data, copy from new data)<br>4. If error → rollback<br>5. If success → sync with server</pre><ol><li><strong>Why do we need stop queries?</strong> React Query is fetching posts (refetch in background)</li></ol><p>When user click “Save”</p><pre>-- onMutate runs : Then optimistic update<br><br>New Post (fake)<br>Post A<br>Post B<br><br>-- BUT... background fetch old data (due to not stopping query)<br>-- So it prevent re-write anything that patched by optimistic process</pre><p>In which scenaio it will be happened?</p><ul><li>Window refocus : Switch back to react web apps will run query</li><li>Infinite scroll : By clicking load data more</li></ul><pre>// useMutation → used for POST, PUT, DELETE<br>// useQueryClient → gives access to React Query cache / control cache globally<br>// useQuery → get data<br>/* eslint-disable @typescript-eslint/no-explicit-any */<br>import { useMutation, useQueryClient } from &quot;@tanstack/react-query&quot;;<br>// These are your service layer functions<br>import { createPost, deletePost, updatePost } from &quot;../../api/post.api&quot;;<br>// Import types for safety<br>import type {<br>  CreatePostPayload,<br>  PostApiResponse,<br>} from &quot;../../types/post.types&quot;;<br><br>export const useCreatePost = () =&gt; {<br>  // Access global cache, i.e. read/update/invalidate cache<br>  const queryClient = useQueryClient();<br><br>  // Create mutation object, it handles loading, error, success state<br>  return useMutation({<br>    // The actual API call<br>    mutationFn: createPost,<br><br>    // runs BEFORE your API request is sent : UI updates instantly no wait result from API<br>    onMutate: async (newPost: CreatePostPayload) =&gt; {<br>      // Pause fetching temporarily, if don&#39;t use, it might overwrite your UI update<br>      await queryClient.cancelQueries({ queryKey: [&quot;posts&quot;] });<br><br>      // Backup current cache, used for rollback if error happens<br>      const previous = queryClient.getQueryData&lt;any&gt;([&quot;posts&quot;]);<br><br>      // If there is NO existing cache, skip optimistic update”<br>      // Why return previous<br>      // onMutate() → returns context, context is passed into: onError and onSettle<br>      if (!previous) return { previous };<br><br>      // Update cache optimistically<br>      queryClient.setQueryData([&quot;posts&quot;], (old: any) =&gt; {<br>        // If data is not in expected format, do nothing safely<br>        // return old : it means don&#39;t modify the cache, return as it is<br>        if (!old || !old.pages) return old;<br><br>        // Create fake post, since backend has not response yet<br>        const optimistic = {<br>          id: Date.now(),<br>          title: newPost.title,<br>          body: newPost.body,<br>        };<br><br>        // Get single data, because infinite query is multiple pages<br>        const firstPage = old.pages[0];<br><br>        if (!firstPage) return old;<br><br>        // Add new post to top of list, eep other pages unchanged<br>        return {<br>          ...old, // copy everything from cache<br>          pages: [<br>            {<br>              ...firstPage, // copy first page<br>              data: [optimistic, ...(firstPage.data || [])],<br>            },<br>            ...old.pages.slice(1), // Keep the rest of pages unchanged<br>          ],<br>          pageParams: old.pageParams,<br>        };<br>      });<br><br>      return { previous };<br>    },<br><br>    // Runs if API fails<br>    onError: (_err, _newPost, context) =&gt; {<br>      if (context?.previous) {<br>        // Undo optimistic update, prevent UI inconsistency<br>        queryClient.setQueryData([&quot;posts&quot;], context.previous);<br>      }<br>    },<br><br>    // Runs after success OR error<br>    onSettled: () =&gt; {<br>      // Force refetch from server, keep UI update with backend, Replaces fake post with real one<br>      queryClient.invalidateQueries({ queryKey: [&quot;posts&quot;] });<br>    },<br>  });<br>};<br><br>export const useUpdatePost = () =&gt; {<br>  const queryClient = useQueryClient();<br><br>  return useMutation({<br>    mutationFn: ({ id, data }: { id: number; data: CreatePostPayload }) =&gt;<br>      updatePost(id, data),<br><br>    onMutate: async ({ id, data }) =&gt; {<br>      await queryClient.cancelQueries({ queryKey: [&quot;posts&quot;] });<br><br>      const previous = queryClient.getQueryData&lt;any&gt;([&quot;posts&quot;]);<br><br>      queryClient.setQueryData([&quot;posts&quot;], (old: any) =&gt; {<br>        if (!old?.pages) return old;<br><br>        // Create update object for optimistic version of updated post<br>        const updatedPost: PostApiResponse = {<br>          id,<br>          ...data,<br>        };<br><br>        // infinite query = multiple pages<br>        // ... (spread operator), Copy everything from this object before updating<br>        // old = ALL cached data for &quot;posts&quot;<br>        // page = ALL data list of post<br>        return {<br>          ...old,<br>          pages: old.pages.map((page: any) =&gt; ({<br>            // Loop posts inside each page:<br>            ...page,<br>            data: page.data.map((p: any) =&gt; (p.id === id ? updatedPost : p)), // Replace only the matching post:<br>          })),<br>        };<br>      });<br><br>      return { previous };<br>    },<br><br>    onError: (_err, _vars, context) =&gt; {<br>      if (context?.previous) {<br>        queryClient.setQueryData([&quot;posts&quot;], context.previous);<br>      }<br>    },<br><br>    onSettled: () =&gt; {<br>      queryClient.invalidateQueries({ queryKey: [&quot;posts&quot;] });<br>    },<br>  });<br>};<br><br>export const useDeletePost = () =&gt; {<br>  const queryClient = useQueryClient();<br><br>  return useMutation({<br>    mutationFn: deletePost,<br><br>    onMutate: async (id: number) =&gt; {<br>      await queryClient.cancelQueries({ queryKey: [&quot;posts&quot;] });<br><br>      const previous = queryClient.getQueryData&lt;any&gt;([&quot;posts&quot;]);<br><br>      queryClient.setQueryData([&quot;posts&quot;], (old: any) =&gt; {<br>        if (!old?.pages) return old;<br><br>        return {<br>          ...old,<br>          pages: old.pages.map((page: any) =&gt; ({<br>            ...page,<br>            data: page.data.filter((p: any) =&gt; p.id !== id), // this only removes (hides) the item from the UI (cache)<br>          })),<br>        };<br>      });<br><br>      return { previous };<br>    },<br><br>    onError: (_err, _id, context) =&gt; {<br>      if (context?.previous) {<br>        queryClient.setQueryData([&quot;posts&quot;], context.previous);<br>      }<br>    },<br><br>    onSettled: () =&gt; {<br>      queryClient.invalidateQueries({ queryKey: [&quot;posts&quot;] });<br>    },<br>  });<br>};</pre><h4>File prviders/QueryProvider.tsx</h4><p>Itgives React Query (cache + features) to your entire app. useQuery, useMutation will not work without it.</p><p>Think like this : React Query needs a <strong>central storage (cache)</strong>.</p><pre>// That storage<br>// The brain / manager of all server data<br>// It handles cache, fetching, mutation, sync data<br>const queryClient = new QueryClient(); </pre><pre>import { QueryClient, QueryClientProvider } from &quot;@tanstack/react-query&quot;;<br>import type { ReactNode } from &quot;react&quot;;<br><br>// Create ONE global instance<br>const queryClient = new QueryClient();<br><br>// This is a wrapper component<br>export const QueryProvider = ({ children }: { children: ReactNode }) =&gt; {<br>  return (<br>    &lt;QueryClientProvider client={queryClient}&gt;{children}&lt;/QueryClientProvider&gt;<br>  );<br>};</pre><h4>File router/AppRouter.tsx</h4><p>Register and map between route path and corresponding component</p><pre>export default function AppRouter() {<br>  return (<br>    &lt;BrowserRouter&gt;<br>      &lt;Routes&gt;<br>        &lt;Route path=&quot;/&quot; element={&lt;PostsPage /&gt;} /&gt;<br>        &lt;Route path=&quot;/create&quot; element={&lt;CreatePostPage /&gt;} /&gt;<br>        &lt;Route path=&quot;/edit/:id&quot; element={&lt;EditPostPage /&gt;} /&gt;<br>        &lt;Route path=&quot;/detail/:id&quot; element={&lt;DetailPostPage /&gt;} /&gt;<br>      &lt;/Routes&gt;<br>    &lt;/BrowserRouter&gt;<br>  );<br>}</pre><h4>File App.tsx</h4><pre>function App() {<br>  return (<br>    // Here is the QueryClient, All components can use it<br>    &lt;QueryProvider&gt;<br>      &lt;main style={{ maxWidth: &quot;600px&quot;, margin: &quot;0 auto&quot; }}&gt;<br>        &lt;AppRouter /&gt;<br>      &lt;/main&gt;<br>    &lt;/QueryProvider&gt;<br>  );<br>}</pre><h3>Pages</h3><h4>File PostPage.tsx</h4><p>This page will</p><ol><li>Shows list of posts</li><li>Supports search (with debounce)</li><li>Supports infinite loading (“Load more”)</li><li>Supports delete, edit and view details</li></ol><p>Search debounce flow</p><pre>User types → search state updates<br>        ↓<br>debouncedSearch (after delay)<br>        ↓<br>usePostQueries(debouncedSearch)<br>        ↓<br>React Query fetches data<br>        ↓<br>UI renders posts</pre><p>Infinite loading flow</p><pre>Click &quot;Load More&quot;<br>        ↓<br>fetchNextPage()<br>        ↓<br>React Query fetches next page<br>        ↓<br>data.pages grows<br>        ↓<br>UI shows more posts</pre><pre>export default function PostsPage() {<br>  const navigate = useNavigate();<br>  const { mutate: deletePost } = useDeletePost();<br><br>  // 🔍 Search state<br>  const [search, setSearch] = useState(&quot;&quot;); // Stores what user types<br>  const debouncedSearch = useDebounce(search, 500); // debouncedSearch changes AFTER 500ms<br><br>  // 📡 Query<br>  const {<br>    data, // all pages of posts<br>    isLoading, // load state<br>    isError, // error state<br>    error,<br>    fetchNextPage,<br>    hasNextPage,<br>    isFetching,<br>  } = usePostQueries(debouncedSearch); // API only triggered after user stops typing<br><br>  // 🔝 Scroll to top on new search<br>  // User scrolls down, then search. New results loaded but scroll stays at a bottom (by using this it will be prevented)<br>  useEffect(() =&gt; {<br>    window.scrollTo({ top: 0 });<br>  }, [debouncedSearch]);<br><br>  // shortens length text<br>  const truncate = (text?: string, max = 80) =&gt; {<br>    if (!text) return &quot;&quot;;<br>    return text.length &gt; max ? text.slice(0, max) + &quot;...&quot; : text;<br>  };<br>................................................................</pre><h4>File CreatePostPage.tsx</h4><p>Flow</p><pre>Input → state (title, body)<br>       ↓<br>Submit form<br>       ↓<br>mutate(payload)<br>       ↓<br>API call (createPost)<br>       ↓<br>Success → reset form + navigate(&quot;/&quot;)</pre><pre>export default function CreatePostPage() {<br>  const [title, setTitle] = useState(&quot;&quot;);<br>  const [body, setBody] = useState(&quot;&quot;);<br><br>  // mutate : function to trigger API<br>  const { mutate, isPending, isError, error } = useCreatePost();<br>  const navigate = useNavigate();<br><br>  const handleSubmit = (e: FormEvent) =&gt; {<br>    e.preventDefault();<br><br>    const payload: CreatePostPayload = {<br>      title,<br>      body,<br>      userId: 1,<br>    };<br><br>    mutate(payload, {<br>      onSuccess: () =&gt; {<br>        setTitle(&quot;&quot;); // reset form<br>        setBody(&quot;&quot;); // reset form<br>        navigate(&quot;/&quot;); // redirect after success<br>      },<br>    });<br>  };</pre><h4>File EditPostPage.tsx</h4><pre>Navigate to edit page (with post data)<br>        ↓<br>Fill form with existingPost<br>        ↓<br>User edits<br>        ↓<br>mutate({ id, data })<br>        ↓<br>API update<br>        ↓<br>navigate(&quot;/&quot;)</pre><p>In PostPage navigation</p><pre>// We pass data directly<br>navigate(&quot;/edit/123&quot;, { state: post });</pre><h3>Backend Service</h3><p>Program.cs</p><pre>using ReactApi.Models;<br>using System.Text.Json;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>// Add services to the container.<br>// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle<br>builder.Services.AddEndpointsApiExplorer();<br>builder.Services.AddSwaggerGen();<br><br>// Add CORS<br>builder.Services.AddCors(options =&gt;<br>{<br>    options.AddPolicy(&quot;AllowAll&quot;, policy =&gt;<br>    {<br>        policy<br>            .AllowAnyOrigin()<br>            .AllowAnyHeader()<br>            .AllowAnyMethod();<br>    });<br>});<br><br>var app = builder.Build();<br><br>app.UseCors(&quot;AllowAll&quot;);<br><br><br>string filePath = &quot;posts.json&quot;;<br><br>// Helper functions<br>List&lt;Post&gt; ReadData()<br>{<br>    if (!File.Exists(filePath))<br>        return new List&lt;Post&gt;();<br><br>    var json = File.ReadAllText(filePath);<br>    var options = new JsonSerializerOptions<br>    {<br>        PropertyNameCaseInsensitive = true<br>    };<br><br>    var data = JsonSerializer.Deserialize&lt;List&lt;Post&gt;&gt;(json, options) ?? new List&lt;Post&gt;();<br><br>    return data;<br>}<br><br>void WriteData(List&lt;Post&gt; posts)<br>{<br>    var json = JsonSerializer.Serialize(posts, new JsonSerializerOptions { WriteIndented = true });<br>    File.WriteAllText(filePath, json);<br>}<br><br>int GetNextId(List&lt;Post&gt; posts) =&gt; posts.Any() ? posts.Max(p =&gt; p.Id) + 1 : 1;<br><br><br><br>// (1) GET ALL + FILTER<br>app.MapGet(&quot;/posts&quot;, (int? _page, int? _limit, string? _query) =&gt;<br>{<br>    var data = ReadData();<br><br>    // FILTER<br>    if (!string.IsNullOrWhiteSpace(_query))<br>    {<br>        _query = _query.ToLower();<br>        data = data.Where(p =&gt;<br>            p.Title.ToLower().Contains(_query) ||<br>            p.Body.ToLower().Contains(_query) ||<br>            p.Id.ToString().Contains(_query) ||<br>            p.UserId.ToString().Contains(_query)<br>        ).ToList();<br>    }<br><br>    // TOTAL (before pagination)<br>    var total = data.Count;<br><br>    // PAGINATION<br>    int page = _page ?? 1;<br>    int limit = _limit ?? 10;<br><br>    var paged = data<br>        .Skip((page - 1) * limit)<br>        .Take(limit)<br>        .ToList();<br><br>    // RESPONSE WRAP<br>    return Results.Ok(new<br>    {<br>        data = paged,<br>        total = total<br>    });<br>});<br><br>// (2) GET BY ID<br>app.MapGet(&quot;/posts/{id:int}&quot;, (int id) =&gt;<br>{<br>    var posts = ReadData();<br>    var post = posts.FirstOrDefault(p =&gt; p.Id == id);<br><br>    return post is not null ? Results.Ok(post) : Results.NotFound();<br>});<br><br><br>// (3) CREATE<br>app.MapPost(&quot;/posts&quot;, (Post newPost) =&gt;<br>{<br>    var posts = ReadData();<br><br>    newPost.Id = GetNextId(posts);<br>    posts.Add(newPost);<br><br>    WriteData(posts);<br><br>    return Results.Created($&quot;/posts/{newPost.Id}&quot;, newPost);<br>});<br><br><br>// (4) PUT (FULL UPDATE)<br>app.MapPut(&quot;/posts/{id:int}&quot;, (int id, Post updatedPost) =&gt;<br>{<br>    var posts = ReadData();<br>    var existing = posts.FirstOrDefault(p =&gt; p.Id == id);<br><br>    if (existing is null) return Results.NotFound();<br><br>    existing.Title = updatedPost.Title;<br>    existing.Body = updatedPost.Body;<br>    existing.UserId = updatedPost.UserId;<br><br>    WriteData(posts);<br><br>    return Results.Ok(existing);<br>});<br><br><br>// (5) PATCH (PARTIAL UPDATE)<br>app.MapPatch(&quot;/posts/{id:int}&quot;, (int id, JsonElement patchData) =&gt;<br>{<br>    var posts = ReadData();<br>    var existing = posts.FirstOrDefault(p =&gt; p.Id == id);<br><br>    if (existing is null) return Results.NotFound();<br><br>    if (patchData.TryGetProperty(&quot;title&quot;, out var title))<br>        existing.Title = title.GetString() ?? existing.Title;<br><br>    if (patchData.TryGetProperty(&quot;body&quot;, out var body))<br>        existing.Body = body.GetString() ?? existing.Body;<br><br>    if (patchData.TryGetProperty(&quot;userId&quot;, out var userId))<br>        existing.UserId = userId.GetInt32();<br><br>    WriteData(posts);<br><br>    return Results.Ok(existing);<br>});<br><br><br>// (6) DELETE<br>app.MapDelete(&quot;/posts/{id:int}&quot;, (int id) =&gt;<br>{<br>    var posts = ReadData();<br>    var post = posts.FirstOrDefault(p =&gt; p.Id == id);<br><br>    if (post is null) return Results.NotFound();<br><br>    posts.Remove(post);<br>    WriteData(posts);<br><br>    return Results.NoContent();<br>});<br><br>// Configure the HTTP request pipeline.<br>if (app.Environment.IsDevelopment())<br>{<br>    app.UseSwagger();<br>    app.UseSwaggerUI();<br>}<br><br>app.UseHttpsRedirection();<br><br>app.Run();</pre><p>Post.cs class model</p><pre>public class Post<br>{<br>    public int Id { get; set; }<br>    public int UserId { get; set; }<br>    public string Title { get; set; } = &quot;&quot;;<br>    public string Body { get; set; } = &quot;&quot;;<br>}</pre><p>post.json data (since no database utilization)</p><pre>[<br>  {<br>    &quot;Id&quot;: 1,<br>    &quot;UserId&quot;: 1,<br>    &quot;Title&quot;: &quot;sunt aut facere repellat provident occaecati&quot;,<br>    &quot;Body&quot;: &quot;quia et suscipit...1&quot;<br>  },<br>  {<br>    &quot;Id&quot;: 2,<br>    &quot;UserId&quot;: 1,<br>    &quot;Title&quot;: &quot;qui est esse&quot;,<br>    &quot;Body&quot;: &quot;est rerum tempore vitae...&quot;<br>  },<br>  {<br>    &quot;Id&quot;: 3,<br>    &quot;UserId&quot;: 1,<br>    &quot;Title&quot;: &quot;ea molestias quasi exercitationem&quot;,<br>    &quot;Body&quot;: &quot;et iusto sed quo iure...&quot;<br>  },<br>  {<br>    &quot;Id&quot;: 4,<br>    &quot;UserId&quot;: 1,<br>    &quot;Title&quot;: &quot;eum et est occaecati&quot;,<br>    &quot;Body&quot;: &quot;ullam et saepe reiciendis...&quot;<br>  },<br>  {<br>    &quot;Id&quot;: 5,<br>    &quot;UserId&quot;: 1,<br>    &quot;Title&quot;: &quot;nesciunt quas odio&quot;,<br>    &quot;Body&quot;: &quot;repudiandae veniam quaerat...&quot;<br>  },<br>  {<br>    &quot;Id&quot;: 6,<br>    &quot;UserId&quot;: 2,<br>    &quot;Title&quot;: &quot;dolorem eum magni eos&quot;,<br>    &quot;Body&quot;: &quot;ut aspernatur corporis...&quot;<br>  },<br>  {<br>    &quot;Id&quot;: 7,<br>    &quot;UserId&quot;: 2,<br>    &quot;Title&quot;: &quot;magnam facilis autem&quot;,<br>    &quot;Body&quot;: &quot;dolore placeat quibusdam...&quot;<br>  },<br>  {<br>    &quot;Id&quot;: 8,<br>    &quot;UserId&quot;: 2,<br>    &quot;Title&quot;: &quot;dolorem dolore est ipsam&quot;,<br>    &quot;Body&quot;: &quot;dignissimos aperiam dolorem...&quot;<br>  },<br>  {<br>    &quot;Id&quot;: 9,<br>    &quot;UserId&quot;: 2,<br>    &quot;Title&quot;: &quot;nesciunt iure omnis&quot;,<br>    &quot;Body&quot;: &quot;consectetur animi nesciunt...&quot;<br>  },<br>  {<br>    &quot;Id&quot;: 10,<br>    &quot;UserId&quot;: 2,<br>    &quot;Title&quot;: &quot;optio molestias id&quot;,<br>    &quot;Body&quot;: &quot;quo et expedita modi...&quot;<br>  },<br>  {<br>    &quot;Id&quot;: 11,<br>    &quot;UserId&quot;: 3,<br>    &quot;Title&quot;: &quot;et ea vero quia&quot;,<br>    &quot;Body&quot;: &quot;pariatur quasi facilis...&quot;<br>  },<br>  {<br>    &quot;Id&quot;: 12,<br>    &quot;UserId&quot;: 3,<br>    &quot;Title&quot;: &quot;in quibusdam tempore&quot;,<br>    &quot;Body&quot;: &quot;et earum quidem...&quot;<br>  },<br>  {<br>    &quot;Id&quot;: 13,<br>    &quot;UserId&quot;: 3,<br>    &quot;Title&quot;: &quot;dolorum ut in voluptas&quot;,<br>    &quot;Body&quot;: &quot;similique nostrum...&quot;<br>  },<br>  {<br>    &quot;Id&quot;: 14,<br>    &quot;UserId&quot;: 3,<br>    &quot;Title&quot;: &quot;voluptatem eligendi optio&quot;,<br>    &quot;Body&quot;: &quot;fuga et accusamus...&quot;<br>  },<br>  {<br>    &quot;Id&quot;: 15,<br>    &quot;UserId&quot;: 3,<br>    &quot;Title&quot;: &quot;eveniet quod temporibus&quot;,<br>    &quot;Body&quot;: &quot;reprehenderit quos...&quot;<br>  },<br>  {<br>    &quot;Id&quot;: 16,<br>    &quot;UserId&quot;: 4,<br>    &quot;Title&quot;: &quot;sint suscipit perspiciatis&quot;,<br>    &quot;Body&quot;: &quot;voluptate et itaque...&quot;<br>  },<br>  {<br>    &quot;Id&quot;: 17,<br>    &quot;UserId&quot;: 4,<br>    &quot;Title&quot;: &quot;fugit voluptas sed&quot;,<br>    &quot;Body&quot;: &quot;eos voluptas et aut...&quot;<br>  },<br>  {<br>    &quot;Id&quot;: 18,<br>    &quot;UserId&quot;: 4,<br>    &quot;Title&quot;: &quot;voluptate et itaque&quot;,<br>    &quot;Body&quot;: &quot;non quo sed...&quot;<br>  },<br>  {<br>    &quot;Id&quot;: 19,<br>    &quot;UserId&quot;: 4,<br>    &quot;Title&quot;: &quot;adipisci placeat illum&quot;,<br>    &quot;Body&quot;: &quot;illum quis cupiditate...&quot;<br>  },<br>  {<br>    &quot;Id&quot;: 20,<br>    &quot;UserId&quot;: 4,<br>    &quot;Title&quot;: &quot;doloribus ad provident&quot;,<br>    &quot;Body&quot;: &quot;qui consequuntur...&quot;<br>  },<br>  {<br>    &quot;Id&quot;: 21,<br>    &quot;UserId&quot;: 1,<br>    &quot;Title&quot;: &quot;zc&quot;,<br>    &quot;Body&quot;: &quot;ccc&quot;<br>  }<br>]</pre><h3>Result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*tENVCIOyXDLjRInRqIBIWA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1f1e7630406" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React — SPA Navigation & Routing]]></title>
            <link>https://medium.com/@mk.muhammadkhoirudin/react-spa-navigation-routing-00ab5338e7a6?source=rss-ea3f3bfa423c------2</link>
            <guid isPermaLink="false">https://medium.com/p/00ab5338e7a6</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Muhammad Khoirudin]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 08:09:52 GMT</pubDate>
            <atom:updated>2026-03-31T08:09:52.614Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*aZDy7JAzTxC1zuShHwlVXw.png" /></figure><p>GitHub Repository : <a href="https://github.com/khoirmuhammad/website/tree/react-routing">https://github.com/khoirmuhammad/website/tree/react-routing</a></p><p>In other framework like flutter or WPF (.NET), when user click on navigation link, they use stack-based navigation model either stacking page or frame. This model make previous page stay mounted in memory or just hidden if doesn’t handled properly.</p><p>React Router works completely differently, It uses conditional rendering, not stacking. Example :</p><pre>&lt;Route path=&quot;/home&quot; element={&lt;Home/&gt;} /&gt;<br>&lt;Route path=&quot;/about&quot; element={&lt;About /&gt;} /&gt;</pre><p>If you go from /home to /about , &lt;Home/&gt; is unmounted (destroyed) and &lt;About /&gt; is mounted (created). It means No stacking &amp; No hidden pages sitting in memory.</p><p>However, memory issue still can happen in React, example if global state grows infinitely (just creating state without removal). But for this case (routing and navigation), in general it doesn’t causing memory leaks.</p><h3>React is Single Page Application (SPA)</h3><p>Characteristic SPA in react : Uses one HTML file (usually index.html), Load JavaScript code then everything is handled in the browser (client-side). Therefore, if user navigate to link, the browser does NOT reload the page, it just updating the UI dynamically.</p><h3>How navigation actually works (the flow)</h3><ol><li>User clicks a link/button, For example: “Go to Products Link”.</li><li>React stops the browser from reloading. Since normally, a website would reload the whole page.</li><li>The URL changes “/products”. It means, the page does NOT refresh only the address bar changes</li><li>React Router checks the URL, it looks “/products”, then we should go to Products page</li><li>React shows the correct component (it replaces only the main content. Only part of the screen updates, Navbar, Sidebar, Footer stay the same)</li></ol><pre>&lt;App&gt;<br> ├── &lt;Navbar /&gt;<br> ├── &lt;Sidebar /&gt;<br> └── &lt;MainContent&gt;   &lt;-- THIS changes<br>        ├── Home<br>        ├── ProductList<br>        └── ProductDetail</pre><h3>Code Started</h3><p>Production approach (MOST COMMON), Use React Router if you use plain react (not Next.js, Remix). So, please install the dependencies</p><pre>npm install react-router-dom</pre><p>Project Structure</p><pre>src/<br>├── main.tsx -&gt; Entry point (start app)<br>├── App.tsx -&gt; Main layout + routing<br>├── index.css<br>│<br>├── components/ -&gt; Reusable UI (Navbar, Sidebar, Footer)<br>│   ├── Navbar.tsx<br>│   ├── Sidebar.tsx<br>│   └── Footer.tsx<br>│<br>├── pages/ -&gt; Each “screen” (Home, Products, etc.)<br>│   ├── Home.tsx<br>│   ├── About.tsx<br>│   ├── Contact.tsx<br>│   ├── Products.tsx<br>│   ├── ProductDetail.tsx<br>│   └── Customers.tsx<br>│<br>├── data/ -&gt; Static/mock data (products)<br>│   └── products.ts</pre><h4>Component</h4><ol><li>Navbar</li></ol><pre>// Link is a special component used for navigation<br>// It likes a href but without reloading page<br>import { Link } from &quot;react-router-dom&quot;;<br><br>// export default → allows other files to use this component<br>// function Navbar() → creates the UI<br>export default function Navbar() {<br>  // &lt;nav&gt; → semantic HTML for navigation<br>  // When clicked → go to / (root URL)<br>  // These (/, /about, /contact) should match ourroutes in App.tsx<br>  return (<br>    &lt;nav className=&quot;bg-blue-600 text-white p-4 flex justify-between&quot;&gt;<br>      &lt;div className=&quot;font-bold&quot;&gt;My React App&lt;/div&gt;<br>      &lt;div className=&quot;space-x-4&quot;&gt;<br>        &lt;Link to=&quot;/&quot;&gt;Home&lt;/Link&gt;<br>        &lt;Link to=&quot;/about&quot;&gt;About&lt;/Link&gt;<br>        &lt;Link to=&quot;/contact&quot;&gt;Contact&lt;/Link&gt;<br>      &lt;/div&gt;<br>    &lt;/nav&gt;<br>  );<br>}</pre><p>2. Sidebar</p><pre>import { Link } from &quot;react-router-dom&quot;;<br><br>// These (/product, /customer) should match ourroutes in App.tsx<br>export default function Sidebar() {<br>  return (<br>    &lt;aside className=&quot;w-60 bg-gray-800 text-white p-4 hidden md:block&quot;&gt;<br>      &lt;ul className=&quot;space-y-2&quot;&gt;<br>        &lt;li&gt;<br>          &lt;Link to=&quot;/product&quot;&gt;Product&lt;/Link&gt;<br>        &lt;/li&gt;<br>        &lt;li&gt;<br>          &lt;Link to=&quot;/customer&quot;&gt;Customer&lt;/Link&gt;<br>        &lt;/li&gt;<br>      &lt;/ul&gt;<br>    &lt;/aside&gt;<br>  );<br>}</pre><h4>Page</h4><ol><li>Products</li></ol><pre>import { Link } from &quot;react-router-dom&quot;;<br>import { products } from &quot;../data/product&quot;;<br><br>export default function Products() {<br>  return (<br>    &lt;div className=&quot;grid grid-cols-1 md:grid-cols-3 gap-4&quot;&gt;<br>      {products.map((p) =&gt; (<br>        &lt;Link<br>          to={`/products/${p.id}`}<br>          key={p.id}<br>          className=&quot;bg-white p-4 rounded shadow&quot;<br>        &gt;<br>          &lt;div className=&quot;h-40 bg-gray-200 flex items-center justify-center&quot;&gt;<br>            {p.image ? (<br>              &lt;img src={p.image} alt={p.name} /&gt;<br>            ) : (<br>              &lt;span&gt;No Image&lt;/span&gt;<br>            )}<br>          &lt;/div&gt;<br>          &lt;h2 className=&quot;mt-2 font-bold&quot;&gt;{p.name}&lt;/h2&gt;<br>          &lt;p&gt;IDR {p.price}&lt;/p&gt;<br>        &lt;/Link&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}</pre><h4>App.tsx</h4><pre>// BrowserRouter : enables routing, Listens to URL changes. Without this, routing doesn&#39;t work<br>// Routes : container for all routes<br>// Route : defines each page<br>import { BrowserRouter, Routes, Route } from &quot;react-router-dom&quot;;<br>import Navbar from &quot;./component/Navbar&quot;;<br>import Sidebar from &quot;./component/Sidebar&quot;;<br>import Footer from &quot;./component/Footer&quot;;<br>import Home from &quot;./page/Home&quot;;<br>import About from &quot;./page/About&quot;;<br>import Contact from &quot;./page/Contact&quot;;<br>import Product from &quot;./page/Products&quot;;<br>import ProductDetail from &quot;./page/ProductDetail&quot;;<br>import Customer from &quot;./page/Customer&quot;;<br><br>function App() {<br>  return (<br>    &lt;BrowserRouter&gt;<br>      &lt;div className=&quot;flex flex-col min-h-screen&quot;&gt;<br>        &lt;Navbar /&gt;<br><br>        &lt;div className=&quot;flex flex-1&quot;&gt;<br>          &lt;Sidebar /&gt;<br>          <br>          // It makes conditional rendering, based on selected route<br>          &lt;main className=&quot;flex-1 p-4 bg-gray-100&quot;&gt;<br>            &lt;Routes&gt;<br>              &lt;Route path=&quot;/&quot; element={&lt;Home /&gt;} /&gt;<br>              &lt;Route path=&quot;/about&quot; element={&lt;About /&gt;} /&gt;<br>              &lt;Route path=&quot;/contact&quot; element={&lt;Contact /&gt;} /&gt;<br>              &lt;Route path=&quot;/product&quot; element={&lt;Product /&gt;} /&gt;<br>              &lt;Route path=&quot;/products/:id&quot; element={&lt;ProductDetail /&gt;} /&gt;<br>              &lt;Route path=&quot;/customer &quot; element={&lt;Customer /&gt;} /&gt;<br>            &lt;/Routes&gt;<br>          &lt;/main&gt;<br>        &lt;/div&gt;<br><br>        &lt;Footer /&gt;<br>      &lt;/div&gt;<br>    &lt;/BrowserRouter&gt;<br>  );<br>}<br><br>export default App;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=00ab5338e7a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React — Dynamic Form Component]]></title>
            <link>https://medium.com/@mk.muhammadkhoirudin/react-dynamic-form-component-dc38fa5eb1c6?source=rss-ea3f3bfa423c------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc38fa5eb1c6</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Muhammad Khoirudin]]></dc:creator>
            <pubDate>Sat, 28 Mar 2026 15:33:30 GMT</pubDate>
            <atom:updated>2026-03-28T15:33:30.320Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*WtZ6J40j5hIHnc5ocYg9Ng.png" /></figure><p><strong>Repository </strong>: <a href="https://github.com/khoirmuhammad/website/tree/react-form">https://github.com/khoirmuhammad/website/tree/react-form</a></p><p>While creating web application, we don’t have just one simple form, it may has many forms that change over time. Dynamic forms let us handle that without rewriting everything.</p><h4>The core problems</h4><p>Imagine we hardcode form like this</p><pre>&lt;InputText name=&quot;firstName&quot; /&gt;<br>&lt;InputText name=&quot;lastName&quot; /&gt;</pre><p>Then our product grows, we suddenly need several forms like registration, admin, settings form. Each form will have different fields, right? Without dynamic form we end up with copy paste components, writing simillar logic (agian and again), maintain multiple version if one filed need to change (That’s messy and error prone)</p><h4>Why it Really Matters</h4><ol><li>Scalability : As apps grow like forms multiply or requirement changes, dynamic forms let us scale without chaos.</li><li>Reusability : One component can be used by multiple form</li><li>Faster Development : Instead of writing UI every time in every forms, we just need calling the existing component</li></ol><h4>Folder Structure</h4><p>I hopw you have undertsood about react fundamental. Start form how to generate project untul how to run on your local machine. Now, let’s go to folder structure</p><pre>src/<br>├── components/<br>│   └── ui/                 # All form-related UI components<br>│       ├── forms/          <br>│       │   ├── InputText.tsx        # Actual input components<br>│       │   ├── FormFieldWrapper.tsx # Layout / UI wrappers<br>│       │   └── index.ts  # Public exports for form components<br>│<br>├── hooks/<br>│   └── useForm.ts       # Form logic (can grow later)<br>│<br>├── types/<br>│   └── form.types.ts       # All form-related types<br>│<br>├── utils/<br>│   └── form/<br>│       └── form.utils.ts    # Helpers (validation, mapping, etc.)<br>│<br>├── forms/                  # Actual form implementations (screens)<br>│   └── Form1.tsx<br>│<br>├── App.tsx<br>└── main.tsx (or index.tsx)</pre><h3>Features</h3><ol><li>Component : InputText (text, number, email, phone, date, datetime, time etc), Dropdown, Checkbox (Single / Multiple), Radio Button, Upload Image (Single / Multiple), Upload File (Single Multiple)</li><li>These components also available to load existing value. So, we can use them for creating new data or updating existing data.</li><li>Single Image upload : User can select an image, stores it into form state, show preview, allow removal (as well as clean up memory)</li><li>Multi Image upload : user upload multiple images, tores them as File[] , Shows preview grid<strong>, </strong>allow removal (as well as clean up memory)</li></ol><h3>How Everything Connects</h3><h4><strong>Step 1 — Define Types</strong></h4><pre>export type BaseFieldProps&lt;T, K extends PropertyKey&gt; = {<br>  name: K;<br>  value: T;<br>  required?: boolean;<br>  disabled?: boolean;<br>  readOnly?: boolean;<br>  label?: string;<br>  error?: string;<br>};</pre><ul><li>Type is not a function or even class</li><li>Export makes it visible and usable in other files</li><li><strong>K</strong> is PropertyKey. It’s a built-in type (If value is string | number | symbol are a valid value). <strong>K</strong> can be anything but it must be a valid object key, so if we pass boolean or object value to <strong>K</strong>, it bad value. <strong>K</strong> will be used for name/label/key (unique), so the value usually use string</li><li><strong>T</strong> can be anything, string | array | object | boolean are valid, since value can receive anything</li></ul><h4>Step 2 — Extend It</h4><pre>export type InputTextProps&lt;K extends PropertyKey&gt; = BaseFieldProps&lt;<br>  string,<br>  K<br>&gt; &amp; {<br>  placeholder?: string; //&lt;InputText placeholder=&quot;Enter email&quot; /&gt;<br>  maxLength?: number; //maxLength={50}<br>  min?: number; //min={0}<br>  max?: number; //max={100}<br>  type?: &quot;text&quot; | &quot;number&quot; | &quot;email&quot; | &quot;password&quot; | &quot;tel&quot; | &quot;url&quot;;<br>  pattern?: string; //pattern=&quot;^[A-Za-z]+$&quot;<br>  onChange: (name: K, value: string) =&gt; void;<br>};<br><br>//onchange<br>//We pass the field name and new value<br>//Example : onChange(&quot;email&quot;, &quot;mkh@gmail.com&quot;)<br>//Later on we will explain how we get onChange property</pre><h4>Step 3 — Build the Component</h4><pre>import type { InputTextProps } from &quot;../../../types/forms/form.type&quot;;<br>import FormFieldWrapper from &quot;./FormFieldWrapper&quot;;<br><br>//Destructuring Props, pull values out of props<br>const InputText = &lt;K extends string&gt;({<br>  name, <br>  value,<br>  onChange,<br>  label,<br>  error,<br>  placeholder,<br>  required,<br>  disabled,<br>  readOnly,<br>  maxLength,<br>  min,<br>  max,<br>  pattern,<br>  type = &quot;text&quot;,<br>}: InputTextProps&lt;K&gt;) =&gt; {<br>  return (<br>    &lt;FormFieldWrapper label={label} error={error}&gt;<br>      &lt;input<br>        type={type}<br>        name={name}<br>        value={value}<br>        onChange={(e) =&gt; onChange(name, e.target.value)}<br>        placeholder={placeholder}<br>        required={required}<br>        disabled={disabled}<br>        readOnly={readOnly}<br>        maxLength={maxLength}<br>        min={min}<br>        max={max}<br>        pattern={pattern}<br>        className=&quot;border p-2 rounded w-full&quot;<br>      /&gt;<br>    &lt;/FormFieldWrapper&gt;<br>  );<br>};<br><br>export default InputText;</pre><ul><li>&lt;K extends string&gt; : <strong>K</strong> is a type that must be a string. Even if K can be PropertyKey, since in this case K will be for key/name, then it propers use string instead.</li><li>This component follow InputTextProps&lt;K&gt; Type</li><li>&lt;FormFieldWrapper label={label} error={error}&gt; : It is a reusable component to wrap the field component</li></ul><pre>import React from &quot;react&quot;;<br><br>interface Props {<br>  label?: string;<br>  error?: string;<br>  children: React.ReactNode;<br>}<br><br>const FormFieldWrapper: React.FC&lt;Props&gt; = ({ label, error, children }) =&gt; {<br>  return (<br>    &lt;div className=&quot;flex flex-col gap-1&quot;&gt;<br>      {label &amp;&amp; &lt;label className=&quot;text-sm font-medium&quot;&gt;{label}&lt;/label&gt;}<br>      {children}<br>      {error &amp;&amp; &lt;span className=&quot;text-red-500 text-xs&quot;&gt;{error}&lt;/span&gt;}<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default FormFieldWrapper;</pre><ul><li>Show label, render the input (children) and show an error message.</li><li>children: React.ReactNode. It means “whatever we put inside this component”</li><li>{label &amp;&amp; &lt;label className… It means, if label exists then show it</li></ul><p>Before using the component, Please register the component inside index.ts file</p><pre>export { default as InputText } from &quot;./InputText&quot;;<br>//Take the default export from ./InputText and export it with the name InputText.</pre><p>Equivalent to</p><pre>import InputText from &quot;./InputText&quot;;<br>export { InputText };</pre><p>Why registering to index.ts is useful? Since we will use component either input text, dropdown, checkbox etc in certain form. Instead of import one by one, like this</p><pre>import InputText from &quot;../ui/forms/InputText&quot;;<br>import Dropdown from &quot;../ui/forms/Dropdown&quot;;</pre><p>We can do it (scalable &amp; cleaner than before)</p><pre>import { InputText, Dropdown } from &quot;../ui/forms&quot;;</pre><h4>Step 4 — Create Hook</h4><pre>//use React state to store form values.<br>import { useState } from &quot;react&quot;;<br><br>//useForm : custom hook (must start with use)<br>//&lt;T&gt; → generic type (dynamic form shape/object/structure) : useForm&lt;Form1Values&gt;<br>//initialState: T → your form structure<br>export function useForm&lt;T&gt;(initialState: T) {<br>  const [values, setValues] = useState&lt;T&gt;(initialState);<br><br>  //name: keyof T -&gt; name must be a key from T<br>  //value: T[keyof T]) -&gt; value can be any value type from T<br><br>  //(prev) -&gt; Previous state<br>  //...prev -&gt; Copy old values<br>  //[name]: value -&gt; Update only ONE field dynamically<br>  const handleChange = (name: keyof T, value: T[keyof T]) =&gt; {<br>    setValues((prev) =&gt; ({<br>      ...prev,<br>      [name]: value,<br>    }));<br>  };<br><br>  //Makes these usable outside the hook.<br>  return {<br>    values,<br>    setValues,<br>    handleChange,<br>  };<br>}</pre><p>Without creating useForm hooks, every form that we created should has this code to handle value changes.</p><pre>const [values, setValues] = useState({<br>  firstName: &quot;&quot;,<br>  lastName: &quot;&quot;,<br>});<br><br>const handleChange = (name, value) =&gt; {<br>  setValues((prev) =&gt; ({<br>    ...prev,<br>    [name]: value,<br>  }));<br>};</pre><p>So, it makes our component reusable, clean (component focus on UI not logic), scalable (one day we need ad validation, reset form or even submission form, it can be put here)</p><p>If you feel confused about</p><pre>const handleChange = (name: keyof T, value: T[keyof T])<br><br>//name : which field to update<br>//value : the new value</pre><p>Imagine</p><pre>//original Form<br>const form = {<br>  firstName: &quot;&quot;,<br>  age: 0,<br>};<br><br>//TypeScript will see as<br>type T = {<br>  firstName: string;<br>  age: number;<br>};<br><br>//name<br>//keyof T : all keys of T (&quot;firstName&quot; | &quot;age&quot;), all value outside will rejected<br><br>//value<br>//T[keyof T] : all possible value types in T. e.g string | number | etc</pre><h4>Step 5 — Use The Component</h4><p>Now, we are creating Form1.tsx, in order to call all field component created before.</p><pre>import {<br>  InputText,<br>  Dropdown,<br>} from &quot;../ui/forms/index&quot;;</pre><p>In step 3, when we created a component, then registered to indext.ts file. We import all your reusable form components. It also centralized design system.</p><pre>import { useForm } from &quot;../../hooks/useForm&quot;;</pre><p>Our custom hook (the “brain” of the form). We put here to handles all form state logic and avoids repeating useState everywhere.</p><pre>interface Form1Values {<br>  firstName: string;<br>  isActive: boolean;<br>  hobbies: string[];<br>  file: File | null;<br>  files: File[];<br>}</pre><p>Defines the structure of your form data (based on your form fields). It defines all form fields in one place, Enables TypeScript safety (by determining data type) and used by useForm&lt;Form1Values&gt;.</p><pre>const Form1: React.FC = () =&gt; {</pre><p>A React functional component. It is just a <strong>JavaScript function that returns UI (JSX)</strong>. JavaScript function usually void or returning data. So, FC means Fuctional Component.</p><pre>const { values, handleChange } = useForm&lt;Form1Values&gt;({<br>    firstName: &quot;&quot;,<br>    isActive: false,<br>    hobbies: [],<br>    file: null,<br>    files: [],<br>  });</pre><p>Initialize form state. values → current form data, handleChange → updates fields. This form must follow the structure of Form1Values .</p><p>Also define default value of each field.</p><pre>&lt;InputText<br>  name=&quot;firstName&quot;<br>  label=&quot;First Name&quot;<br>  value={values.firstName}<br>  onChange={handleChange}<br>  required<br>/&gt;</pre><p>Call child / field component.</p><p>One day we need to add another custom field, just follow the rule</p><ol><li>Create/add field type in form.type.ts</li><li>Create field component in component/ui/forms . e.g. Dropdown.tsx</li><li>Register component in component/ui/forms/index.ts , so it useable for another file.</li><li>Call field component in form component.</li></ol><h3>Field Component Explanation</h3><h4>1. Checkbox Group</h4><pre>// Ensures correct props &amp; type safety<br>import type { CheckboxGroupProps } from &quot;../../../types/forms/form.type&quot;;<br>// Reusable UI wrapper (label + error)<br>import FormFieldWrapper from &quot;./FormFieldWrapper&quot;;<br><br>// K / name must be a valid key (string | number | symbol)<br>// Props destructuring<br>const CheckboxGroup = &lt;K extends PropertyKey&gt;({<br>  name,<br>  value = [],<br>  onChange,<br>  label,<br>  error,<br>  options,<br>  disabled,<br>}: CheckboxGroupProps&lt;K&gt;) =&gt; {<br>  <br>// Runs when a checkbox is clicked<br>  const handleToggle = (optionValue: string) =&gt; {<br>    let newValue: string[]; // Declare new array<br><br>    // Check if already selected<br>    if (value.includes(optionValue)) {<br>      newValue = value.filter((v) =&gt; v !== optionValue); // Remove from array<br>    } else {<br>      newValue = [...value, optionValue]; // Add new value<br>    }<br><br>    // Update formvia hooks<br>    onChange(name, newValue);<br>  };<br><br>  return (<br>    &lt;FormFieldWrapper label={label} error={error}&gt;<br>      &lt;div className=&quot;flex flex-col gap-2&quot;&gt;<br>        &lt;!-- Render each checkbox --&gt;<br>        {options.map((opt) =&gt; (<br>          &lt;label key={opt.value} className=&quot;flex items-center gap-2&quot;&gt;<br>            &lt;input<br>              type=&quot;checkbox&quot;<br>              checked={value.includes(opt.value)} // If value exists : checked<br>              disabled={disabled}<br>              onChange={() =&gt; handleToggle(opt.value)}<br>            /&gt;<br>            {opt.label}<br>          &lt;/label&gt;<br>        ))}<br>      &lt;/div&gt;<br>    &lt;/FormFieldWrapper&gt;<br>  );<br>};<br><br>export default CheckboxGroup;</pre><h4>2. Input Image (Single)</h4><p><strong>FLOW</strong></p><pre>User selects file<br> ↓<br>handleChange()<br> ↓<br>onChange(name, file) ← goes to useForm hooks<br> ↓<br>state updated<br> ↓<br>value prop changes<br> ↓<br>previewUrl recalculated<br> ↓<br>image displayed</pre><pre>// useMemo → cache preview URL<br>// useEffect → cleanup memory<br>// useRef → access DOM input<br>import React, { useMemo, useEffect, useRef } from &quot;react&quot;;<br>import type { InputImageProps } from &quot;../../../types/forms/form.type&quot;;<br>import FormFieldWrapper from &quot;./FormFieldWrapper&quot;;<br><br>// K = type of name, can only string | number | symbol<br>const InputImage = &lt;K extends PropertyKey&gt;({<br>  name,<br>  value,<br>  onChange,<br>  label,<br>  error,<br>  required,<br>  disabled,<br>  accept = &quot;image/*&quot;,<br>  preview = true,<br>}: InputImageProps&lt;K&gt;) =&gt; {<br>  //It just creates a reference (pointer), if button clicked, it refer to this input<br>  const inputRef = useRef&lt;HTMLInputElement | null&gt;(null);<br><br>  // Generate preview : When value changes, Create a temporary URL<br>  // Why useMemo : Only run when value changes<br>  // useMemo = compute &amp; return value, since we only need the value, not doing something like API call, update DOM so useMemo is better than useEffect<br>  // useMemo = Input (File) → Output (URL)<br>  // useEffect = Input → run code → update state → re-render → get value<br>  const previewUrl = useMemo(() =&gt; {<br>    if (!value) return null;<br>    return URL.createObjectURL(value);<br>  }, [value]);<br><br>  // Cleanup memory<br>  // Since createObjectURL allocates memory, Without cleanup, memory leak<br>  // This run when : component unmounts (component disappears / hidden / remove from DOM) or previewUrl changes<br>  // Why useEffect : Cleanup must happen when something changes or component is removed<br>  <br>  // Mount   = component appears<br>  // Update  = component changes<br>  // Unmount = component disappears<br>  useEffect(() =&gt; {<br>    return () =&gt; {<br>      if (previewUrl) {<br>        URL.revokeObjectURL(previewUrl);<br>      }<br>    };<br>  }, [previewUrl]);<br><br>  // Handle file selection (single only)<br>  // Triggered when user selects a file<br>  const handleChange = (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>    // Get first file, if none file then null as a default<br>    const file = e.target.files?.[0] || null;<br>    // Updates state<br>    onChange(name, file);<br><br>    // Reset input, user can re-select the same file again<br>    // prevent allows re-select same file<br>    if (inputRef.current) {<br>      inputRef.current.value = &quot;&quot;;<br>    }<br>  };<br><br>  // Remove image<br>  const handleRemove = () =&gt; {<br>    // Update state, Clear image from form state<br>    onChange(name, null);<br><br>    // prevent <br>    if (inputRef.current) {<br>      inputRef.current.value = &quot;&quot;;<br>    }<br>  };<br><br>  return (<br>    &lt;FormFieldWrapper label={label} error={error}&gt;<br>      &lt;div className=&quot;flex flex-col gap-3&quot;&gt;<br>        {/* Hidden input */}<br>        &lt;input<br>          ref={inputRef}<br>          type=&quot;file&quot;<br>          name={String(name)}<br>          accept={accept}<br>          onChange={handleChange}<br>          required={required}<br>          disabled={disabled}<br>          className=&quot;hidden&quot;<br>        /&gt;<br><br>        {/* Custom Button */}<br>        &lt;button<br>          type=&quot;button&quot;<br>          onClick={() =&gt; inputRef.current?.click()}<br>          disabled={disabled}<br>          className=&quot;bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 disabled:opacity-50&quot;<br>        &gt;<br>          Choose Image<br>        &lt;/button&gt;<br><br>        {/* File Info */}<br>        &lt;p className=&quot;text-sm text-gray-600&quot;&gt;<br>          {value ? &quot;1 file selected&quot; : &quot;No file selected&quot;}<br>        &lt;/p&gt;<br><br>        {/* Preview */}<br>        {preview &amp;&amp; previewUrl &amp;&amp; (<br>          &lt;div className=&quot;relative w-32&quot;&gt;<br>            &lt;img<br>              src={previewUrl}<br>              alt=&quot;preview&quot;<br>              className=&quot;w-32 h-32 object-cover rounded border&quot;<br>            /&gt;<br><br>            &lt;button<br>              type=&quot;button&quot;<br>              onClick={handleRemove}<br>              className=&quot;absolute top-1 right-1 bg-red-500 text-white text-xs px-2 py-1 rounded hover:bg-red-600&quot;<br>            &gt;<br>              ✕<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        )}<br>      &lt;/div&gt;<br>    &lt;/FormFieldWrapper&gt;<br>  );<br>};<br><br>export default InputImage;</pre><h4>3. Input Image (Multiple)</h4><p><strong>FLOW</strong></p><pre>User selects files<br>   ↓<br>handleChange()<br>   ↓<br>onChange(name, files[])<br>   ↓<br>Form state updates<br>   ↓<br>value changes<br>   ↓<br>previewUrls recalculated<br>   ↓<br>images rendered</pre><pre>// <br>import React, { useMemo, useEffect, useRef } from &quot;react&quot;;<br>import type { InputMultipleImageProps } from &quot;../../../types/forms/form.type&quot;;<br>import FormFieldWrapper from &quot;./FormFieldWrapper&quot;;<br><br>const InputMultipleImage = &lt;K extends PropertyKey&gt;({<br>  name,<br>  value,<br>  onChange,<br>  label,<br>  error,<br>  required,<br>  disabled,<br>  accept = &quot;image/*&quot;,<br>  maxFiles,<br>  preview = true,<br>}: InputMultipleImageProps&lt;K&gt;) =&gt; {<br>  const inputRef = useRef&lt;HTMLInputElement | null&gt;(null);<br><br>  // Generate preview URLs<br>  const previewUrls = useMemo(() =&gt; {<br>    // Each file → converted to preview URL<br>    return value.map((file) =&gt; URL.createObjectURL(file));<br>  }, [value]);<br><br>  // Cleanup memory<br>  useEffect(() =&gt; {<br>    // Each createObjectURL uses memory<br>    return () =&gt; {<br>      previewUrls.forEach((url) =&gt; URL.revokeObjectURL(url));<br>    };<br>  }, [previewUrls]);<br><br>  // Handle file selection<br>  const handleChange = (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>  // Convert FileList → File[]  <br>  const files = Array.from(e.target.files || []);<br>    <br>    // Allows adding more images instead of replacing<br>    let newFiles = [...value, ...files];<br><br>    // Prevent exceeding max e.g 3<br>    if (maxFiles) {<br>      // Keep only the first maxFiles items<br>      // Take items from index 0 up to (but NOT including) index 3<br>      newFiles = newFiles.slice(0, maxFiles);<br>    }<br><br>    onChange(name, newFiles);<br><br>    // Reset input (prevents stale file list)<br>    if (inputRef.current) {<br>      inputRef.current.value = &quot;&quot;;<br>    }<br>  };<br><br>  // Remove image<br>  const handleRemove = (index: number) =&gt; {<br>    // Removes selected image<br>    const updated = value.filter((_, i) =&gt; i !== index);<br>    onChange(name, updated);<br><br>    if (inputRef.current) {<br>      inputRef.current.value = &quot;&quot;;<br>    }<br>  };<br><br>  return (<br>    &lt;FormFieldWrapper label={label} error={error}&gt;<br>      &lt;div className=&quot;flex flex-col gap-3&quot;&gt;<br>        {/* Hidden native input */}<br>        &lt;input<br>          ref={inputRef}<br>          type=&quot;file&quot;<br>          name={String(name)}<br>          accept={accept}<br>          multiple<br>          onChange={handleChange}<br>          required={required}<br>          disabled={disabled}<br>          className=&quot;hidden&quot;<br>        /&gt;<br><br>        {/* Custom Button */}<br>        &lt;button<br>          type=&quot;button&quot;<br>          onClick={() =&gt; inputRef.current?.click()}<br>          disabled={disabled}<br>          className=&quot;bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 disabled:opacity-50&quot;<br>        &gt;<br>          Choose Images<br>        &lt;/button&gt;<br><br>        {/* Custom File Info */}<br>        &lt;p className=&quot;text-sm text-gray-600&quot;&gt;<br>          {value.length &gt; 0<br>            ? `${value.length} file${value.length &gt; 1 ? &quot;s&quot; : &quot;&quot;} selected`<br>            : &quot;No file selected&quot;}<br>        &lt;/p&gt;<br><br>        {/* Preview */}<br>        {preview &amp;&amp; value.length &gt; 0 &amp;&amp; (<br>          &lt;div className=&quot;grid grid-cols-3 gap-2&quot;&gt;<br>            {previewUrls.map((url, index) =&gt; (<br>              &lt;div key={index} className=&quot;relative&quot;&gt;<br>                &lt;img<br>                  src={url}<br>                  alt={`preview-${index}`}<br>                  className=&quot;w-full h-24 object-cover rounded border&quot;<br>                /&gt;<br><br>                &lt;button<br>                  type=&quot;button&quot;<br>                  onClick={() =&gt; handleRemove(index)}<br>                  className=&quot;absolute top-1 right-1 bg-red-500 text-white text-xs px-2 py-1 rounded hover:bg-red-600&quot;<br>                &gt;<br>                  ✕<br>                &lt;/button&gt;<br>              &lt;/div&gt;<br>            ))}<br>          &lt;/div&gt;<br>        )}<br>      &lt;/div&gt;<br>    &lt;/FormFieldWrapper&gt;<br>  );<br>};<br><br>export default InputMultipleImage;</pre><h4>4. Input File (Dynamic &amp; Generic)</h4><p>We can control file acceptance, file not acceptance (not allowed), is single or multiple, number/max of file etc.</p><pre>import React, { useMemo, useEffect, useRef } from &quot;react&quot;;<br>import FormFieldWrapper from &quot;./FormFieldWrapper&quot;;<br>import type { InputFileProps } from &quot;../../../types/forms/form.type&quot;;<br><br>// ================= UTILITIES =================<br><br>// Convert &quot;pdf|docx|xlsx&quot; into [&quot;pdf&quot;, &quot;docx&quot;, &quot;xlsx&quot;]<br>const parseExtensions = (ext?: string): string[] =&gt; {<br>  if (!ext) return [];<br>  return ext.split(&quot;|&quot;).map((e) =&gt; e.trim().toLowerCase());<br>};<br><br>// Decide if a file is allowed or not<br>const isFileValid = (<br>  file: File,<br>  accept?: string,<br>  notAllowed?: string,<br>): boolean =&gt; {<br>  // Get file extension<br>  const fileExt = file.name.split(&quot;.&quot;).pop()?.toLowerCase() || &quot;&quot;;<br><br>  const allowList = parseExtensions(accept);<br>  const blockList = parseExtensions(notAllowed);<br><br>  // Block list has priority<br>  if (blockList.length &amp;&amp; blockList.includes(fileExt)) return false;<br><br>  // If allow list exists → only allow those<br>  if (allowList.length) return allowList.includes(fileExt);<br><br>  // If no rules → allow everything<br>  return true;<br>};<br><br>// make it to : &lt;input accept=&quot;.pdf,.docx&quot; /&gt;<br>const buildAcceptAttr = (accept?: string) =&gt; {<br>  if (!accept) return undefined;<br>  return accept<br>    .split(&quot;|&quot;)<br>    .map((ext) =&gt; `.${ext.trim()}`)<br>    .join(&quot;,&quot;);<br>};<br><br>// ================= COMPONENT =================<br><br>const InputFile = &lt;K extends PropertyKey&gt;({<br>  name,<br>  value,<br>  onChange,<br>  label,<br>  error,<br>  required,<br>  disabled,<br>  isSingle = true,<br>  accept,<br>  notAllowed,<br>  maxFiles,<br>  preview = true,<br>}: InputFileProps&lt;K&gt;) =&gt; {<br>  const inputRef = useRef&lt;HTMLInputElement | null&gt;(null);<br><br>  // Normalize value → always array internally<br>  // Actual value can be : File | File[] | null, so This makes it ALWAYS: File[]<br>  // So, we don’t need to worry about isSingle logic<br>  const files: File[] = useMemo(() =&gt; {<br>    if (!value) return [];<br>    return Array.isArray(value) ? value : [value];<br>  }, [value]);<br><br>  // Generate preview URLs<br>  const previewUrls = useMemo(() =&gt; {<br>    return files.map((file) =&gt; URL.createObjectURL(file));<br>  }, [files]);<br><br>  // Cleanup memory<br>  useEffect(() =&gt; {<br>    return () =&gt; {<br>      previewUrls.forEach((url) =&gt; URL.revokeObjectURL(url));<br>    };<br>  }, [previewUrls]);<br><br>  // Handle file selection<br>  const handleChange = (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>    // Get selected files<br>    const selectedFiles = Array.from(e.target.files || []);<br><br>    // Validate<br>    const validFiles = selectedFiles.filter((file) =&gt;<br>      isFileValid(file, accept, notAllowed),<br>    );<br><br>    // Alert if invalid<br>    if (validFiles.length !== selectedFiles.length) {<br>      alert(&quot;Some files are not allowed&quot;);<br>    }<br><br>    if (isSingle) {<br>      const file = validFiles[0] || null;<br>      onChange(name, file);<br>    } else {<br>      let newFiles = [...files, ...validFiles]; // Append new files<br><br>      if (maxFiles) {<br>        newFiles = newFiles.slice(0, maxFiles);<br>      }<br><br>      onChange(name, newFiles);<br>    }<br><br>    // Reset input (important!)<br>    if (inputRef.current) {<br>      inputRef.current.value = &quot;&quot;;<br>    }<br>  };<br><br>  // Remove file<br>  const handleRemove = (index: number) =&gt; {<br>    if (isSingle) {<br>      onChange(name, null);<br>    } else {<br>      const updated = files.filter((_, i) =&gt; i !== index);<br>      onChange(name, updated);<br>    }<br><br>    if (inputRef.current) {<br>      inputRef.current.value = &quot;&quot;;<br>    }<br>  };<br><br>  return (<br>    &lt;FormFieldWrapper label={label} error={error}&gt;<br>      &lt;div className=&quot;flex flex-col gap-3&quot;&gt;<br>        {/* Hidden Input */}<br>        &lt;input<br>          ref={inputRef}<br>          type=&quot;file&quot;<br>          name={String(name)}<br>          accept={buildAcceptAttr(accept)}<br>          multiple={!isSingle}<br>          onChange={handleChange}<br>          required={required}<br>          disabled={disabled}<br>          className=&quot;hidden&quot;<br>        /&gt;<br><br>        {/* Button */}<br>        &lt;button<br>          type=&quot;button&quot;<br>          onClick={() =&gt; inputRef.current?.click()}<br>          disabled={disabled}<br>          className=&quot;bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 disabled:opacity-50&quot;<br>        &gt;<br>          {isSingle ? &quot;Choose File&quot; : &quot;Choose Files&quot;}<br>        &lt;/button&gt;<br><br>        {/* File Info */}<br>        &lt;p className=&quot;text-sm text-gray-600&quot;&gt;<br>          {files.length &gt; 0<br>            ? `${files.length} file${files.length &gt; 1 ? &quot;s&quot; : &quot;&quot;} selected`<br>            : &quot;No file selected&quot;}<br>        &lt;/p&gt;<br><br>        {/* Preview */}<br>        {preview &amp;&amp; files.length &gt; 0 &amp;&amp; (<br>          &lt;div className=&quot;grid grid-cols-3 gap-2&quot;&gt;<br>            {files.map((file, index) =&gt; {<br>              const url = previewUrls[index];<br>              const isImage = file.type.startsWith(&quot;image/&quot;);<br><br>              return (<br>                &lt;div key={index} className=&quot;relative border rounded p-2&quot;&gt;<br>                  {/* Image Preview */}<br>                  {isImage ? (<br>                    &lt;img<br>                      src={url}<br>                      alt={`preview-${index}`}<br>                      className=&quot;w-full h-24 object-cover rounded&quot;<br>                    /&gt;<br>                  ) : (<br>                    /* Non-image */<br>                    &lt;div className=&quot;flex flex-col items-center justify-center h-24 text-xs text-gray-600 text-center break-all&quot;&gt;<br>                      &lt;span className=&quot;font-semibold&quot;&gt;<br>                        {file.name.split(&quot;.&quot;).pop()?.toUpperCase()}<br>                      &lt;/span&gt;<br>                      &lt;span className=&quot;truncate w-full&quot;&gt;{file.name}&lt;/span&gt;<br>                    &lt;/div&gt;<br>                  )}<br><br>                  {/* Remove */}<br>                  &lt;button<br>                    type=&quot;button&quot;<br>                    onClick={() =&gt; handleRemove(index)}<br>                    className=&quot;absolute top-1 right-1 bg-red-500 text-white text-xs px-2 py-1 rounded hover:bg-red-600&quot;<br>                  &gt;<br>                    ✕<br>                  &lt;/button&gt;<br>                &lt;/div&gt;<br>              );<br>            })}<br>          &lt;/div&gt;<br>        )}<br>      &lt;/div&gt;<br>    &lt;/FormFieldWrapper&gt;<br>  );<br>};<br><br>export default InputFile;</pre><h3>Result</h3><h4>1. New Form</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*0dECnqvqAzfYYL9nSTVaOA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*zYJ0DpqGg2890PcD6GlHKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*oJOXAMlwF5e_aKnEW9meJA.png" /></figure><h4>2. Load Existing Value into Form</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*OH3gvNWgn5hQ4YW9t29rCA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*9GCeZzrXPie-iiA-mr2Mbw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*S7kpqJhU54-Ok21SXwMu4Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc38fa5eb1c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding RabbitMQ: Core Concepts of Producers, Consumers, Queues, and Exchanges]]></title>
            <link>https://medium.com/@mk.muhammadkhoirudin/understanding-rabbitmq-core-concepts-of-producers-consumers-queues-and-exchanges-faf18e8265bd?source=rss-ea3f3bfa423c------2</link>
            <guid isPermaLink="false">https://medium.com/p/faf18e8265bd</guid>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Muhammad Khoirudin]]></dc:creator>
            <pubDate>Fri, 06 Feb 2026 16:55:31 GMT</pubDate>
            <atom:updated>2026-02-06T16:55:31.865Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*_YoD4lRPuMgBmIb3E9ONGw.png" /></figure><p>RabbitMQ is a great thing to learn if you’re touching distributed systems, microservices, or event-driven architecture.</p><p><strong>What is RabbitMQ?</strong> an open-source message broker that implements the AMQP (Advanced Message Queuing Protocol). It enables applications to communicate with each other by sending and receiving messages through queues.</p><p><strong>Why do we need RabbitMQ?</strong></p><ul><li><strong>Decoupling / Loose Coupling</strong>: Producers don’t need to know who consumes messages, this reduces dependencies between services</li><li><strong>Asynchronous processing</strong>: Applications don’t need to wait for tasks to complete. Instead of blocking while work is being done, tasks can be processed in the background.</li><li><strong>Scalability</strong>: You can easily add more consumers to handle increased load, improving system performance</li></ul><p><strong>Use cases</strong></p><ul><li>Background jobs (sending emails, image processing, report generation)</li><li>Communication between services (Microservice)</li><li>Event Driven Architecture (EDA)</li></ul><h3>Core Concepts of RabbitMQ as Message Broker</h3><h4>1. Producer</h4><p>A <strong>Producer</strong> is the application that sends messages.</p><p>It never communicates directly with consumers.<br>This means the producer does not know — and should not care — who will receive the message.</p><p>Instead, the producer sends messages to an <strong>Exchange</strong>, not directly to a queue. The exchange acts as a routing mechanism that decides how messages should be distributed to queues.</p><pre>Producer<br>   |<br>   v<br>Exchange<br>   |<br>   ├── Queue A → Consumer A<br>   ├── Queue B → Consumer B<br>   └── Queue C → Consumer C</pre><h4>2. Consumer</h4><p>A <strong>Consumer</strong> is responsible for receiving and processing messages from a queue.</p><p>After successfully processing a message, the consumer sends an <strong>acknowledgment (ACK)</strong> to RabbitMQ. Once RabbitMQ receives the acknowledgment, it removes the message from the queue.</p><p>Each queue can have multiple workers (consumers) attached to it. RabbitMQ distributes messages among them.</p><p>Please see the following scenario. A customer places an order, and system want to :</p><ul><li>Reserve inventory (order emit message to inventoryService.queue)</li><li>Charge payment (order emit event/message to paymentService.queue)</li><li>Send confirmation email (order emit message to emailService.queue)</li></ul><pre>order.events (topic exchange)<br>   ├── inventoryService.queue   → Inventory Service<br>   ├── paymentService.queue     → Payment Service<br>   └── emailService.queue       → Email Service</pre><p><strong>Key rule:</strong> Different responsibilities should have different queues.</p><p>The question “many workers per ONE queue”, where is it?</p><pre>order.created { orderId: 123 }<br>order.created { orderId: 124 }<br><br>inventoryService.queue → Inventory Worker #1 (handle orderId 123)<br>                       → Inventory Worker #2 (handle orderId 124)<br><br>payementService.queue → Payment Worker #1 (handle orderId 123)<br>                      → Payment Worker #2 (handle orderId 124)<br><br>emailService.queue → Email Worker #1 (handle orderId 123)<br>                   → Email Worker #2 (handle orderId 124)</pre><h4>3. Message</h4><p>A RabbitMQ message is just a byte array + metadata. It actually doesn’t care about JSON, XML, Plain Text, Binnary File like Image, PDF etc. It will be converted to byte format.</p><p>Data Structure</p><pre>Message<br>├── Body (bytes)        ← your data (The payload — the thing your app wants to send)<br>└── Properties          ← metadata (common data like Routing key, Headers, Content-Type, Timestamps etc)</pre><h4>4. Exchange</h4><p>Producers cannot send messages directly to queues because</p><ul><li>Producer must know queue names</li><li>Producer must know how many queues exist</li><li>Producer must know routing rules</li></ul><p>This creates tight coupling.</p><p>By using an <strong>exchange</strong>, producers send messages to the exchange instead of directly to queues. The exchange decides where the messages should go.</p><p>An exchange only <strong>routes</strong> messages. It does not store or process them.</p><p>To understand exchanges, you must also understand about routing key, binding and exchange type. Let’s use simple anlaogies</p><ol><li>You = Producers</li><li>A receptionist = Exchange</li><li>Several mailboxes = Queues</li><li>A label on your envelope = Routing Key</li><li>Sticky notes on mailboxes/Rules = Binding</li></ol><p>Now let’s connect to our explanation before</p><ol><li>You <em>(producers)</em> give envelope <em>(message) </em>to receptionist <em>(exchange). </em>Since, you don’t know which mailbox should get it.</li><li>Routing key is just a label on the envelope (common string), like topic written on the envelop. Example : “order.created”</li><li>Binding is a rule attached to a mailbox.</li><li>Exchange type defines how the receptionist reads labels.</li></ol><p><strong>1️⃣ Default Exchange</strong></p><p>It is an automatic binding. Routing key must equals Queue Name. Then, Message goes directly to queue name (Send directly to this exact queue by name). Exchange name will be empty string</p><pre>//PRODUCERS<br>internal class ProducerDirectExchangeType<br>    {      <br>        public static void DefaultExchangeName(IModel channel)<br>        {<br>            <br>            channel.QueueDeclare(queue: &quot;default&quot;, exclusive: false);<br><br>            var message = new { Name = &quot;Producer&quot;, Message = &quot;Hello! this is default exchange&quot; };<br>            var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message));<br>            channel.BasicPublish(exchange: &quot;&quot;, routingKey: &quot;default&quot;, body: body);<br><br>        }<br>    }<br><br>//CONSUMERS<br>internal class ConsumerDirectExchangeType<br>    {<br><br>        public static void DefaultExchangeName(IModel channel)<br>        {<br>            channel.QueueDeclare(queue: &quot;default&quot;, exclusive: false);<br><br>            var consumer = new EventingBasicConsumer(channel);<br>            consumer.Received += (sender, eventArgs) =&gt;<br>            {<br>                var body = eventArgs.Body.ToArray();<br>                var message = Encoding.UTF8.GetString(body);<br><br>                Console.WriteLine($&quot;Message received: {message}&quot;);<br>            };<br><br>            channel.BasicConsume(queue: &quot;default&quot;, autoAck: true, consumer: consumer);<br><br>        }<br>    }</pre><p>It’s good for : Simple point-to-point messaging, simple setup (for demos)</p><p><strong>2️⃣ Direct Exchange (like default but custom one you create)</strong></p><p>Routes based on exact match<strong> </strong>(binding between routing key and queue)</p><ul><li>Exchange name : Your custom name</li><li>Binding key : Anything you define</li></ul><p>Example</p><pre>exchange = orders.exchange<br><br>//If routing key = order.created, send message to inventory.queue<br>// inventory.queue says: Hey exchange, give me messages where routing_key = order.created<br>inventory.queue  → order.created<br><br>//If routing key = order.paid, send message to payment.queue<br>// payment.queue says: Hey exchange, give me messages where routing_key = order.paid<br>payment.queue    → order.paid</pre><pre>//PRODUCERS<br><br>// Declare direct exchange<br>channel.ExchangeDeclare(<br>  exchange: &quot;orders.exchange&quot;,<br>  type: ExchangeType.Direct,<br>  durable: true<br>);<br><br>// Example 1: Order Created<br>channel.BasicPublish(<br>  exchange: &quot;orders.exchange&quot;,<br>  routingKey: &quot;order.created&quot;,<br>  basicProperties: null,<br>  body: Encoding.UTF8.GetBytes(&quot;Order 123 created&quot;)<br>);<br><br>// Example 2: Order Paid<br>channel.BasicPublish(<br>  exchange: &quot;orders.exchange&quot;,<br>  routingKey: &quot;order.paid&quot;,<br>  basicProperties: null,<br>  body: Encoding.UTF8.GetBytes(&quot;Order 123 paid&quot;)<br>);<br><br><br>//CONSUMERS<br><br>// Example 1: Order Created<br>channel.ExchangeDeclare(<br>  exchange: &quot;orders.exchange&quot;,<br>  type: ExchangeType.Direct,<br>  durable: true<br>);<br><br>channel.QueueDeclare(<br>  queue: &quot;inventory.queue&quot;,<br>  durable: true,<br>  exclusive: false,<br>  autoDelete: false,<br>  arguments: null<br>);<br><br>// Bind with routing key<br>channel.QueueBind(<br>  queue: &quot;inventory.queue&quot;,<br>  exchange: &quot;orders.exchange&quot;,<br>  routingKey: &quot;order.created&quot;<br>);<br><br>// Example 2: Order Paid<br>channel.ExchangeDeclare(<br>  exchange: &quot;orders.exchange&quot;,<br>  type: ExchangeType.Direct,<br>  durable: true<br>);<br><br>channel.QueueDeclare(<br>  queue: &quot;payment.queue&quot;,<br>  durable: true,<br>  exclusive: false,<br>  autoDelete: false,<br>  arguments: null<br>);<br><br>// Bind with routing key<br>channel.QueueBind(<br>  queue: &quot;payment.queue&quot;,<br>  exchange: &quot;orders.exchange&quot;,<br>  routingKey: &quot;order.paid&quot;<br>);</pre><p>Conclusion : routing key &amp; queue will be bound.</p><p>Use Case</p><ul><li>Event driven architecture. Example : Order service will notify inventory and payment service</li></ul><p><strong>3️⃣ Topic Exchange</strong></p><p>It likes direct, but supports wildcards.</p><pre>* → exactly one word<br># → zero or more words</pre><p>Why Topic Exchange Is Needed in Real Systems? Because real systems grow and direct exchange becomes too rigid.</p><p>At first we have several routing key likes</p><pre>order.created<br>order.paid<br>order.cancelled</pre><p>By using direct exchange works perfectly. Now we introduce regions (may different region have tax calculation logic).</p><pre>order.created.us<br>order.created.eu<br>order.created.asia<br><br>order.paid.us<br>order.paid.eu<br>order.paid.asia<br><br>order.cancelled.us<br>order.cancelled.eu<br>order.cancelled.asia</pre><p>If the binding</p><pre>//EXMAPLE 1<br>order.*.us<br><br>It means<br>- first word must be order<br>- Second word can be anything<br>- Third word must be us<br><br>So these following routing key will be matched<br>order.created.us<br>order.paid.us<br>order.cancelled.us<br><br>//EXAMPLE 2<br>order.created.*<br><br>It Means<br>- First word must be order<br>- Second word must be created<br>- Third word can be anything<br><br>So these following routing key will be matched<br>order.created.us<br>order.created.eu<br>order.created.asia<br><br>//EXAMPLE 3<br>order.#<br><br>It means<br>- First word must be order<br>- After that? Anything. Any length.<br><br>So these following routing key will be matched<br>order.created.us<br>order.paid.eu<br>order.cancelled.asia<br>order.anything.anything.anything</pre><p><strong>4️⃣ Fanout Exchange</strong></p><p>It sends every message to all bound queues. It does not care about routing key.</p><p>Use case example :</p><p>Real Use Case #1 — Notifications</p><pre>user.registered<br><br>//You want to: Send welcome email, Send SMS, Log analytics</pre><p>Real Use Case #2 — Cache Invalidation</p><p>Imagine microservices each have their own cache. When product price changes, it will publish “product.updated”. ou need every service to clear cache. Instead of calling each service, just use fanout</p><pre>//PRODUCERS<br><br>// Declare fanout exchange<br>channel.ExchangeDeclare(<br>  exchange: &quot;notification.exchange&quot;,<br>  type: ExchangeType.Fanout,<br>  durable: false<br>);<br><br>channel.BasicPublish(<br>  exchange: &quot;notification.exchange&quot;,<br>  routingKey: &quot;&quot;, // ignored in fanout<br>  basicProperties: null,<br>  body: Encoding.UTF8.GetBytes(&quot;User Khoir registered!&quot;);<br>);<br><br>//CONSUMERS (Create for every service like this : Email, SMS, Log Services)<br>channel.ExchangeDeclare(<br>  exchange: &quot;notification.exchange&quot;,<br>  type: ExchangeType.Fanout,<br>  durable: false<br>);<br><br>var queueName = channel.QueueDeclare().QueueName;<br><br>channel.QueueBind(<br>  queue: queueName,<br>  exchange: &quot;notification.exchange&quot;,<br>  routingKey: &quot;&quot;<br>);</pre><p>If you call “var queueName = channel.QueueDeclare().QueueName;”, every service has unique queue once it’s auto generated. Or we can create manual queue for each service. So, after one service done (ack = true), it won’t remove the message in a queue.</p><h3>Conclusion</h3><p>RabbitMQ is more than just a message broker. It is a key building block for designing scalable, decoupled, and event-driven systems.</p><p>By understanding the roles of producers, exchanges, queues, and consumers, we can clearly see how messages flow through the system. Producers send messages to exchanges, exchanges route them based on routing keys and bindings, and consumers process messages from queues while acknowledging successful handling.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=faf18e8265bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Concurrency, Parallelism, Multi Threading and Asynchronous Programming]]></title>
            <link>https://medium.com/@mk.muhammadkhoirudin/understanding-concurrency-parallelism-multi-threading-and-asynchronous-programming-c3fc6a7156d8?source=rss-ea3f3bfa423c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3fc6a7156d8</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Muhammad Khoirudin]]></dc:creator>
            <pubDate>Mon, 02 Feb 2026 04:21:25 GMT</pubDate>
            <atom:updated>2026-02-02T04:21:25.748Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wvNoKtNk-tYmkRyR-uEtfg.png" /><figcaption><a href="https://miro.medium.com/v2/resize:fit:1200/1*T0CHXvBv4IgcFj9UxSNQhQ.png">https://miro.medium.com/v2/resize:fit:1200/1*T0CHXvBv4IgcFj9UxSNQhQ.png</a></figcaption></figure><p>Terms such as concurrent, parallel, simultaneous, multithreading, and asynchronous are often used interchangeably in software development, leading to widespread misunderstanding. Although closely related, these concepts describe different ideas, some refer to how tasks are organized and progress, while others describe the techniques used to implement that behavior.</p><p>For example, concurrency and parallelism are conceptual models, whereas multithreading and asynchronous programming are implementation approaches. Confusing these distinctions can result in incorrect assumptions about performance, scalability, and system behavior. A clear understanding of these terms is essential for designing efficient and reliable software systems.</p><h3>Concurrency &amp; Parallelism are a Concept</h3><h4>1. Concurrency</h4><p>A single CPU core that makes progress on many tasks within the same time window (time period), but not at the same instant.</p><p><strong>Key Points</strong></p><ul><li>Single core CPU</li><li>Handle mutliple tasks</li><li>Makes all tasks progress (by switching between tasks quickly)</li><li>Same time period, e.g. in 20 seconds</li></ul><p><strong>Diagram</strong></p><pre>Time → (20 Seconds)<br>Thread A: ████      ████<br>Thread B:      ████      ████<br><br>- 1 Core CPU<br>- Have 2 Threads<br>- Have 4 tasks (scheduled on the threads; never run together but all make progress during the time period)<br>- Only once task runs at any instant. (Task A: 0–5 seconds, Task B: 5–10 seconds, etc.)<br></pre><p><strong>Example (Real Life)</strong></p><p>One chef cooking alone (he makes progress for many tasks during the same time pariod)</p><ul><li>Starts boiling rice</li><li>[While rice is boiled] — Chops the vegetables</li><li>[While vegetables are chopped] — Prepare dishes</li></ul><p><strong>Example (System)</strong></p><ul><li>User A (request 1): awaited, waiting for database</li><li>User B (request 2): actively processing data</li><li>User C (request 3): awaited, waiting for network</li></ul><p>Both examples show several tasks making progress. <em>It’s called concurrent not parallel</em></p><h4>2. Parallelism</h4><p>Parallelism is equivalent to simultaneous execution. Multiple CPU Cores work on multiple tasks in the same instant.</p><p><strong>Diagram</strong></p><pre>Time → (10 Seconds)<br>Core 1: Thread A █████████<br>Core 2: Thread B █████████<br><br>Threads truly run at the same time on different cores.</pre><p><strong>Example (Real Life)</strong></p><p>Three people cooking together at the same time</p><ul><li>Person 1 boils rice</li><li>Person 2 chops vegetables</li><li>Person 3 prepares the dishes</li></ul><p><strong>Example (System)</strong></p><p>A large SQL query on 3 table partitions</p><ul><li>Core 1 → scans partition A</li><li>Core 2 → scans partition B</li><li>Core 3 → scans partition C</li></ul><p><em>It’s called concurrency and parallelism.</em></p><h4>3. Relationship</h4><p>Concurrent ≠ always parallel, <em>but </em>Parallel ⇒ always concurrent. Why?</p><blockquote><em>If things are running at the same instant, they are automatically make work in progress together</em></blockquote><h3>Async Programming &amp; Multithreading</h3><h4>Async Programming</h4><p>It is a way to achieve concurrency. So, async is concurrent by design. Why?</p><ul><li>Tasks overlap in a time period</li><li>While one task waits, another task runs</li></ul><p><strong>Definition :</strong> A concurrency model where tasks are not blocked while waiting for long operations such as network, database, or disk I/O. Tasks are paused and resumed when ready.</p><p><strong>Key Points :</strong></p><ul><li>Usually single-threaded or uses fewer threads (a low number of CPU cores is sufficient)</li><li>Uses an event loop mechanism (pause waiting tasks, run other tasks, resume waiting tasks when ready, repeat)</li></ul><h4>Multi Threading</h4><p>It is also a way to achieve concurrency. So, multi-threading is concurrent by design. Why?</p><ul><li>Threads interleave via time slicing</li><li>Multiple tasks make progress</li></ul><p><strong>Definition :</strong> A concurrency model where a program has multiple threads that are scheduled and run by the operating system</p><h4>Different between two</h4><p><strong>Async</strong></p><ul><li>Purpose : Run multiple tasks without blocking</li><li>Number of threads : Number of threads: Usually 1 (or a small thread pool)</li><li>Runtime : Event loop</li><li>Parallel : No (by default)</li><li>Good at waiting (database operations, network, disk I/O) and handling many user requests</li><li>Why do web servers handling 10,000 users prefer async instead of multithreading? <em>Creating 10,000 threads would cause huge memory overhead. With async, a small number of threads can efficiently switch between tasks, making it more scalable.</em></li></ul><p><strong>Multi Threading</strong></p><ul><li>Purpose : Run tasks in multiple threads</li><li>Number of threads : 2 or more</li><li>Runtime : OS Scheduler</li><li>Parallel : Yesy (If multiple cores)</li><li>Good at CPU-heavy work such as image processing (OCR, image resizing, face recognition) and heavy calculations (sorting huge arrays)</li><li>Why does video processing (e.g., Netflix encoding or streaming pipelines) prefer multithreading instead of async programming?<br><em>Using a single thread for CPU-heavy work underutilizes available CPU cores. Multithreading allows work to run in parallel across cores, significantly speeding up processing.</em></li></ul><h3>How They Work</h3><h4>1. Async (event loop, single thread) — (Concurrent, no parallel)</h4><pre>Time →<br>[Task 1 run] → (wait I/O)<br>            [Task 2 run] → (wait I/O)<br>                         [Task 1 resume]</pre><p>By using event loop, it can run multiple task eventhough use only single thread.</p><h4>2. Single-threaded (no concurrency, no parallelism)</h4><pre>Time →<br>[Task 1--------------][Task 2--------------][Task 3--------------]</pre><p>One task at a time until completed. If Task 1 does heavy computation, everything will wait. No overlap.</p><h4><strong>3. Multithreading on 1 CPU core (Concurrent, no parallel)</strong></h4><pre>Time →<br>[Task 1----][Task 2----][Resume Task 1----][Resume Task 2----]</pre><p>Each task makes <em>progress</em>, but not at the same time (start — pause — resume — evantually completes). Task overlap in time window.</p><h4>4. Multithreading on <strong>multi-core CPU (Concurrent and Parallel)</strong></h4><pre>Time →<br>Core 1: [Task 1----------------------]<br>Core 2: [Task 2----------------------]</pre><p>Threads run on different cores. Execution happens at the same instant.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3fc6a7156d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Practical Guide to Keycloak — Securing .NET Core APIs (Web MVC as Auth Client)]]></title>
            <link>https://medium.com/@mk.muhammadkhoirudin/a-practical-guide-to-keycloak-securing-net-core-apis-web-mvc-as-auth-client-351b1758c04e?source=rss-ea3f3bfa423c------2</link>
            <guid isPermaLink="false">https://medium.com/p/351b1758c04e</guid>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[keycloak]]></category>
            <dc:creator><![CDATA[Muhammad Khoirudin]]></dc:creator>
            <pubDate>Wed, 28 Jan 2026 22:08:40 GMT</pubDate>
            <atom:updated>2026-01-28T22:08:40.102Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Practical Guide to Keycloak — Securing .NET Core APIs (Web MVC as Auth Client)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*Wn4kL2dFKoAl5w1tdzwWtg.png" /></figure><p>We have done with the fundamental of keycloak in the previous article. <a href="https://medium.com/@mk.muhammadkhoirudin/a-practical-guide-to-keycloak-oauth2-and-openid-connect-for-developers-57453075b6ae"><strong>DONT FORGET TO READ IT FIRST</strong></a>. And also we have tested the authentication using postman in <a href="https://medium.com/@mk.muhammadkhoirudin/a-practical-guide-to-keycloak-securing-net-core-apis-postman-as-auth-client-1cad3244ac37?postPublishedType=initial"><strong>this article</strong></a>.</p><p>Now we will try to create Web Application using ASP NET Core MVC. We will create several features</p><ul><li>Sign in (Keycloak)</li><li>Prevent resource (page and API) from unauthorized user</li><li>Sign out</li></ul><p>Let’s get started</p><h4>API Repository : <a href="https://github.com/khoirmuhammad/Keycloak-Auth/tree/master/SImpleAPI">https://github.com/khoirmuhammad/Keycloak-Auth/tree/master/SImpleAPI</a></h4><h4>Client Repository : <a href="https://github.com/khoirmuhammad/Keycloak-Auth/tree/master/SimpleClient">https://github.com/khoirmuhammad/Keycloak-Auth/tree/master/SimpleClient</a></h4><h3>Create ASP NET Core MVC Project</h3><p>In this case we only need to know the IP Address / Domain Name</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*NHS2UvtquiwyzqiCS8SDAA.png" /></figure><h3>Keycloak Configuration (Required)</h3><p>Create Client in Keycloak : webclient</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*9uweJ-NeW4caoy8LavFaKQ.png" /></figure><p>don’t forget in <strong>“Client Scopes”</strong> mapping to particular client scopes that we want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fTAfzV49Cvp58rDg0Pepmg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VIJBD1a3KBuABNp3G4YReg.png" /></figure><ul><li>Set Redirect URIs : <a href="https://localhost:5001/signin-oidc">https://localhost:7153/signin-oidc</a></li><li>Set Logout Redirect URIs : <a href="https://localhost:5001/signout-callback-oidc">https://localhost:</a><a href="https://localhost:5001/signin-oidc">7153</a><a href="https://localhost:5001/signout-callback-oidc">/signout-callback-oidc</a></li><li>Set Web Origins : <a href="https://localhost:5001/signin-oidc">https://localhost:7153</a></li></ul><p>The domain name come from ASP NET Core MVC. But how about ?</p><ul><li>“/signin-oidc”</li><li>“/signout-callback-oidc”</li></ul><p>This is default path, when you have set the OpenID Connect configuration in NET Core MVC.</p><h3>Back To ASP NET Core MVC Project</h3><h4>1. Install NuGet Packages</h4><pre>dotnet add package Microsoft.AspNetCore.Authentication.OpenIdConnect<br>dotnet add package Microsoft.AspNetCore.Authentication.Cookies</pre><p>OpenIdConnect (Handles authentication via an external provider)</p><ul><li>This is a .NET package that lets your app use <strong>OpenID Connect (OIDC)</strong> for authentication.</li><li>We want users to <strong>log in using an external provider</strong> rather than managing usernames/passwords itself</li></ul><p>Cookies (Keeps the user logged in within your app)</p><ul><li>This package allows your app to use <strong>cookie-based authentication </strong>(After signed in store authentication data to cookies)</li></ul><h4>2. Program.cs (Add Authentication)</h4><pre>// Configures authentication services for your ASP.NET Core app.<br>builder.Services.AddAuthentication(options =&gt;<br>{<br>    //Use cookies to track authenticated users.<br>    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;<br>    <br>    //Essentially, when an unauthenticated user hits a protected page, they get redirected to the OpenID Connect provider for login. But later on we will redirect into our login buton in our web<br>    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;<br>})<br>//Configures cookie-based authentication.<br>.AddCookie(options =&gt;<br>{<br>    options.Cookie.Name = &quot;mvc-auth-cookie&quot;; //Sets the name of the cookie stored in the browser.<br>    options.Cookie.HttpOnly = true; //Makes the cookie inaccessible to JavaScript, which improves security against XSS attacks.<br>    options.Cookie.SecurePolicy = CookieSecurePolicy.Always; //Ensures the cookie is only sent over HTTPS.<br>})<br>//Configures OIDC authentication, connecting to your identity provider (Keycloak)<br>.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =&gt;<br>{<br>    options.Authority = &quot;http://localhost:8080/realms/employeeapi&quot;;<br>    options.ClientId = &quot;webclient&quot;;<br>    options.ClientSecret = &quot;A1908Qvt1Dvy6UOP3VQjVLrmSArYbCZA&quot;; //store in appSettings or other key<br>    options.ResponseType = OpenIdConnectResponseType.Code; //Recommended for server-side web apps.<br><br>    options.SaveTokens = true; //Stores the access and refresh tokens in the authentication cookie<br>    options.GetClaimsFromUserInfoEndpoint = true; //Retrieves additional user info from the provider after login (like email, name, roles)<br><br>    options.Scope.Clear();<br>    options.Scope.Add(&quot;openid&quot;); //Required for OIDC, identifies the user.<br>    options.Scope.Add(&quot;profile&quot;); //Access to basic user profile info (name, email, etc.).<br>    options.Scope.Add(&quot;employeeapi_api.all&quot;); //A custom scope to allow access to your own API<br><br>    options.RequireHttpsMetadata = false; // true in production<br>});</pre><p>Explanation</p><pre>options.Authority = &quot;http://localhost:8080/realms/employeeapi&quot;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*6CjuMpO1rKKZHVhKq1Prmw.png" /></figure><p>Then you will get the openid-configuration endpoint. Once you retrieve the response, see the issuer value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*4Ijz5p9mCzTzvkzYSduhDQ.png" /></figure><pre>options.ClientId = &quot;webclient&quot;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*6MhEGgQprEc4yHc1aHlJsA.png" /></figure><pre>options.ClientSecret = &quot;A1908Qvt1Dvy6UOP3VQjVLrmSArYbCZA&quot;; //store in appSettings or other key</pre><p>Go to Credentials tab</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9EOgTbgq8fUGHD-Nm-Vx0g.png" /></figure><h4>3. Program.cs (Middleware Auth)</h4><pre>//Try to identify the user.<br>//Without this : Cookies or tokens are never read, [Authorize] will always fail<br>app.UseAuthentication();<br><br>//Enforces authorization rules<br>//Checks [Authorize] attributes<br>app.UseAuthorization();</pre><h4>4. Program.cs (HTTP Call Dependency Injection)</h4><pre>builder.Services.AddHttpClient();</pre><p>Later on, we will call the Simple API that secured by keycloak (test if our access token is OK)</p><h4>5. Create Account Controller</h4><pre>public class AccountController : Controller<br>{<br>    //returnUrl = where the user should go after successful login (home page itself)<br>    public IActionResult Login(string returnUrl = &quot;/&quot;)<br>    {<br>        //The user is not authenticated, start an authentication challenge.<br>        return Challenge(new AuthenticationProperties<br>        {<br>            RedirectUri = returnUrl<br>        }, OpenIdConnectDefaults.AuthenticationScheme); //Redirect to OIDC provider<br>    }<br><br>    public IActionResult Logout()<br>    {<br>        //Remove authentication and end the user’s session<br>        return SignOut(<br>            CookieAuthenticationDefaults.AuthenticationScheme,<br>            OpenIdConnectDefaults.AuthenticationScheme);<br>    }<br>}</pre><h4>6. Create Filter &amp; Implement to Protected Page</h4><p>In protected page we will use this filter to prevent unauthorized user access it.</p><pre>public class RedirectHomeIfNotAuthenticatedFilter : IAuthorizationFilter<br>{<br>    public void OnAuthorization(AuthorizationFilterContext context)<br>    {<br>        if (!context.HttpContext.User.Identity?.IsAuthenticated ?? true)<br>        {<br>            context.Result = new RedirectToActionResult(&quot;Index&quot;, &quot;Home&quot;, null);<br>        }<br>    }<br>}</pre><p>Register to DI</p><pre>builder.Services.AddScoped&lt;RedirectHomeIfNotAuthenticatedFilter&gt;();<br><br>var app = builder.Build();</pre><p>Go to HomeController.cs</p><pre>[ServiceFilter(typeof(RedirectHomeIfNotAuthenticatedFilter))]<br>public IActionResult Privacy()<br>{<br>    return View();<br>}</pre><h4>7. Modify CSHtml</h4><p>Home/Index.cshtml</p><pre>@{<br>    ViewData[&quot;Title&quot;] = &quot;Home Page&quot;;<br>}<br><br>&lt;div class=&quot;text-center&quot;&gt;<br>    &lt;h1 class=&quot;display-4&quot;&gt;Welcome&lt;/h1&gt;<br>    @if (User.Identity?.IsAuthenticated ?? false)<br>    {<br>            &lt;form method=&quot;post&quot; action=&quot;/Account/Logout&quot; style=&quot;display:inline&quot;&gt;<br>                &lt;button type=&quot;submit&quot; class=&quot;btn btn-danger&quot;&gt;Logout&lt;/button&gt;<br>            &lt;/form&gt;<br>    }<br>    else<br>    {<br>            &lt;a class=&quot;btn btn-primary&quot; href=&quot;/Account/Login&quot;&gt;Login&lt;/a&gt;<br>    }<br>    &lt;p&gt;Learn about &lt;a href=&quot;https://learn.microsoft.com/aspnet/core&quot;&gt;building Web apps with ASP.NET Core&lt;/a&gt;.&lt;/p&gt;<br>&lt;/div&gt;</pre><p>Home/Privacy.cshtml</p><pre>@{<br>    ViewData[&quot;Title&quot;] = &quot;Privacy Policy&quot;;<br>}<br>&lt;h1&gt;@ViewData[&quot;Title&quot;]&lt;/h1&gt;<br><br>&lt;p&gt;Use this page to detail your site&#39;s privacy policy.&lt;/p&gt;<br>&lt;a href=&quot;/Account/Logout&quot;&gt;Logout&lt;/a&gt;</pre><h4>8. Create APIController</h4><p>In SImpleAPI Project we have and API resource</p><pre>public class ApiController : Controller<br>{<br>    private readonly IHttpClientFactory _httpClientFactory;<br><br>    public ApiController(IHttpClientFactory httpClientFactory)<br>    {<br>        _httpClientFactory = httpClientFactory;<br>    }<br><br>    public async Task&lt;IActionResult&gt; GetEmployee(int id)<br>    {<br>        var accessToken = await HttpContext.GetTokenAsync(&quot;access_token&quot;);<br><br>        var client = _httpClientFactory.CreateClient();<br>        client.DefaultRequestHeaders.Authorization =<br>            new AuthenticationHeaderValue(&quot;Bearer&quot;, accessToken);<br><br>        var response = await client.GetAsync($&quot;https://localhost:7250/employees/{id}&quot;);<br><br>        if (!response.IsSuccessStatusCode)<br>        {<br>            return Unauthorized();<br>        }<br><br>        var content = await response.Content.ReadAsStringAsync();<br>        return Content(content, &quot;application/json&quot;);<br>    }<br>}</pre><h3>Testing</h3><ul><li>Don’t forget to run docker : ensure keycloak provider has run</li><li>Don’t forget to run the <a href="https://github.com/khoirmuhammad/Keycloak-Auth/tree/master/SImpleAPI">Simple API</a></li></ul><h4>Before Sign in</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4W0lTihwhuDiiyfBuAgGbg.png" /></figure><p>After Sign in</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*8YCYgGlqhX3khaQ3EZQYNg.png" /></figure><p>Home Page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_AUoPiB6zI-kRkvVxTnQuw.png" /></figure><p>Privacy Page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K_BHt3XwgSzXZkNOpmFTbg.png" /></figure><p>API Data Response</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*PzYRhf5XAIz6SQVMn1qlyw.png" /></figure><h3>Conclusion</h3><p>Finally, we demonstrated how to call a secured API from an MVC controller using an access token and render the data in a Razor view, along with a clean login/logout experience in the UI.</p><p>With this foundation, you now have a solid mental model of <strong>how authentication and authorization work end-to-end</strong> in a real .NET application using Keycloak. From here, you can confidently extend the solution with role-based access, finer-grained scopes, or more advanced security patterns.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=351b1758c04e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>