<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ben Mukebo on Medium]]></title>
        <description><![CDATA[Stories by Ben Mukebo on Medium]]></description>
        <link>https://medium.com/@benmukebo?source=rss-cd794122db0a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TNjQdafaOn4lEL_Xr8tnUg.png</url>
            <title>Stories by Ben Mukebo on Medium</title>
            <link>https://medium.com/@benmukebo?source=rss-cd794122db0a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 17:25:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@benmukebo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[ How I Built a Production-Ready RBAC System in React with CASL]]></title>
            <link>https://benmukebo.medium.com/how-i-built-a-production-ready-rbac-system-in-react-with-casl-fd5b16354e3d?source=rss-cd794122db0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd5b16354e3d</guid>
            <category><![CDATA[autorization]]></category>
            <category><![CDATA[rbac]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[permission]]></category>
            <category><![CDATA[rbac-access-control]]></category>
            <dc:creator><![CDATA[Ben Mukebo]]></dc:creator>
            <pubDate>Thu, 19 Feb 2026 08:34:41 GMT</pubDate>
            <atom:updated>2026-02-19T08:34:41.524Z</atom:updated>
            <content:encoded><![CDATA[<p>Most React apps start with simple auth:<br>👉 <strong>Logged in or not.</strong></p><p>But real-world apps need <strong>granular permissions. </strong>Who can create, read, update, or delete what?</p><p>Here’s the architecture I used with <strong>CASL</strong> (@casl/ability + @casl/react) to enforce permissions at every level of the UI.</p><h3>🧠 The Permission Model</h3><p>The foundation is a simple <strong>Action × Subject</strong> matrix. Every permission is a combination of <em>what the user can do</em> (action) and <em>what they can do it to</em> (subject):</p><pre>// permissions.dto.ts<br>enum Action { Create, Read, Update, Delete}<br>enum Subject { Home, Posts, Comments, Users}</pre><p>Every permission = <strong>what</strong> a user can do × <strong>where</strong> they can do it.</p><p>A user { subject: &quot;posts&quot;, actions: { read: true, create: true, delete: false, update: false}] } can view and create posts, but can&#39;t update or delete them.</p><h3>Step 1: Install Dependencies</h3><pre>npm install @casl/ability @casl/react</pre><ul><li><strong>@casl/ability</strong> =&gt; <em>The core CASL library for defining and checking permissions</em></li><li><strong>@casl/react</strong> =&gt; <em>React bindings that provide the </em><em>&lt;Can&gt; component and </em><em>createContextualCan utility</em></li></ul><h3>Step 2: Define the CASL Ability Type</h3><p>CASL is a powerful isomorphic authorization library. We start by defining our ability type:</p><pre>// casl/ability.ts<br><br>import { createMongoAbility, type MongoAbility } from &quot;@casl/ability&quot;;<br><br>export type AppAbility = MongoAbility&lt;[ActionEnum, SubjectEnum]&gt;;<br><br>export function createEmptyAbility(): AppAbility {<br>  return createMongoAbility&lt;AppAbility&gt;([]);<br>}</pre><p>TypeScript generics ensure that every ability.can() call uses valid action/subject pairs. You&#39;ll get compile-time errors if you pass an invalid combination.</p><p>The createEmptyAbility() function returns an ability with zero permissions. It&#39;s used as the default state before the user is authenticated.</p><h3>Step 3: Build Ability from API Response</h3><p>Most backends expose an endpoint that returns the current user&#39;s profile and permissions. Here&#39;s how to take that response and build a CASL ability:</p><pre>// casl/permissions.utils.ts<br><br>import { AbilityBuilder, createMongoAbility } from &quot;@casl/ability&quot;;<br>import type { AppAbility } from &quot;./ability&quot;;<br>import { createEmptyAbility } from &quot;./ability&quot;;<br>export function buildAbilityFromPermissions(permissions: PermissionDTO[]): AppAbility {<br>  if (!Array.isArray(permissions) || permissions.length === 0) {<br>    return createEmptyAbility();<br>  }<br>  try {<br>    const { can, build } = new AbilityBuilder&lt;AppAbility&gt;(createMongoAbility);<br>    permissions.forEach((permission) =&gt; {<br>      permission.actions<br>        .filter((action) =&gt; action.enabled)<br>        .forEach((action) =&gt; {<br>          can(action.name, permission.subject);<br>        });<br>    });<br>    return build();<br>  } catch {<br>    return createEmptyAbility();<br>  }<br>}</pre><p>The /me endpoint returns something like:</p><pre>{<br>  &quot;id&quot;: &quot;usr_123&quot;,<br>  &quot;name&quot;: &quot;Jane Doe&quot;,<br>  &quot;email&quot;: &quot;jane@example.com&quot;,<br>  &quot;permissions&quot;: [<br>    {<br>      &quot;subject&quot;: &quot;posts&quot;,<br>      &quot;actions&quot;: [<br>        { &quot;name&quot;: &quot;read&quot;, &quot;enabled&quot;: true },<br>        { &quot;name&quot;: &quot;create&quot;, &quot;enabled&quot;: true },<br>        { &quot;name&quot;: &quot;update&quot;, &quot;enabled&quot;: false },<br>        { &quot;name&quot;: &quot;delete&quot;, &quot;enabled&quot;: false }<br>      ]<br>    },<br>    {<br>      &quot;subject&quot;: &quot;comments&quot;,<br>      &quot;actions&quot;: [<br>        { &quot;name&quot;: &quot;read&quot;, &quot;enabled&quot;: true },<br>        { &quot;name&quot;: &quot;create&quot;, &quot;enabled&quot;: true }<br>      ]<br>    },<br>    {<br>      &quot;subject&quot;: &quot;admin&quot;,<br>      &quot;actions&quot;: [<br>        { &quot;name&quot;: &quot;general_access&quot;, &quot;enabled&quot;: true }<br>      ]<br>    }<br>  ]<br>}</pre><p><strong>Key design choice</strong>: Every failure path returns createEmptyAbility() — no permissions. Fail closed, never open.</p><h3>Step 4: Provide Ability via React Context</h3><p>The ability needs to be accessible throughout the entire component tree. We fetch the user’s permissions from the /me endpoint after authentication, then build the CASL ability from the response:</p><pre>// casl/AbilityContext.tsx<br><br>import { createContext, useContext, useMemo, type FC, type ReactNode } from &quot;react&quot;;<br>import { createContextualCan } from &quot;@casl/react&quot;;<br>import { useQuery } from &quot;@tanstack/react-query&quot;;<br>import type { AppAbility } from &quot;./ability&quot;;<br>import { createEmptyAbility } from &quot;./ability&quot;;<br>import { buildAbilityFromPermissions } from &quot;./permissions.utils&quot;;<br>import { useAuth } from &quot;@/context/AuthContext&quot;;<br><br>const AbilityContext = createContext&lt;AppAbility&gt;(createEmptyAbility());<br>export const AbilityProvider: FC&lt;{ children: ReactNode }&gt; = ({ children }) =&gt; {<br>  const { isAuthenticated } = useAuth();<br>  // Fetch current user&#39;s permissions from /me endpoint<br>  const { data: currentUser } = useQuery({<br>    queryKey: [&quot;me&quot;],<br>    queryFn: () =&gt; httpClient.get(&quot;/me&quot;),<br>    enabled: isAuthenticated,<br>  });<br>  const ability = useMemo(() =&gt; {<br>    if (!isAuthenticated || !currentUser?.permissions) {<br>      return createEmptyAbility();<br>    }<br>    return buildAbilityFromPermissions(currentUser.permissions);<br>  }, [isAuthenticated, currentUser]);<br>  return (<br>    &lt;AbilityContext.Provider value={ability}&gt;<br>      {children}<br>    &lt;/AbilityContext.Provider&gt;<br>  );<br>};<br>export function useAbility(): AppAbility {<br>  return useContext(AbilityContext);<br>}<br>// Declarative permission component from @casl/react<br>export const Can = createContextualCan(AbilityContext.Consumer);<br></pre><pre><strong>Provider ordering matters.</strong> AbilityProvider must be nested <em>inside</em> AuthProvider because it depends on auth state, and <em>inside</em> QueryClientProvider because it uses React Query:</pre><pre>// App.tsx<br><br>&lt;QueryClientProvider client={queryClient}&gt;<br>  &lt;AuthProvider&gt;<br>    &lt;AbilityProvider&gt;<br>      &lt;RouterProvider /&gt;<br>    &lt;/AbilityProvider&gt;<br>  &lt;/AuthProvider&gt;<br>&lt;/QueryClientProvider&gt;</pre><h3>Step 5: Route-Level Guards</h3><p>The first layer of protection — prevent users from even reaching routes they don’t have access to:</p><pre>// casl/route-permissions.ts<br><br>const routePermissionMap: Array&lt;{ pattern: RegExp; subject: SubjectEnum }&gt; = [<br>  { pattern: /^\/posts/, subject: SubjectEnum.Posts },<br>  { pattern: /^\/comments/, subject: SubjectEnum.Comments },<br>  { pattern: /^\/categories/, subject: SubjectEnum.Categories },<br>  { pattern: /^\/users/, subject: SubjectEnum.Users },<br>  { pattern: /^\/settings/, subject: SubjectEnum.Settings },<br>  { pattern: /^\/admin/, subject: SubjectEnum.Admin },<br>  // Home intentionally excluded — it&#39;s the safe fallback<br>];<br><br>export function getRequiredPermission(pathname: string): SubjectEnum | null {<br>  for (const { pattern, subject } of routePermissionMap) {<br>    if (pattern.test(pathname)) return subject;<br>  }<br>  return null; // No permission required (e.g., home page)<br>}</pre><p>Then, in your route guard component:</p><pre>// components/ProtectedRoute.tsx<br><br>export const ProtectedRoute: FC&lt;{ children: ReactNode }&gt; = ({ children }) =&gt; {<br>  const { isAuthenticated } = useAuth();<br>  const location = useLocation();<br>  const ability = useAbility();<br>  if (!isAuthenticated) {<br>    return &lt;Navigate to=&quot;/login&quot; state={{ from: location }} replace /&gt;;<br>  }<br>  const requiredPermission = getRequiredPermission(location.pathname);<br>  if (requiredPermission) {<br>    const hasAccess =<br>      ability.can(ActionEnum.Read, requiredPermission) ||<br>      ability.can(ActionEnum.General_Access, requiredPermission);<br>    if (!hasAccess) {<br>      return &lt;Navigate to=&quot;/403&quot; replace /&gt;;<br>    }<br>  }<br>  return &lt;&gt;{children}&lt;/&gt;;<br>};</pre><p>Notice the <strong>dual check</strong>: Read OR General_Access. Admin sections use General_Access instead of standard CRUD actions. Without this, admin routes would be blocked even for authorized admin users.</p><p>Also notice that the Home page is intentionally excluded from the route map. It serves as the safe landing page — if we required permissions for it too, users with limited roles could end up in redirect loops.</p><h3>Step 6: Sidebar Filtering</h3><p>Users shouldn’t see navigation items for pages they can’t access:</p><pre>// casl/sidebar-permissions.ts<br><br>const sidebarPermissionMap: Record&lt;string, SubjectEnum | SubjectEnum[]&gt; = {<br>  home: SubjectEnum.Home,<br>  // Parent visible if user has ANY child permission<br>  posts: [SubjectEnum.Posts, SubjectEnum.Comments, SubjectEnum.Categories],<br>  // Children<br>  &quot;all-posts&quot;: SubjectEnum.Posts,<br>  comments: SubjectEnum.Comments,<br>  categories: SubjectEnum.Categories,<br>  users: SubjectEnum.Users,<br>  settings: SubjectEnum.Settings,<br>  // Admin items<br>  admin: SubjectEnum.Admin,<br>};<br>export function shouldShowItem(<br>  itemId: string,<br>  canRead: (subject: SubjectEnum) =&gt; boolean<br>): boolean {<br>  const permission = sidebarPermissionMap[itemId];<br>  // Items not in the map (like &quot;sign-out&quot;) are always visible<br>  if (permission === undefined) return true;<br>  // Array = show if user has ANY of the permissions<br>  if (Array.isArray(permission)) return permission.some(canRead);<br>  return canRead(permission);<br>}<br>export function filterMenuItems&lt;T extends { id: string; children?: T[] }&gt;(<br>  items: T[],<br>  canRead: (subject: SubjectEnum) =&gt; boolean<br>): T[] {<br>  return items<br>    .filter((item) =&gt; shouldShowItem(item.id, canRead))<br>    .map((item) =&gt; {<br>      if (item.children) {<br>        const filtered = item.children.filter((child) =&gt;<br>          shouldShowItem(child.id, canRead)<br>        );<br>        if (filtered.length === 0) return null;<br>        return { ...item, children: filtered };<br>      }<br>      return item;<br>    })<br>    .filter((item): item is T =&gt; item !== null);<br>}</pre><p>The <strong>array pattern</strong> is powerful for parent menu items. A “Posts” parent should be visible if the user has access to <em>any</em> of its children (All Posts, Comments, or Categories). But if all children are filtered out, the parent disappears too.</p><p>In the sidebar component:</p><pre>const Sidebar: FC = () =&gt; {<br>  const ability = useAbility();<br>  const canRead = useCallback(<br>    (subject: SubjectEnum) =&gt;<br>      ability.can(ActionEnum.Read, subject) ||<br>      ability.can(ActionEnum.General_Access, subject),<br>    [ability]<br>  );<br>  const visibleMenuItems = useMemo(<br>    () =&gt; filterMenuItems(menuItems, canRead),<br>    [canRead]<br>  );<br>  return &lt;nav&gt;{visibleMenuItems.map(renderMenuItem)}&lt;/nav&gt;;<br>};</pre><h3>Step 7: Element-Level Permissions</h3><p>The most granular level showing/hiding or enabling/disabling individual buttons and actions:</p><h3>Declarative: &lt;Can&gt; component</h3><p>Use this to hide elements completely:</p><pre>&lt;Can I={ActionEnum.Create} a={SubjectEnum.Posts}&gt;<br>  &lt;button onClick={handleCreatePost}&gt;New Post&lt;/button&gt;<br>&lt;/Can&gt;</pre><p>The “New Post” button only renders if the user has create permission on posts. Users without it won&#39;t even know the button exists.</p><h3>Programmatic: useAbility() hook</h3><p>Use this when you want to <em>disable</em> rather than hide, or when the permission logic is more complex:</p><pre>const ability = useAbility();<br>const canEdit = ability.can(ActionEnum.Update, SubjectEnum.Posts);<br><br>&lt;button<br>  disabled={!canEdit}<br>  title={canEdit ? &quot;Edit post&quot; : &quot;Permission denied&quot;}<br>  onClick={() =&gt; handleEdit(post)}<br>&gt;<br>  Edit<br>&lt;/button&gt;</pre><p><strong>UX tip</strong>: Prefer disabling over hiding for actions users know exist. Hiding a “New Post” button is fine for users who can’t create and don’t need to know the button exists. But disabling an “Edit” button in a list is better; it tells the user the feature exists, but they need elevated permissions.</p><h3>The Full Permission Flow</h3><pre>Backend assigns permissions to role<br>            ↓<br>/me endpoint returns user permissions<br>            ↓<br>buildAbilityFromPermissions() → CASL rules<br>            ↓<br>AbilityProvider stores ability in React Context<br>            ↓<br>┌───────────────────────────────────────────┐<br>│                                           │<br>│  Route Level    → ProtectedRoute          │<br>│                   (redirect to /403)      │<br>│                                           │<br>│  Navigation     → filterMenuItems()       │<br>│                   (hide sidebar items)    │<br>│                                           │<br>│  Element Level  → &lt;Can&gt; or useAbility()   │<br>│                   (hide/disable buttons)  │<br>│                                           │<br>└───────────────────────────────────────────┘</pre><h3>🎯 Key Takeaways</h3><ol><li><strong>Fail closed.</strong> Every error path returns createEmptyAbility() zero permissions. Never default to granting access.</li><li><strong>Three layers of enforcement.</strong> Route guards, sidebar filtering, and element-level controls. Each catches what the layer above might miss.</li><li><strong>Keep permission data in constants, not JSX.</strong> Permission maps (sidebarPermissionMap, routePermissionMap) are easy to audit and update. The components just consume them.</li><li><strong>Account for non-CRUD actions.</strong> Not everything is Create/Read/Update/Delete. The General_Access action handles sections that are either fully accessible or not at all.</li><li><strong>TypeScript is your friend.</strong> MongoAbility&lt;[ActionEnum, SubjectEnum]&gt; catches invalid action/subject combinations at compile time, not runtime.</li></ol><p>🎥 Full walkthrough here:<br><a href="https://www.youtube.com/watch?v=gL3BJ8_5Jz8">https://www.youtube.com/watch?v=gL3BJ8_5Jz8</a></p><p>This architecture has been running in production and handles everything from simple “can this user see the home page” checks to complex multi-action permission matrices, all with minimal boilerplate and strong type safety.</p><p>If you’re building a React app that needs more than basic auth, I’d highly recommend CASL. The learning curve is small, and the payoff in maintainability is huge.</p><p><em>What patterns are you using for permissions in your React apps? I’d love to hear different approaches in the comments.</em></p><p>#react #typescript #casl #rbac #frontend #webdevelopment #authorization</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd5b16354e3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ How to Add Offline Mode to a Next.js 14+ App with PWA]]></title>
            <link>https://benmukebo.medium.com/build-an-offline-ready-pwa-with-next-js-14-using-ducanh2912-next-pwa-17851765fa6b?source=rss-cd794122db0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/17851765fa6b</guid>
            <dc:creator><![CDATA[Ben Mukebo]]></dc:creator>
            <pubDate>Fri, 01 Aug 2025 14:32:10 GMT</pubDate>
            <atom:updated>2025-08-01T15:43:38.801Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern web users expect <strong>apps that work offline</strong>, and with <strong>Next.js 14+</strong> and <strong>Progressive Web Apps (PWA)</strong>, that’s now achievable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/0*1oGNRAL5Q74h_HtF.jpg" /></figure><p>In this article, I’ll walk you step by step through <strong>turning a Next.js 14+ App Router project into an offline-ready PWA</strong> using @ducanh2912/next-pwa.</p><h3>1. Why “@ducanh2912/next-pwa”?</h3><p>@ducanh2912/next-pwa is a package that allows you to create a progressive web app with Next.js. When researching offline support for Next.js, I found two popular libraries:</p><ol><li><strong>next-pwa</strong></li><li><strong>@ducanh2912/next-pwa</strong></li></ol><p>Here’s why I went with the second option:</p><ul><li><strong>next-pwa</strong> hasn’t been updated in ~3 years.</li><li><strong>@ducanh2912/next-pwa</strong> is actively maintained (last update less than a year ago).</li><li>It has built-in support for <strong>Next.js 13+ App Router and Next.js 14</strong>.</li><li>Features like: <br> - cacheOnFrontEndNav → caches pages visited during client-side navigation: <br> - aggressiveFrontEndNavCaching → faster page transitions, offline navigation<br>- reloadOnOnline → updates automatically when you reconnect</li></ul><blockquote>Now, how to configure it?</blockquote><h3>2. Install the Package</h3><p>In your Next.js project:</p><pre>npm install @ducanh2912/next-pwa</pre><p>Or using Yarn:</p><pre>yarn add @ducanh2912/next-pwa</pre><h3>3. Configure next.config.js</h3><p>Here’s a minimal but <strong>offline-ready</strong> setup:</p><pre>// next.config.js<br>const withPWA = require(&quot;@ducanh2912/next-pwa&quot;).default({<br>  dest: &quot;public&quot;,<br>  register: true,<br>  skipWaiting: true,<br>  disable: process.env.NODE_ENV === &#39;development&#39;, // Disable PWA in dev<br>  cacheOnFrontEndNav: true,<br>  aggressiveFrontEndNavCaching: true,<br>  reloadOnOnline: true,<br>  swcMinify: true,<br>  workboxOptions: {<br>    disableDevLogs: true,<br>  },<br>  // Example runtime caching for an API endpoint<br>  runtimeCaching: [<br>    {<br>      urlPattern: /^https:\/\/api\.example\.com\/data.*/i,<br>      handler: &#39;NetworkFirst&#39;,<br>      options: {<br>        cacheName: &#39;example-api-cache&#39;,<br>        expiration: {<br>          maxEntries: 100,<br>          maxAgeSeconds: 60 * 60 * 24 * 7, // Cache for 1 week<br>        },<br>        cacheableResponse: {<br>          statuses: [0, 200],<br>        },<br>      },<br>    },<br>    {<br>      urlPattern: /.*/i,<br>      handler: &#39;NetworkOnly&#39;,<br>      options: {<br>        cacheableResponse: {<br>          statuses: [0, 200],<br>        },<br>      },<br>    },<br>  ],<br>});<br><br>module.exports = withPWA({});</pre><h4>Key Notes About This Config</h4><ul><li><strong>dest: &quot;public&quot;</strong> → Service Worker and Workbox files will be generated here after the build (sw.js, workbox-*.js)</li><li><strong>register: true</strong> → Automatically registers the Service Worker on first visit</li><li><strong>skipWaiting: true</strong> → Activates the new Service Worker immediately on update</li><li><strong>cacheOnFrontEndNav &amp; </strong><strong>aggressiveFrontEndNavCaching</strong> → Makes client-side navigation <strong>load instantly offline</strong></li><li><strong>runtimeCaching</strong> → Defines caching strategies for API endpoints or images</li><li><strong>NetworkFirst</strong> → Tries fetching fresh data first, then falls back to cache if offline</li><li><strong>NetworkOnly</strong> → For routes you <strong>never want cached</strong></li><li><strong>reloadOnOnline</strong> — Reload the app when it has gone back online.</li><li><strong>fallbacks</strong> → Configure routes to be precached so that they can be used as a fallback when fetching a resource from both the cache and the network fails. To enable this behavior for pages, simply create pages/_offline.tsx or app/~offline/page.tsxfile to app/.</li></ul><h3>4. Add a web application manifest.json for the PWA</h3><p>Update app/manifest.json (App Router) or public/manifest.json (Pages Router) With the following content:</p><pre>{<br>  &quot;id&quot;: &quot;/&quot;,<br>  &quot;name&quot;: &quot;My Offline App&quot;,<br>  &quot;short_name&quot;: &quot;OfflineApp&quot;,<br>  &quot;description&quot;: &quot;A sample Next.js 14+ PWA with offline support&quot;,<br>  &quot;start_url&quot;: &quot;/&quot;,<br>  &quot;display&quot;: &quot;standalone&quot;,<br>  &quot;background_color&quot;: &quot;#ffffff&quot;,<br>  &quot;scope&quot;: &quot;/&quot;,<br>  &quot;theme_color&quot;: &quot;#0C27BE&quot;,<br>  &quot;orientation&quot;: &quot;portrait&quot;<br>  &quot;icons&quot;: [<br>    {<br>      &quot;src&quot;: &quot;/icons/icon-16x16.png&quot;,<br>      &quot;sizes&quot;: &quot;16x16&quot;,<br>      &quot;type&quot;: &quot;image/png&quot;<br>    },<br>    {<br>      &quot;src&quot;: &quot;/icons/icon-32x32.png&quot;,<br>      &quot;sizes&quot;: &quot;32x32&quot;,<br>      &quot;type&quot;: &quot;image/png&quot;<br>    },<br>    {<br>      &quot;src&quot;: &quot;/icons/icon-192x192.png&quot;,<br>      &quot;sizes&quot;: &quot;192x192&quot;,<br>      &quot;type&quot;: &quot;image/png&quot;<br>    },<br>    {<br>      &quot;src&quot;: &quot;/icons/icon-512x512.png&quot;,<br>      &quot;sizes&quot;: &quot;512x512&quot;,<br>      &quot;type&quot;: &quot;image/png&quot;<br>    },<br>    {<br>      &quot;src&quot;: &quot;/icons/maskable.png&quot;,<br>      &quot;sizes&quot;: &quot;192x192&quot;,<br>      &quot;type&quot;: &quot;image/png&quot;,<br>      &quot;purpose&quot;: &quot;maskable&quot;<br>    }<br>  ]<br>}</pre><h4>Don’t Forget App Icons</h4><p>Inside public/icons folder, add:</p><ul><li>icon-16x16.png</li><li>icon-32x32.png</li><li>icon-192x192.png</li><li>icon-512x512.png</li><li>maskable.png (optional but recommended)</li></ul><blockquote>💡 These icons are required for <strong>Add to Home Screen</strong> on mobile devices, Without icons, your PWA <strong>cannot be installed</strong> on mobile devices.</blockquote><h3>5. Config metadata Layout</h3><p>Add the following to your app/layout.tsx or pages/_app.tsx:</p><pre>export const metadata: Metadata = {<br>  title: &#39;My Offline App&#39;,<br>  description: &#39;A sample Next.js 14 PWA&#39;,<br>  manifest: &#39;/manifest.json&#39;, // link the PWA manifest<br>  ...<br>};</pre><h3>6. Build and Verify Your PWA Offline Setup</h3><ol><li><strong>Build your app</strong>:</li></ol><pre>npm run build &amp;&amp; npm start</pre><ol><li><strong>Check the </strong><strong>/public folder</strong> after build:</li></ol><p>You should see these files added automatically:</p><ul><li>sw.js</li><li>workbox-*.js</li><li>worker-*.js</li></ul><p>These confirm your <strong>service worker is ready</strong>.</p><ol><li><strong>Verify in Chrome DevTools</strong>:</li></ol><ul><li>Open <strong>Application → Service Workers</strong></li><li>You should see <strong>Service Worker: activated and running</strong></li></ul><ol><li><strong>Test offline mode</strong>:</li></ol><ul><li>Go to DevTools<strong> → </strong>Network<strong> → Offline</strong></li><li>Reload your app → Pages and assets should load offline.</li></ul><h3>7. Tips for a Better Offline UX</h3><ul><li><strong>First visit must be online</strong> to cache assets.</li><li><strong>Add runtime caching</strong> for API responses or images you need offline.</li><li><strong>Consider an offline banner</strong> to notify users when they lose connectivity.</li><li><strong>Check Cache Storage</strong> in DevTools to confirm caching behavior. (DevTools → Application → Cache Storage)</li></ul><h3>🎉 Final Thoughts</h3><p>By using <strong>@ducanh2912/next-pwa</strong> With <strong>Next.js 14+</strong>, we can:</p><ul><li>Make the app <strong>offline-ready</strong></li><li>Automatically <strong>cache assets and pages</strong></li><li>Build a <strong>PWA ready for Add to Home Screen</strong></li></ul><p>By using <strong>@ducanh2912/next-pwa</strong> with <strong>Next.js 14+</strong>, you can:</p><ul><li>Deliver an <strong>offline-first web app</strong></li><li>Allow users to <strong>install it like a native app</strong></li><li>Automatically <strong>cache visited pages and static assets</strong></li></ul><p>Once you see <strong>sw.js</strong> and <strong>Workbox files</strong> in your /public folder, your Next.js app is officially <strong>PWA-ready and works offline</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*u-w2nomjQzza781n.png" /></figure><p><em>If this article has been helpful, please hit the 👏 button and share it with others! 🚀 to show how much you liked it! 😄</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17851765fa6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Boost Your React App’s Performance with Vite, Lazy Loading, and Code Splitting]]></title>
            <link>https://benmukebo.medium.com/boost-your-react-apps-performance-with-vite-lazy-loading-and-code-splitting-2fd093128682?source=rss-cd794122db0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fd093128682</guid>
            <dc:creator><![CDATA[Ben Mukebo]]></dc:creator>
            <pubDate>Mon, 26 May 2025 08:21:19 GMT</pubDate>
            <atom:updated>2025-05-26T08:41:49.945Z</atom:updated>
            <content:encoded><![CDATA[<p>Performance is everything. In today’s web, where users expect instant feedback and snappy interfaces, optimizing load time in your React applications is no longer optional — it’s essential.</p><p>This article walks you through building a <strong>modern, high-performance React app</strong> using:</p><ul><li>⚡ <strong>Vite</strong> (for ultra-fast development and builds),</li><li>🧭 <strong>React Router</strong> (with nested routing),</li><li>🔁 <strong>Code splitting </strong>(to reduce initial bundle size),</li><li>💤 <strong>Lazy loading</strong> (to load components and pages only when needed)</li><li>🧱 Clean project architecture with React Router and Context API</li></ul><p>We’ll also explore how to structure your project cleanly while taking full advantage of these features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_1vdCBzESgz8nuWR.jpg" /></figure><h3>1. Code Splitting</h3><p><strong>Code splitting</strong> is a performance optimization technique (build-time technique) that breaks your JavaScript bundle into smaller chunks. This allows the browser to download only what’s needed instead of loading everything upfront. This way, only the code needed for the current view gets loaded.<br>=&gt; By default, bundlers like Webpack or Vite package your <strong>entire app into a single JavaScript file</strong>. As your app grows, this leads to:</p><ul><li>Slower initial load times</li><li>Longer time to interactivity</li><li>Wasted bandwidth for unused code</li></ul><p><strong><em>The Solution:<br></em></strong>Code splitting solves this by:</p><ul><li>Loading only the code required for the current page</li><li>Deferring the rest until it’s needed</li></ul><p><strong><em>🛠️ How to Use It</em></strong></p><p>Use the import() Syntax to dynamically import modules:</p><pre>// This creates a separate chunk<br>import(&#39;./components/HeavyComponent&#39;);</pre><p>Bundlers like <strong>Vite</strong> or <strong>Webpack</strong> automatically split this into a separate file (chunk) that’s loaded only when requested.</p><h3>2. Lazy Loading</h3><p><strong>Lazy loading</strong> delays loading components until they are actually needed, typically when they’re rendered for the first time.</p><p>Even if you split your code, React might still <strong>eagerly import chunks</strong> before they’re needed. This causes:</p><ul><li>Unnecessary network usage</li><li>Higher memory consumption</li><li>Slower initial renders, especially on mobile devices</li></ul><p><strong><em>The Solution<br></em></strong>Lazy loading fixes this by:</p><ul><li>Loading components only when rendered</li><li>Reducing memory and bandwidth usage</li><li>Improving performance on initial page load</li></ul><p><strong><em>🛠️ How to Use It</em></strong></p><p>React provides built-in support for lazy loading:</p><pre>import React, { Suspense } from &#39;react&#39;;<br><br>const Chart = React.lazy(() =&gt; import(&#39;./Chart&#39;));<br><br>&lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>  &lt;Chart /&gt;<br>&lt;/Suspense&gt;</pre><p><strong><em>Keep in Mind</em></strong></p><ol><li>The Lazy-loaded components you import <strong>must be a default export</strong></li></ol><pre>// Correct<br>export default function HeavyComponent() { ... }<br><br>// Not supported directly by React.lazy<br>export function HeavyComponent() { ... }</pre><ul><li>React’s lazy() Works only with modules that export a component as the default.</li></ul><pre> <br>const HeavyComponent = React.lazy(() =&gt; import(‘./HeavyComponent’));</pre><p>2. Always wrap lazy-loaded components with&lt;Suspense&gt;, or React will throw a runtime error (when the component tries to load). This ensures your app doesn’t load unused components on the initial page load.</p><pre>&lt;Suspense fallback={&lt;Loader /&gt;}&gt;<br>  &lt;MyLazyComponent /&gt;<br>&lt;/Suspense&gt;</pre><h3>3. Lazy Loading vs Code Splitting.</h3><ul><li><strong>Code splitting</strong> happens at <strong>build time</strong>. It tells the bundler to split your code into separate files using dynamic import().</li><li><strong>Lazy loading</strong> happens at <strong>runtime</strong>. It tells React to defer loading a component until it’s actually needed.</li></ul><p>💡 <em>In simple terms: Code splitting creates the chunks. Lazy loading decides when to load them.</em></p><h3>4. Recommended Project Structure</h3><pre>src/<br>├── components/<br>│   └── Loader.jsx<br>├── contexts/<br>│   └── AuthContext.jsx<br>├── layouts/<br>│   └── MainLayout.jsx<br>├── pages/<br>│   ├── Home.jsx<br>│   ├── About.jsx<br>│   └── NotFound.jsx<br>├── routes/<br>│   └── AppRoutes.jsx<br>├── App.jsx<br>├── main.jsx</pre><h3>5. Mise en Place avec Vite + React Router</h3><p>1. Créez le projet :</p><pre>npm create vite@latest my-app -- --template react<br>cd my-app<br>npm install<br>npm install react-router</pre><p>2. main.jsx</p><pre>import { BrowserRouter } from &#39;react-router-dom&#39;;<br>import { AuthProvider } from &#39;./contexts/AuthContext&#39;;<br>import App from &#39;./App&#39;;<br><br>ReactDOM.createRoot(document.getElementById(&#39;root&#39;)).render(<br>  &lt;BrowserRouter&gt;<br>    &lt;AuthProvider&gt;<br>      &lt;App /&gt;<br>    &lt;/AuthProvider&gt;<br>  &lt;/BrowserRouter&gt;<br>);</pre><h3>6. Routing with Lazy Loading</h3><p>Here’s how you define lazy-loaded routes using React Router:</p><pre>// src/routes/AppRoutes.jsx<br><br>import { lazy } from &#39;react&#39;;<br>import { Routes, Route } from &#39;react-router&#39;;<br>import MainLayout from &#39;../layouts/MainLayout&#39;;<br><br>const Home = lazy(() =&gt; import(&#39;../pages/Home&#39;));<br>const About = lazy(() =&gt; import(&#39;../pages/About&#39;));<br>const NotFound = lazy(() =&gt; import(&#39;../pages/NotFound&#39;));<br><br>export default function AppRoutes() {<br>  return (<br>    &lt;Routes&gt;<br>      &lt;Route path=&quot;/&quot; element={&lt;MainLayout /&gt;}&gt;<br>        &lt;Route index element={&lt;Home /&gt;} /&gt;<br>        &lt;Route path=&quot;about&quot; element={&lt;About /&gt;} /&gt;<br>        &lt;Route path=&quot;*&quot; element={&lt;NotFound /&gt;} /&gt;<br>      &lt;/Route&gt;<br>    &lt;/Routes&gt;<br>  );<br>}</pre><p>Use this in your root component:</p><pre>// src/App.jsx<br><br>import React, { Suspense } from &#39;react&#39;;<br>import AppRoutes from &#39;./routes/AppRoutes&#39;;<br>import Loader from &#39;./components/Loader&#39;;<br><br>function App() {<br>  return (<br>    &lt;Suspense fallback={&lt;Loader /&gt;}&gt;<br>      &lt;AppRoutes /&gt;<br>    &lt;/Suspense&gt;<br>  );<br>}<br><br>export default App;</pre><p><strong>Benefit &amp; Implementation Highlights:<br></strong>By combining Vite, code splitting, and lazy loading, you get:</p><ul><li>⚡ <strong>Faster Load Time</strong>: Only essential code is loaded on initial visit (Smaller initial JS bundle).<br>🔁 <strong>Dynamic Imports: </strong>Features are loaded on demand. Reducing upfront load time and bandwidth usage.</li><li>💤 <strong>Better Performance: </strong>Heavy components/pages are loaded only when needed. Especially on slower networks or devices</li><li>🧱 <strong>Cleaner Architecture: </strong>Modular structure, your project is easy to scale and maintain</li></ul><h3>Conclusion</h3><p>Optimizing performance is <strong>not optional;</strong> it’s a competitive advantage. With tools like <strong>Vite</strong> and techniques like <strong>code splitting</strong> and <strong>lazy loading, </strong>together gives your React application a significant performance boost. You get:</p><ul><li>Faster initial page loads,</li><li>Modular code architecture,</li><li>And a smoother user experience.</li></ul><blockquote>Want to Dive Deeper?<br> You can explore a full production-grade React app using everything from this article — code splitting, lazy-loaded routes, context management, and Vite as the build tool.</blockquote><blockquote>🔗 <strong>GitHub:</strong> <a href="https://github.com/BenMukebo/Smart-job-match-web-app/pull/4">Smart Job Match Web App</a></blockquote><blockquote>Feel free to fork, star ⭐️, or contribute!</blockquote><p>Start implementing these techniques today and watch your app feel twice as fast 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fd093128682" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cloud Services (Heroku)]]></title>
            <link>https://benmukebo.medium.com/cloud-services-heroku-71373ab8f62d?source=rss-cd794122db0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/71373ab8f62d</guid>
            <dc:creator><![CDATA[Ben Mukebo]]></dc:creator>
            <pubDate>Sat, 20 Jan 2024 08:57:57 GMT</pubDate>
            <atom:updated>2024-01-20T08:57:57.985Z</atom:updated>
            <content:encoded><![CDATA[<p>Heroku is a platform-as-a-service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X5lj4SodeK28vTq2JzimcA.png" /></figure><p><strong>SaaS: Software as a Service</strong>.<br>eg: Dropbox, Google Drive, WebEx, ….</p><p><strong>PaaS: Platform as a Service</strong>.<br>eg: AWS, elastic Beanstalk, Heroku, open ship, …</p><p><strong>IaaS: Infrastructure as a Service</strong>.<br>eg: AWSec2, Google computer engine, digital ocean. …</p><h4>Cloud Services Analogy</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JFlYGi50nEHUZjwimOvnEQ.png" /></figure><p>If your application is dependent on other upstream or Downstream applications, chances are high that you may have a middleware that connects these applications in an asynchronous fashion</p><p>Deploy on a Runtime environment, middleware, VM, server, storage, networking</p><h4>Heroku Core Components</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-0AVQqzwSMpaAlSypE4lqQ.png" /></figure><p><strong>1. Heroku Platform</strong></p><p><strong>2. Heroku data services</strong></p><p>2.1 Heroku Postgres: A managed SQL database and one of the most popular DBMS.<br>A relational database management system (RDBMS) is a program used to create, update, and manage relational databases. Some of the most well-known RDBMSs include MySQL, PostgreSQL, MariaDB, Microsoft SQL Server, and Oracle Database.</p><p>2.2 Heroku Redis: One of the most popular key-value store used for the caching needs and if the app needs a NoSQL DB</p><p>2.3 Apache Kafka: Can be used as middleware to implement pub sub solution or as a streaming data service if your app needs one</p><p><strong>3. Heroku Enterprise</strong></p><p>3.1.Heroku Private space: a network-isolated qroup of applications and data services within an isolated runtime environment</p><p>3.2 Heroku connect: a bi-directional sync between Heroku Postgres and Salesforce</p><p>3.3 Heroku Shield offers additional security features to build HIPAA or PCI-compliant apps for regulated Industries like healthcare and financial services</p><p>SQL: sico, noSQL: no sico</p><p>What the value does heroku offer as a Paas service</p><p>The code is pushed to the git <strong>repository</strong> and deployed The deployed code is pushed to Heroku <strong>Dynos</strong> which are also called smart containers. The Heroku Runtime provides you with all the data services and integration services required to run the application seamlessly.</p><p>As your app gets more traction, you need to focus on <strong>Scalability,</strong> and to fix any issues the customers may find, and perform a continuous build-on-deploy in the software world. This process is commonly called <strong>CICD</strong></p><p>The Dynos can also be manually scaled or auto-scaled to meet the new demand and improve the performance of your application.</p><h4>Heroku First-Class Languages</h4><p>This means that Heroku Specialists are constantly at work to make sure the latest language versions features and frameworks are maintained patched and supported by Heroku</p><p>Heroku lets you deploy and run applications that are developed using:</p><ul><li>Ruby</li><li>Java</li><li>Node.js</li><li>Clojure</li><li>Scarla</li><li>Go</li><li>Python</li><li>BuildPacks for other languages <br>Heroku extends support for any language of your choice by providing build packs that are contributed by the Heroku community.</li></ul><h4>Heroku Deployment</h4><p>You need to provide:</p><ul><li>Application Source Code Dependency Description.<br>That instructs the build system<br>Eg: pom.xml for Java, package.json for Node, …</li><li>Let Heroku know what the entry point is for your application. (<strong>procfle</strong>)<br>Common frameworks (Rails, Jamgo) define entry points in configuration files and Heroku can easily figure them out.<br>For apps that don’t use a framework you explicitly define the entry point in a <strong>procfle </strong>file where each line declares a process type in the form of a process type colon command. A Process type is an alphanumeric name of your command and these will need to be executed.</li><li>Heroku uses Git to deploy your app (<strong>procfle</strong>)<br>Git is a distributed commonly used version control system.<br>When you create an app on Heroku a git remote is created named “Heroku” and gets associated with the local git repository of your app and deploys with: “git push heroku master”.<br>Now that the source code and its dependencies are available in the Heroku platform Heroku initiates a build.</li></ul><h4>Build Packs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f9ZE-nGIpljzePVd7P2YlQ.png" /></figure><p>Heroku Produice has an output called <strong>slug</strong>, which is ready for execution now. The slug will be run on <strong>Dynos</strong> called smart containers, which are lightweight Unix containers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71373ab8f62d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make ActiveRecord::Enum validation in Rails API application]]></title>
            <link>https://benmukebo.medium.com/make-activerecord-enum-validation-in-rails-api-application-2f42d0c4bec2?source=rss-cd794122db0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f42d0c4bec2</guid>
            <dc:creator><![CDATA[Ben Mukebo]]></dc:creator>
            <pubDate>Tue, 14 Nov 2023 20:05:18 GMT</pubDate>
            <atom:updated>2023-11-15T16:01:40.814Z</atom:updated>
            <content:encoded><![CDATA[<p>As all know, Before Rails version 7.1 When you assign an incorrect value to any record that has an enum as type, it normally raises an ArgumentError as Server Error status: 500</p><p>And, for those who do know, a Rails enum is a way to define a set of allowed values for an attribute in a Rails model. Enums are stored as integers in the database but can be accessed and used in Ruby as symbols.</p><p>Enums were added to Rails in the 4.1 version, but until Rails 7.1, the ability to validate the enums was missing.</p><p>Let’s explore a practical scenario using a User model in a Rails API application. Consider the User model with various attributes, including a age_group column defined as an Enum which is expected to contain only the values specified here in my user.rb file:</p><pre># user.rb<br><br>class User &lt; ApplicationRecord<br>  ...<br>  enum age_group: { infants: 0, children: 1, adolescents: 2, adults: 3 }.freeze<br>end</pre><p>If an incorrect value is assigned to the age_group column, Rails would raise an ArgumentError as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*Hf2z4_WhsbMa79EjQpNOMg.png" /></figure><p>After doing more research to find a better way to catch and display a correct enum error, I found different approaches to doing so, but I felt they required more code logic to write than I wanted to find my own way to handle this more gracefully, and here it is.</p><h3>Catching Enum Errors</h3><p>In the Api::UsersController, we can implement a rescue block to catch the ArgumentError and provide a more user-friendly response; it is just<em> </em>simple. <em>😄</em></p><p>First, go to your controller in the create or update action:</p><pre># users_controller.rb<br>class Api::UsersController &lt; ApplicationController<br>  before_action :set_user, only: %i[show update destroy]<br>    ...<br><br>  # PATCH/PUT /users/1<br>  def update<br>    if @user.update(user_params)<br>      render_success_response(&#39;Profile updated successfully&#39;, @user)<br>    else<br>      render_unprocessable_entity_response(@user.errors)<br>    end<br>  rescue ArgumentError =&gt; e<br>    render_unprocessable_entity_response(e.message)<br>  end<br><br>   ...<br><br>  private<br><br>  # Use callbacks to share common setup or constraints between actions.<br>  def set_user<br>    @user = User.find(params[:id])<br>  rescue ActiveRecord::RecordNotFound =&gt; e<br>    render_not_found_response(e.message)<br>  end<br><br>  # Only allow a list of trusted parameters through.<br>  def user_params<br>    params.require(:user).permit(:username, :age_group, :remember_me, :terms_of_service)<br>  end<br>end</pre><p>The <strong><em>update</em></strong> action in `UsersController` handles profile modifications. Upon a successful update, it renders a successful response. If there are validation errors, it invokes `render_unprocessable_entity_response` with user errors. A rescue block addresses `ArgumentError` during updates, ensuring consistent feedback for enum-related errors.</p><h3>Response Helper Module</h3><p>Then, to maintain consistency in handling responses, a ResponseHelper module is created in app/controllers/concerns/response_helper.rb. This module includes methods for rendering success, unauthorized, not found, and unprocessable entity responses:</p><pre># response_helper.rb<br><br>module ResponseHelper<br>  def render_success_response(message, data)<br>    render json: {<br>      success: true,<br>      message: message,<br>      data: data<br>    }, status: :ok<br>  end<br><br>  # unprocessable_entity<br>  def render_unprocessable_entity_response(error = &#39;Unprocessable entity&#39;)<br>    render json: {<br>      success: false,<br>      errors: error,<br>    }, status: :unprocessable_entity<br>  end<br><br>  def render_unauthorized_response(message = &#39;Unauthorized&#39;)<br>    ...<br>  end<br><br>  def render_not_found_response(message)<br>    render json: {<br>      success: false,<br>      message: message,<br>      data: nil<br>    }, status: :not_found<br>  end<br>end</pre><p>Don’t forget to include the ResponseHelper module in your app/controllers/application_controller.rb:</p><pre># application_controller.rb<br><br>class ApplicationController &lt; ActionController::API<br>  include ResponseHelper<br><br>  # Other configurations...<br>end</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*du-HMsSPUiiuODhcA4Zscg.png" /></figure><p>With these enhancements, your Rails API application will handle Enum errors more gracefully, providing clear and consistent responses to clients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*EOMkPLWt1N3JEWy5.png" /></figure><h3>Written by Ben Mukebo.</h3><p><em>I am a software developer, familiar with a variety of different web technologies and frameworks, and keen on always finding ways to explain things as simple as possible.</em></p><p><em>If this article has been helpful, please hit the 👏 button and share it with others! 🚀 to show how much you liked it! 😄</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f42d0c4bec2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Devise Token Auth vs Devise JWT]]></title>
            <link>https://benmukebo.medium.com/rails-api-user-authentication-36346b68157e?source=rss-cd794122db0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/36346b68157e</guid>
            <dc:creator><![CDATA[Ben Mukebo]]></dc:creator>
            <pubDate>Sat, 08 Apr 2023 13:02:24 GMT</pubDate>
            <atom:updated>2023-04-08T14:21:55.089Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e4fuYA4ZAF_sH9T7.png" /></figure><p><em>One of the most important considerations when creating a new Rails API application is making sure user authentication is implemented correctly. Determining the best strategy for deciding between numerous authentication methods and solutions, such as “Devise Token Auth” and “Devise JWT,” is essential.</em></p><p>Being a curious Ruby on Rails developer, I am well aware of the value of user authentication and the difficulties that come with implementing it. I am thus glad to impart my expertise and experience to other developers who might be experiencing the same issues in order to aid them in making wise choices about user authentication in their Rails API apps.</p><p><strong>Let’s first define the meaning of the term “authentication.”</strong></p><ul><li><strong>Authentication</strong> is the process of verifying the identity of a user or device attempting to access a secure system or application by requiring credentials such as a username and password, which are checked against an authorized user database. Its purpose is to ensure security systems and enterprise information security.</li></ul><p><strong>Let’s now look at some common authentication methods.</strong></p><ul><li>There are several types of authentication that can be used to secure an application. such as <strong>password authentication</strong>, <strong>token-based authentication</strong>, <strong>OAuth authentication</strong>, <strong>two-factor authentication</strong>, <strong>single sign-on</strong> (SSO), and <strong>biometric authentication</strong>, which are some of the most common types.</li></ul><h4>Devise JWT vs. Devise Token Auth With Ruby on Rails</h4><p>There are several other authentication solutions available for Ruby on Rails. Here are some popular options:</p><p>=&gt; Token-based authentication (Devise Token Auth)</p><ul><li>Token-based authentication involves generating a token on the server and sending it to the client upon successful authentication. The token is then included in subsequent API requests as an authorization header, and the server validates the token on each request to ensure the user is authenticated. This approach is simpler to implement and is commonly used in RESTful APIs.</li></ul><p>=&gt; JWT-based authentication (Devise JWT)</p><ul><li>On the other hand, JWT-based authentication uses self-contained tokens that contain user data and can be verified without a server-side session. JWTs are signed by the server and can be verified by clients, making them a stateless authentication solution. They can be used in scenarios where there are multiple API servers, as the token can be validated by any server that shares the same secret key. JWTs are commonly used in modern web applications, especially in microservices architectures.</li></ul><blockquote>Both “<a href="https://github.com/lynndylanhurley/devise_token_auth">Devise Token Auth</a>” and “<a href="https://github.com/waiting-for-dev/devise-jwt">Devise JWT</a>” are authentication solutions for Ruby on Rails API applications that are built on top of <a href="https://github.com/heartcombo/devise">Devise</a>, a popular authentication library for Rails. But the main difference is, “Devise Token Auth” provides token-based authentication, while “Devise JWT” provides JSON Web Token (JWT)-based authentication.</blockquote><p>Choosing between “Devise Token Auth” and “Devise JWT” depends on your specific requirements. However, it is worth noting that “Devise JWT” is considered a more secure authentication solution due to the nature of JWTs being self-contained and signed by the server.</p><p><strong>Additional</strong></p><p>Here are some popular authentication solutions available for Ruby on Rails besides Devise JWT and Devise Token Auth:</p><ul><li><a href="https://github.com/omniauth/omniauth">OmniAuth</a> is a flexible authentication solution for Ruby on Rails that provides support for multiple authentication providers, including Facebook, Twitter, Google, and more. It is designed to be modular and extensible, and it provides a wide range of authentication features.</li><li><a href="https://github.com/tuwukee/jwt_sessions">JWT::Sessions</a> is a JSON Web Token (JWT)-based authentication solution for Ruby on Rails. It provides a simple and secure way to authenticate users using JWTs and includes support for user sign-up, sign-in, email confirmation, and more.</li><li><a href="https://github.com/Sorcery/sorcery">Sorcery:</a> Sorcery is a flexible and lightweight authentication solution for Ruby on Rails. It provides a wide range of authentication features, including password authentication, OAuth authentication, remember me functionality, and more.</li><li><a href="https://github.com/thoughtbot/clearance">Clearance</a>: Clearance is a simple authentication solution for Ruby on Rails. It provides basic authentication features, including sign-up, sign-in, email confirmation, and password reset. It is designed to be easy to use and customize.</li><li><a href="https://github.com/binarylogic/authlogic">Authlogic:</a> Authlogic is a flexible and customizable authentication solution for Ruby on Rails. It provides a wide range of authentication features, including password authentication, OAuth authentication, and more. It is designed to be easy to use and integrate with existing Rails applications.</li></ul><p>These are just a few of the several authentication options that Ruby on Rails supports. It’s crucial to choose an authentication solution after carefully weighing the needs of your application and the security implications of each option.</p><h3>Conclusion</h3><ul><li>In conclusion, it is essential to choose the right authentication approach when developing Rails API applications. “Devise Token Auth” and “Devise JWT” are popular solutions that offer their unique advantages, and the best choice depends on your application’s specific requirements.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*IJvaA8fgfBi7b8tM.png" /></figure><h3>Written by Ben Mukebo.</h3><p><em>I am a software developer, familiar with a variety of different web technologies and frameworks, and keen on always finding ways to explain things as simply as possible.</em></p><p><em>If this article has been helpful, please hit the 👏 button and share it with others! 🚀 to show how much you liked it! 😄</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36346b68157e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Preventing SQL Injection for Rails Queries.]]></title>
            <link>https://benmukebo.medium.com/how-to-prevent-sql-injection-writing-your-queries-in-rails-3b379cb8f17f?source=rss-cd794122db0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b379cb8f17f</guid>
            <dc:creator><![CDATA[Ben Mukebo]]></dc:creator>
            <pubDate>Sat, 21 Jan 2023 04:19:55 GMT</pubDate>
            <atom:updated>2024-03-28T06:29:35.628Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-wvvLKv4gsLIS13k.jpg" /></figure><p>As a Rails developer, writing secure and efficient model methods that interact with the database is crucial. Recently, I discovered that using the Rails query API can prevent SQL injection and improve the security of your application.</p><p>In this article, we will explore the basics of SQL injection and how the Rails query API can be used to secure and prevent SQL injection and improve the efficiency of your model methods. In the end, you will have the knowledge and skills needed to write secure and efficient model methods in Rails.</p><p>Let’s observe these two methods where the User model has a method that returns 3 most recent posts</p><pre># app/models/user.rb<br><br>  def most_recent_posts<br>   posts.order(&#39;created_at DESC&#39;).limit(3)<br>  end<br><br># And<br><br>  def most_recent_posts<br>   posts.order(created_at: :desc).limit(3)<br>  end</pre><p>Both methods will return a user&#39;s three most recent likes in descending order of creation time. The first method uses a string with the SQL ORDER BY clause, while the second method uses the ActiveRecord method order with a symbol to specify the ordering.</p><p>It’s worth noting that the way the SQL is written doesn’t affect the performance as much as the indexes on the table or the database&#39;s query planner. So, it’s better to test the performance in your specific case and see which one performs better. However, it’s good practice to use the Rails query API to prevent SQL injection. This will ensure the security of your application and avoid any potential vulnerabilities.</p><h4>What is SQL Injection?</h4><ul><li>SQL injection is a type of security vulnerability that occurs when an attacker is able to insert malicious SQL code into a query, allowing them to gain unauthorized access to the database or manipulate data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ibT0SykXNbxkFpNs" /><figcaption>Photo by <a href="https://unsplash.com/@magnetme?utm_source=medium&amp;utm_medium=referral">Magnet.me</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>What is the Rails Query API and How to use them to prevent SQL Injection?</strong></h4><ul><li>The Rails query API is a set of methods provided by ActiveRecord, the ORM (Object-Relational Mapping) framework used in Ruby on Rails, that allows you to interact with the database in a secure and efficient manner. These methods provide a higher-level, more abstract interface for querying the database, and take care of escaping any user-supplied input to prevent SQL injection attacks.</li><li>By using the Rails query API, you can prevent SQL injection by ensuring that any user-supplied input is properly escaped and sanitized before it’s included in a query. For example:</li></ul><p>Instead of using raw SQL and string interpolation to build a query, you can use ActiveRecord methods such as where, order, limit etc. These methods will automatically escape any user-supplied input, so you don&#39;t have to worry about it. eg:</p><pre>def most_recent_posts(user_input)<br> likes.where(&quot;name = ?&quot;, user_input).limit(3).order(created_at: :desc)<br>end</pre><p>In this example, thewhere method takes two arguments: the SQL fragment and the user input. The ? is a placeholder, and the user_input will automatically be sanitized and escaped before it&#39;s included in the query, preventing any SQL injection attack.</p><blockquote><strong>Sanitization </strong>refers to the process of cleaning or validating user-supplied input to ensure that it doesn’t contain any malicious code. For example, if the user input is a string, ActiveRecord will check for any special characters or SQL keywords that could be used to inject malicious code into the query. If any are found, they will be removed or replaced with safe equivalents.</blockquote><blockquote><strong>Escaping</strong> refers to the process of adding special characters to user-supplied input to make it safe to include in a query. For example, if the user input is a string, ActiveRecord will add escape characters to any special characters or SQL keywords that could be used to inject malicious code into the query. This ensures that the input is treated as a literal value and not as part of the query itself.</blockquote><blockquote><strong>The use of placeholders</strong> is also an important part of preventing SQL injection attacks. A placeholder is a special marker, such as “user_name”, that indicates where the user-supplied input should be inserted into the query. The ActiveRecord framework will automatically substitute the user input for the placeholders, and the SQL query is constructed with the safe user input.</blockquote><p><em>=&gt; </em><strong><em>Here are some examples of using the Rails query API to build queries:</em></strong></p><p>a. Finding all users with a specific email address:</p><pre># Using SQL Placeholders<br>User.where(&quot;email = ?&quot;, &#39;example@example.com&#39;)</pre><p><em>Using SQL placeholders is a secure approach to include dynamic values in SQL queries. Placeholders, represented by </em><em>?, are utilized within the query, and values are passed separately.</em></p><p><em>In this query, the </em><em>? acts as a placeholder for the email address value, ensuring proper sanitation and protection against SQL injection.</em></p><pre># Using Named Placeholders:<br>User.where(&quot;email = :email&quot;, email: &#39;example@example.com&#39;)<br>User.where(&quot;username LIKE :search OR email LIKE :search&quot;, search: &quot;%#{params[:search]}%&quot;)</pre><p><em>Named placeholders, represented by symbols preceded by a colon (</em><em>:), offer a secure alternative for incorporating dynamic values in SQL queries. These placeholders are associated with specific values when executing the query. For example:<br></em><em>&#39;example@example.com&#39; passed separately, ensuring proper sanitation and protection against SQL injection.</em></p><p><em>Additionally, named placeholders can be useful for filtering based on multiple criteria. In this scenario, the </em><em>:search placeholder is employed to search for users based on usernames or email addresses containing a specified search term, maintaining security against SQL injection.</em></p><p>b. Finding all orders placed after a certain date:</p><pre>Order.where(&#39;created_at &gt; ?&#39;, 1.week.ago)</pre><p>The where method is used to filter the orders by creation date. The method takes a string with the SQL fragment and a value as the second parameter. The value is passed as a placeholder in the query.</p><p>c. Ordering all products by price in ascending order:</p><pre>Product.order(price: :asc)</pre><p>In this example, the order method is used to sort the products by price. The method takes a symbol with the column name and the sorting order.</p><p><strong><em>=&gt; Here are examples of not using the Rails query API:</em></strong></p><p>a. Finding all users with a specific email address:</p><pre>User.find_by_sql(&quot;SELECT * FROM users WHERE email = &#39;#{params[:email]}&#39;&quot;)<br># eg Vulnerable to SQL injection<br># User.where(&quot;username LIKE &#39;%#{params[:search]}%&#39; OR email LIKE &#39;%#{params[:search]}%&#39;&quot;)</pre><p>In this example, the find_by_sql method is used to execute a raw SQL query. The email address is passed as a string, which is vulnerable to SQL injection if the user input is not properly sanitized.</p><p>b. Finding all orders placed after a certain date:</p><pre>Order.find_by_sql(&quot;SELECT * FROM orders WHERE created_at &gt; #{1.week.ago}&quot;)</pre><p>The find_by_sql method is used to execute a raw SQL query. The date value is passed as a string, which is vulnerable to SQL injection if the user input is not properly sanitized.</p><p>c. Ordering all products by price in ascending order:</p><pre>Product.find_by_sql(&quot;SELECT * FROM products ORDER BY price ASC&quot;)</pre><p>In this example, the find_by_sql the method is used to execute a raw SQL query. The sorting order is passed as a string, which is vulnerable to SQL injection if the user input is not properly sanitized.</p><h3>Conclusion</h3><ul><li>In summary, when you use the Rails query API, any user-supplied input is automatically sanitized, escaped, and passed as placeholders in the query, which prevents any SQL injection attack. This is a crucial feature of ActiveRecord that allows you to write secure, database-agnostic code and protects your application from potential vulnerabilities.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*EIwemSgw8_f2Tswf.png" /></figure><h3>Written by Ben Mukebo.</h3><p><em>I am a software developer, familiar with a variety of different web technologies and frameworks, and keen on always finding ways to explain things as simple as possible.</em></p><p><em>If this article has been helpful, please hit the 👏 button and share it with others! 🚀 to show how much you liked it! 😄</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b379cb8f17f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[User Authentication app in Ruby on Rails with Devise-JWT tutorial.]]></title>
            <link>https://benmukebo.medium.com/user-authentication-app-in-ruby-on-rails-with-devise-jwt-tutorial-adabebebd83e?source=rss-cd794122db0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/adabebebd83e</guid>
            <dc:creator><![CDATA[Ben Mukebo]]></dc:creator>
            <pubDate>Fri, 11 Nov 2022 11:59:33 GMT</pubDate>
            <atom:updated>2023-03-18T04:14:45.321Z</atom:updated>
            <content:encoded><![CDATA[<p>During my training a while ago, I had a lot of trouble setting up user authentication to generate a token based on the user payload of your choice, which is attached to every request that requires client-side authentication to identify the user on the server. After more research and reading several articles written on user authentication, I have gained a better understanding of how to set up user authentication for a Rails application using devise and devise-jwt gems. So, I’m going to give you all the necessary information you need to set up and handle errors that can occur during the implementation. I hope this tutorial will help you too.</p><p>If you want to know the purpose of generating tokens, visit the article I wrote about the difference between <a href="https://medium.com/@benmukebo/session-cookies-vs-a-devise-jwt-for-authenticating-users-in-ruby-on-rails-fd923a0586a0">Session Cookies vs. Devise-JWT for Authenticating Users in Ruby on Rails</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ng7-tp4tQJh-6F9e.png" /></figure><p>Let’s start then, so we will need to initialize a new repository for this lesson:</p><h3>Create a new ruby on rails API app</h3><ul><li>To create a rails API application with PostgreSQL database from the command line run:</li></ul><pre>$ rails new user-authentication --api --database=postgresql -T<br> </pre><p>You have noticed the presence of “-T” That is because we don’t need to create an app with testing.</p><h4>Step 1: Configure Rack CORS Middleware</h4><p>Rack::Cors provides support for Cross-Origin Resource Sharing (CORS) for Rack-compatible web applications.</p><p>You need to uncomment the rack-cors line from your generated gem file.</p><pre>gem &#39;rack-cors&#39;, &#39;~&gt; 1.1&#39;</pre><p>And since this is an API-only application, we have to handle ajax requests by uncommenting the contents from config/initialzers/cors.rb file that gets generated when we add--api to create an app. Then, we’ll need to add some updating to handle Cross-Origin Resource Sharing (CORS) and allow all origins to make requests.</p><p>Since we are making <a href="https://techdocs.f5.com/kb/en-us/products/big-ip_asm/manuals/product/asm-implementations-12-1-0/17.html#:~:text=If%20you%20enable%20cross%2Ddomain,domain%20may%20access%20your%20resource.">cross-domain</a> requests, let’s add Authorizationto the list of allowed request headers and exposed response headers. Your code might look like this. <a href="https://github.com/cyu/rack-cors">rack-cors</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*piPUaMNbDVhv93_eH7irLA.png" /></figure><p>The exposed Authorization the header will be used to send (dispatch) and receive JWT tokens in authentication headers.</p><p><strong>Bear in mind</strong>:</p><ul><li><em>Using </em><em>origins ‘*’ is for our convenience. When deploying to production, set </em><em>origins to the URL of your frontend app. Otherwise, the whole internet will be able to hit your API. Though in some cases that’s desirable.</em></li></ul><p>e.i <em>origins &#39;http://your.frontend.domain.com&#39;</em></p><ul><li>If you want to limit requests for methods, you can list all allowed methods like this:</li></ul><p>e.i <em>methods: %i[get post put patch delete options head]</em></p><p>(Optional)<strong> </strong>In the case of rails &lt; 6 you can guard against header attacks on production. For this, you have to manually permit the allowed hosts with:</p><pre>Rails.<strong>application</strong>.<strong>config</strong>.<strong>hosts</strong> <strong>&lt;&lt;</strong> &quot;product.com&quot;</pre><p>Read more about it here in the <a href="https://guides.rubyonrails.org/configuring.html#configuring-middleware">Rails Guides</a></p><p>But Rails ≥ 6 has support for blocking requests from unknown hosts, so origin domains will need to be added there as well. prevents DNS rebinding and other Host header attacks. For more documentation you can read about <a href="https://blog.saeloun.com/2019/10/31/rails-6-adds-guard-against-dns-rebinding-attacks.html">Rails 6 adds guard against DNS rebinding attacks</a></p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>Read more about the HostAuthorization</p><p>In other environments Rails.application.config.hosts is empty and no Host header checks will be done</p><p>Rails 6 has support for blocking requests from unknown hosts, so origin domains will need to be added there as well.</p><pre>Rails.application.config.hosts &lt;&lt; &quot;product.com&quot;</pre><p>Note that for environments other than the development, config.hosts is empty by default. This means no domain checks will be done and the guard will be inactive.</p><p>Read more about it here in the <a href="https://guides.rubyonrails.org/configuring.html#configuring-middleware">Rails Guides</a></p><p>To activate, we can set the Rails.application.config.hosts value to the domain of our choice in the respective environment file.</p><p>To allow a custom domain, we can add the domain to the host&#39;s config. For instance, in development.rb:</p><pre># Allow requests from domain &#39;yourcustomdomain.com&#39;<br>Rails.application.config.hosts &lt;&lt; &#39;yourcustomdomain.com&#39;</pre><p>To allow requests from subdomains,</p><pre># Allow requests from subdomains like &#39;www.yourcustomdomain.com&#39;<br># and &#39;blog.yourcustomdomain.com&#39;.<br>Rails.application.config.hosts &lt;&lt; &#39;.yourcustomdomain.com&#39;</pre><p>And if we need to bypass the guard altogether and allow requests from any domain,</p><pre># Allow requests from any domain<br>Rails.application.config.hosts = nil</pre><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><h4>Step 2: Add the needed Gems</h4><p>Here, You are going to add these gems to your application’s Gemfile:</p><p>devise &amp; devise-jwt for authentication, dispatch, and revocation of JWT tokens and fast_jsonapifor JSON response.</p><pre>gem &#39;devise&#39;, &#39;~&gt; 4.8&#39;<br>gem &#39;devise-jwt&#39;, &#39;~&gt; 0.9.0&#39;<br>gem &#39;fast_jsonapi&#39;</pre><p>Then, execute the bundle to install them.</p><pre>$ bundle install</pre><h4>Step3: Setup and Configure Devise</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Emh2W3cQwj1F2QedOncxsQ.jpeg" /></figure><p>To install the device, run:</p><pre>$ rails g devise:install</pre><p><strong><em>Note:</em></strong><em> if this command hangs, try stopping it and running </em><em>spring stop before running it again.</em></p><p>This command generates two files:</p><p>config/initializers/devise.rb, and config/locales/devise.en.yml</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*Rtez4Ju7Hkg95zh7fmpOvg.png" /></figure><p>And as you can see, we got some instructions to follow:</p><ol><li>The first one refers to the mailer settings. For a development environment, you need to specify your default URL. This won’t give you trouble if you are not going to send mail to your users, but let’s copy and paste the line on the<em> </em><em>development.rb</em> file just in case we need to send mail to our users.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*d_hrS_qFXqzXo7BUrq7aVQ.png" /></figure><p>2. The second point asks us to define a root_url for something. You don’t really need anything on the root path of your application for devise to work. This is just the gem reminding you to make a home page, so I will leave this for later.</p><p>(3 - 4). The third and last points are not necessary since we&#39;ve created an API app and won’t need to implement the “view” part.</p><p><strong><em>Note: </em></strong>Since it’s an API-only app, it is important to set our navigational formats to empty in the generated initializers/devise.rb . To prevent devise from using flash messages which are not presented in Rails API mode.</p><pre>config.navigational_formats = []</pre><p>This line will help you handle Error response statuses such as:</p><p>. <em>401 Unauthorized invalid request</em>,<em> </em><em>422 Unprocessable Entity</em>, …</p><h4>Step4 1. Create a devise User model</h4><p>Let’s create a devise model to represent a user and migration file with devise. Run this command to create a User model:</p><pre>$ rails g devise User</pre><p>After that we need to create a DB and run migrations:</p><pre>$ rails db:create<br>$ rails db:migrate</pre><p><strong>Note</strong><em>: you can chain multiple rails commands, ie: </em><em>rails db:drop db:create db:migrate db:seed …</em></p><h4><strong>4 2. Configure</strong> the <strong>user </strong>model</h4><p>You have to tell which user models you want to be able to authenticate with JWT tokens. For them, the authentication process will be like this:</p><ul><li>A user authenticates through Devise to create a session request (for example, using the standard :database_authenticatable module).</li><li>If the authentication succeeds, a JWT token is dispatched to the client in the Authorization response header, with the format Bearer #{token} (tokens are also dispatched on a successful sign-up).</li><li>The client can use this token to authenticate the following requests for the same user, providing it in the Authorization request header, also with the format Bearer #{token}</li><li>When the client visits Devise to destroy a session request, the token is revoked.</li></ul><p>Update the generated User model with the following code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*PIfYXsnGPrnfM2bsiiBrCA.png" /></figure><p>You can enable it in the user model :confirmable and the :recoverable to ask for confirmation of email and allow us to reset the password in the application.</p><blockquote>As you see, unlike other JWT authentication libraries, it is expected that tokens will be revoked by the server.</blockquote><p>If you need to add something to the JWT payload, you can do it by defining a jwt_payload method in the user model. It must return a Hash. For instance:</p><pre>def jwt_payload<br> { ‘foo’ =&gt; ‘bar’ }<br>end</pre><p>You can add a hook method on_jwt_dispatch to the user model. It is executed when a token is dispatched for that user instance, and it takes token and payload as parameters.</p><pre>def on_jwt_dispatch(token, payload)<br> do_something(token, payload)<br>endr</pre><h4>Step6: Revocation strategies: Denylist</h4><p>devise-jwt comes with three revocation strategies out of the box (<strong>JTIMatcher</strong>, <strong>Denylist</strong>, and <strong>Allowlist</strong>) but in this article, we will only talk about one of them. If you need more information on the two other ones, you can visit this <a href="https://supertokens.com/blog/revoking-access-with-a-jwt-blacklist">link</a> also you can read the <a href="http://waiting-for-dev.github.io/blog/2017/01/24/jwt_revocation_strategies">JWT Revocation Strategies</a> blog post.</p><p><strong>6.1 Denylist</strong></p><p>Now, you need to create another model file called jwt_denylist.rb and</p><p>In this strategy, a database table is used as a list of revoked JWT tokens. The jti claim, which uniquely identifies a token, is persisted. The exp claim is also stored to allow the clean-up of stale tokens.</p><p>Let’s create the corresponding model and include the strategy:</p><pre>class <em>JwtDenylist </em>&lt; <em>ApplicationRecord<br>  include Devise</em>::<em>JWT</em>::<em>RevocationStrategies</em>::<em>Denylist</em></pre><pre>self.table_name = &#39;jwt_denylist&#39;<br>end</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*Fk5HzHEgGw030I7K_rYP1g.png" /></figure><p>In order to use it, you need to create the denylist table in a migration:</p><pre>$ rails g migration CreateJwtDenylist</pre><p>Then update it to this.</p><pre>class CreateJwtDenylist &lt; ActiveRecord::Migration[7.0]<br>  def change<br>    create_table :jwt_denylist do |t|<br>      t.string :jti, null: false<br>      t.datetime :exp, null: false</pre><pre>      t.timestamps<br>    end<br>    add_index :jwt_denylist, :jti<br>  end<br>end</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*xkHMjeHpBek-pPRRB-6oLg.png" /></figure><p>and run the migration.</p><pre>$ rails db:migrate</pre><blockquote><em>This sets up a table that tracks JWT tokens that have been logged out and should no longer have access to the app.</em></blockquote><p><strong>6.2 Session storage caveat</strong></p><p>If you are working with a Rails application that has session storage enabled and a default Devise setup, chances are the same origin requests will be authenticated from the session regardless of whether a token is present in the headers or not. This is so because of the default Devise workflow. When a user signs in with :database_authenticatable strategy, the user is stored in the session.</p><p>So, how can we avoid this caveat?</p><p>Fortunately, we don’t have to worry about it because when you created the application with the --api flag, that disabled already the session, but if you still need the session for any other purpose, disable :database_authenticatable user storage. In config/initializers/devise.rb:</p><pre>config.skip_session_storage = [:http_auth, :params_auth]</pre><p>6.3 This error must occur: “<em>Your application has sessions disabled. To write to the session you must first configure a session store”. </em>In order to solve this, you can add this into your /<a href="https://github.com/BenMukebo/sweet-aromas-api/tree/setup/config">config</a>/application.rb</p><pre># This also configures session_options for use below<br>config.session_store :cookie_store, key: ‘_interslice_session’<br><br># Required for all session management (regardless of session_store)<br>config.middleware.use ActionDispatch::Cookies<br>config.middleware.use config.session_store, config.session_options<br><br># Rails.application.config.session_store :cookie_store, key: ‘_your_app_session’, expire_after: 14.days</pre><h4>Step 7: Add respond_with using the fast_jsonapi method</h4><p>Serializers Ruby on Rails convert a given object into a <strong>JSON</strong> format. As we already added the fast_jsonapi gem, we can generate a serializer to configure the JSON format we&#39;ll want to send to our front end and actually see from our API.</p><pre>$ rails rails generate serializer user id email created_at updated_at</pre><p>Now, we have to add the attributes we want to include as a user response. So the final version user_serializer.rb looks like this:</p><pre>class UserSerializer<br>  include FastJsonapi::ObjectSerializer<br>  attributes :id, :email, :created_at, updated_at<br>end</pre><p>Only the attributes specified in the attribute whitelist will be sent through in our responses, so let’s add to it. We can access serializer data for a single record by,</p><pre>UserSerializer.new(resource).serializable_hash[:data][:attributes]<br>And multiple records by,<br>UserSerializer.new(resource).serializable_hash[:data].map{|data| data[:attributes]}</pre><p>Note: These serializers will now be the default structure for their relevant model when the render is called in the controller this is the Rails naming magic. Now when I request my user data I get this:</p><pre>{<br>  &quot;id&quot;: 1,<br>  &quot;email&quot;: &quot;user@email.com&quot;<br>}</pre><p>For more information, visit the link about <a href="https://medium.com/@maxfpowell/a-quick-intro-to-rails-serializers-b390ced1fce7">Rails Serializers</a></p><p>Now, we have to tell devise to communicate through JSON by adding these methods in the RegistrationsController and SessionsController</p><p><strong>Session storage caveat</strong></p><pre>config.skip_session_storage = [:http_auth, :params_auth]</pre><h4>Step 8: More Devise Setup</h4><p><strong>8.1 Secret key configuration</strong></p><p>Let’s setup the config for jwt secret which will be used to decode the token inside our member</p><p>You have to configure the secret key that will be used to sign generated tokens</p><p>Let’s update first the config/initializers/devise.rb. Add this to the file inside the config block.</p><pre><em>config</em>.jwt do |<em>jwt</em>|<br>  <em>jwt</em>.secret = <em>Rails</em>.application.credentials.devise[:jwt_secret_key]<br>  jwt.expiration_time = 24.hours.to_i<br>end</pre><p>This tells Devise-JWT to use a secret key specified in our credentials file to build tokens.</p><p>If you are using Encrypted Credentials (Rails 5.2+), you can store the secret key in config/credentials.yml.enc.</p><p>Note: You are encouraged to use a secret different than your application secret_key_base. It is quite possible that some other component of your system is already using it. If several components share the same secret key, the chances that a vulnerability in one of them has a wider impact increase. In rails, generating new secrets, run this to your command line</p><pre>$ bundle exec rake secret #or<br>$ rake secret</pre><p>Then copy that and open now your credentials editor using bin/rails credentials:edit command and add the devise_jwt_secret_key.</p><p>Note you may need to set $EDITOR depending on your specific environment. Let’s open the credentials file from the command line.</p><pre>$ EDITOR=nano rails credentials:edit<br>$ EDITOR=&quot;code --wait&quot; rails credentials:edit<br>$ EDITOR=vim rails credentials:edit<br></pre><p>And paste in the following, with the key generated from running rake secret above.</p><pre>devise:<br> jwt_secret_key: &lt;rake secret key&gt;</pre><p>. Note: Application secret keys and credentials should never be checked into Version Control for security reasons.</p><p>To use “<strong>encrypted credentials,” </strong>you need a “key.” Because without this encryption key, you won’t be able to decrypt your “credentials.”</p><p>The <strong>key</strong>, located on config/master.key, is created when you run Rails new. It&#39;s also added to.gitignore, which prevents it from being committed to your repository.</p><p>— — — — -You can store the secret key in config/credentials.yml.enc.</p><p>The <strong>encrypted credentials</strong> (called “secrets” in release 5.1) are saved on config/credentials.yml.enc. Don’t edit the file directly. To add credentials, run</p><p>bin/rails credentials:edit</p><p>After saving the file, the encrypted version will be saved to config/credentials.yml.enc.</p><p>It’s safe to commit the encrypted file to your repository but you should never commit the encryption key(master.key). You cannot save the key to your repository because someone who can access your code can then decrypt the “credentials”.</p><p><strong>Your application has sessions disabled. To write to the session you must first configure a session store</strong></p><pre><em># This also configures session_options for use below<br></em>config.session_store :cookie_store, key: &#39;_interslice_session&#39;<br><em># Required for all session management (regardless of session_store)<br></em>config.middleware.use ActionDispatch::Cookies<br>config.middleware.use config.session_store, config.session_options</pre><ul><li><strong>The Master Key</strong></li></ul><p>The encrypted credentials.yml.enc file will be decrypted in production, using a key stored either in the RAILS_MASTER_KEYenvironment variable, or in a key file. In development environment, the application uses config/master.key to decrypt the data.</p><p>This key file is created for you when you scaffold your new Rails 5.2 app using the rails newcommand. If it doesn&#39;t exist, a key will be created when you run rails credentials:edit.</p><p>You should also note that without the master.key file present in your project&#39;s config folder, you will experience errors. This might happen, for example, when you fork and clone an existing project and try to run rails db:setup (or equivalent).</p><h4>Step 9: Customize devise controllers and routes</h4><p>To override the default devise sessions controller, let&#39;s create the sessions, and registration controllers that handle sign-up, sign-in, and log_out.</p><p>$ rails g devise :controllers users -c sessions registrations</p><p>Always add respond_to :json on the top to specify that they will be responding to JSON requests.</p><p>/controllers/users/registrations_controller.rb would look like this:</p><pre>class Users::RegistrationsController &lt; Devise::RegistrationsController<br>  respond_to :json<br>  private<br>  def respond_with(resource, _opts = {})<br>    if resource.persisted?<br>      render json: {<br>        status: { code: 200, message: &#39;Signed up sucessfully.&#39; },<br>        data: UserSerializer.new(resource).serializable_hash[:data][:attributes]<br>      }, status: :ok<br>    else<br>      render json: {<br>        status: { message: &quot;User couldn&#39;t be created successfully.&quot; }<br>      }, status: :unprocessable_entity<br>    end<br>  end<br>end</pre><p><em>/controllers/users/sessions_controller.rb</em> would look like this:</p><pre>class Users::SessionsController &lt; Devise::SessionsController<br>  respond_to :json<br>  private<br>  def respond_with(resource, _opts = {})<br>    render json: {<br>      status: { code: 200, message: &#39;Logged in successfully.&#39; },<br>      data: UserSerializer.new(resource).serializable_hash[:data][:attributes]<br>    }, status: :ok<br>  end<br>  def respond_to_on_destroy<br>    if current_user<br>      render json: {<br>        status: 200,<br>        message: &quot;#{current_user.user_name} has logged out successfully.&quot;<br>      }, status: :ok<br>    else<br>      render json: {<br>        status: 401,<br>        message: &quot;Couldn&#39;t find an active session.&quot;<br>      }, status: :unauthorized<br>    end<br>  end<br>end</pre><p>Then, let’s update the <em>application_controller.rb</em> file to configure_permitted_parameters</p><pre>class ApplicationController &lt; ActionController::API<br>  before_action :configure_permitted_parameters, if: :devise_controller?<br>  protected<br>  def configure_permitted_parameters<br>    devise_parameter_sanitizer.permit(:sign_in) do |user_params|<br>      user_params.permit(:email, :password)<br>    end<br>    devise_parameter_sanitizer.permit(:sign_up) do |user|<br>      user.permit(:email, :password)<br>  end<br>end</pre><p>Then, Update the routes aliases to override the default routes provided by the devise in the routes.rb so they point to your new controllers, rather than to the default devise controllers.</p><p><em>api/config/routes</em></p><pre>Rails.application.routes.draw do<br>devise_for :users, defaults: { format: :json }, path: &#39;&#39;,                          path_names: {<br>    sign_in: &#39;login&#39;,<br>    sign_out: &#39;logout&#39;,<br>    registration: &#39;signup&#39;<br>  },<br>  controllers: {<br>    sessions: &#39;users/sessions&#39;,<br>    registrations: &#39;users/registrations&#39;<br>  }<br>end</pre><h4>Final step: Deployment</h4><pre>$ heroku create user-authent<br>$ git push heroku setup:main<br>$ heroku run rails db:migrate</pre><pre>#If the master key does not get to push to github</pre><pre>$ heroku config:set RAILS_MASTER_KEY=`cat config/master.key` #then<br>$ heroku run rails db:migrate</pre><h3>Conclusion</h3><ul><li>In the article, you’ve learned how to implement user authentication in the ruby on rails app by using “devise” and “devise-jwt” gems.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*DBgiDYHQiU5zFbe5.png" /></figure><h3>Written by Ben Mukebo.</h3><p><em>I am a software developer, familiar with a variety of different web technologies and frameworks, and keen on always finding ways to explain things as simple as possible.</em></p><p><em>If this article has been helpful, please hit the 👏 button and share it with others! 🚀 to show how much you liked it! 😄</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adabebebd83e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Session Cookies vs. A Devise-JWT for Authenticating Users in Ruby on Rails]]></title>
            <link>https://benmukebo.medium.com/session-cookies-vs-a-devise-jwt-for-authenticating-users-in-ruby-on-rails-fd923a0586a0?source=rss-cd794122db0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd923a0586a0</guid>
            <dc:creator><![CDATA[Ben Mukebo]]></dc:creator>
            <pubDate>Tue, 30 Aug 2022 16:07:11 GMT</pubDate>
            <atom:updated>2022-08-30T17:10:42.193Z</atom:updated>
            <content:encoded><![CDATA[<p>This article will explain the differences between Devise-JWT and Sessions, as well as which one to use for authentication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XrqIFzFzbM9fH6iQ" /><figcaption>Photo by <a href="https://unsplash.com/@anniespratt?utm_source=medium&amp;utm_medium=referral">Annie Spratt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Recently, I had to implement authentication on one of the Rails projects I was assigned to work on. through my research on the best approach to use to create a user authentication API. I found several articles, especially related to the <strong>Devise-JWT-Token</strong> since they used Ruby on Rails for the API creation.</p><p>After configuring the authentication with Devise JWT, I began to wonder if there was a better way to implement user authentication than the Devise-JWT token I had previously used. That pushed my ideas far, and I ended up finding that there are two primary different approaches in Ruby on Rails that you can use for <strong>session management.</strong></p><ul><li><strong>Session or Cookies, and</strong></li><li><strong>JWT (JSON Web Tokens)</strong></li></ul><p>As you might remember, HTTP is a stateless protocol. This means that your server doesn’t remember anything from previous requests. We generally need to maintain login “sessions”, so that once a user logs in for the first time, they should be able to continue to access different parts of the application without having to log in again and again for each subsequent “http” request made by the server.</p><h3>Why are session cookies and Devise-JWT important?</h3><p>Consider how websites remember how a user is logged in when the page reloads. We<strong> </strong>need to allow websites to remember users within a website when they move between different parts of the application. So, how does it work when a user signs in and your server remembers?</p><blockquote>So, the only way to remember the states of your application is by using either sessions or tokens.</blockquote><blockquote>In web applications, after successful authentication, the server generates a “cookie” in the case of session-cookie, or an “accesstoken” in the case of device-JWT. Those are the two mechanisms that Rails and your browser use to store and retrieve the state for a user in order to maintain login sessions in the application.</blockquote><h4><strong>I. Session Cookies</strong></h4><p>When you browse the web, you use HTTP requests, which is a stateless protocol. So, how can you tell that a given request actually came from that particular user who is logged in? This is why cookies are important. They allow you to keep track of your users from one request to another until the cookie expires.</p><p><strong>=&gt; <em>What is a session?</em></strong></p><p>A <a href="https://guides.rubyonrails.org/action_controller_overview.html#session"><strong>session</strong></a> is just a place to store data from one request to then read it on later requests. For example, after a user is logged in, you can store the user’s ID in the session so on later requests you can fetch the user and know the request is authenticated and get the user’s details. Also, a session can have different mechanisms to store the data. The ones used in most cases are “<strong>cookies</strong>”. You can give an identifier value to the user’s browser, and then on every request you get it back and can use it to fetch the session and corresponding data.</p><p>If you’d like to learn more, visit this link on <a href="https://www.justinweiss.com/articles/how-rails-sessions-work/">how rails sessions work</a>.</p><p><strong>=&gt; <em>What is a cookie?</em></strong></p><p><a href="https://www.theodinproject.com/lessons/ruby-on-rails-sessions-cookies-and-authentication#cookies"><strong>Cookies</strong></a> are key-value pairs that are stored in the browser and sent on every request to their domain. They can be used for anything, but in this case, they are used to store a “credential” that can identify the session for the user. If you’d like to learn more, visit this <a href="https://guides.rubyonrails.org/action_controller_overview.html#cookies">Rails guide: cookies</a>.</p><p><strong>Steps in Session Cookie</strong></p><pre><strong>=&gt;</strong> After successful authentication</pre><pre>1. The Server generates a &quot;<strong>sessionId&quot;</strong> (signs it using &quot;secret key&quot;), and saves the sessionId in a <strong>sessionDB</strong>, and sends a cookie with the sessionId to the browser (client side).</pre><pre>2. The browser (client side) receives the &quot;cookie&quot; in the response from the server, and saves it in the cookie storage.</pre><pre>3. The browser then includes the &quot;cookie&quot; in every subsequent request to the server.</pre><pre><strong>=&gt;</strong> User is authenticated and the client side has a &quot;<strong><em>cookie&quot;</em></strong> </pre><pre>4. Get the <strong>&quot;sessionId&quot;</strong> from the request &quot;cookie&quot;.</pre><pre>5<strong>. </strong>Verify the<strong> &quot;sessionId&quot; </strong>integrity using the<strong> &quot;secret key&quot;. <br></strong>Then look up the<strong> &quot;sessionId&quot; </strong>within the sessionDB on the server and get the<strong> &quot;userId&quot;.</strong></pre><pre>6. Look up the &quot;userId&quot; within the shoppingCartDB to add items to cart for that userId, or display cart info for that userId.<em>.</em></pre><p><strong>Note:</strong></p><ul><li><em>The sessionId does not contain any</em><strong><em> “</em></strong><em>userId</em><strong><em>” </em></strong><em>information, but is a random string generated and signed by the “secret key.” The sessionId is then saved within the sessionDB. The sessionDB is a database table that maps “sessionId” to “userId”. The session cookie</em><strong><em> </em></strong><em>is called the</em><strong><em> “stateful” </em></strong><em>approach to managing sessions, since the</em><strong><em> </em></strong><em>“state” or “session”</em><strong><em> </em></strong><em>is saved within a DB. A sessionDB stores sessionIds.</em></li></ul><h4><strong>II. Devise-JWT ( </strong>accessToken <strong>)</strong></h4><p><a href="https://github.com/DakotaLMartinez/rails-devise-jwt-tutorial">Devise-jwt</a> is a device extension that uses JSON Web Tokens(JWT) for user authentication. It’s an encoded, URL-safe string that can contain an unlimited amount of data (unlike a cookie) and is cryptographically signed. When a server receives a JWT, it can guarantee the data it contains can be trusted because it’s signed by the source.</p><p>userId is got by decrypting the JWT token (no DB call is required to get userId), so this is somewhat faster than the session approach. Servers can be scaled separately, without the need to share session DB. This makes the JWT approach a great option for micro-services architecture.</p><p>On the client-side, the browser stores the token locally using local storage, session storage, or cookie storage. On future requests, the JWT is added to the authorization header prefixed by the bearer, and the server will validate its signature by decoding the token before proceeding to send a response.</p><p><strong>Steps in Devise -JWT</strong></p><pre><strong>=&gt;</strong> After successful authentication</pre><pre>1. The server generates an <strong>&quot;accessToken&quot;</strong>, encrypting the &quot;userId&quot; and &quot;expiresIn&quot;, with the ACCESS_TOKEN_SECRET, <br>and sends the &quot;accessToken&quot; to the browser (client side).</pre><pre>2. The browser (client side) receives the &quot;accessToken&quot; and saves it on the client side.</pre><pre>3. The &quot;accessToken&quot; is included in every subsequent request to the server.</pre><pre><strong>=&gt;</strong> User is authenticated and the client side has an &quot;<strong><em>accessToken</em></strong>&quot;.</pre><pre>4. Get the <strong>&quot;accessToken&quot;</strong> from the request &quot;header&quot;.</pre><pre>5<strong>. </strong>Decrypt the<strong> &quot;accessToken&quot;</strong> i.e the JWT, using ACCESS_TOKEN_SECRET and get the<strong> &quot;userId&quot; </strong>---&gt; <em>(there is no DB lookup).</em></pre><pre>6. Look up the &quot;userId&quot; within the shoppingCartDB to add items to cart for that userId, or display cart info for that userId.</pre><p><strong>Note:</strong></p><ul><li><em>Devise-JWT uses a “secret key” specified in our credentials file to build the JWT tokens, sometimes referred to as “Bearer Tokens” since all the information about the user i.e. “bearer”, is contained within the token. The token is added to the request headers themselves (rather than stored/retrieved as a cookie). This isn’t performed automatically by the browser (as with cookies) but is typically handled by a front-end framework as part of an AJAX call. All the information about the user is contained within the accessToken ( the encrypted “userId”), and the accessToken is not saved within any sessionDB on the server side like cookies, it only exists on the client side. That is why it is</em><strong><em> </em></strong><em>called a</em><strong><em> stateless </em></strong><em>approach to managing sessions since no “state” or “session” is saved within a DB (it is contained within the JWT token itself).</em></li></ul><p><strong>Additional Note:</strong></p><ul><li>We can use either the “Session-Cookie” or the “Devise-JWT” (widely used in modern web applications) to implement the session management. The main difference is that in the case of the device-JWT, the server does not need to maintain a DB of sessionId for lookup. Because the tokens are stored on the client side while the session uses server memory to store user data, this may cause a problem if a large number of users access the application at the same time.</li><li>We can also combine the JWT with cookies. On every request to the server, the JWT will be read from cookies and added to the authorization header using the bearer scheme. The server can then verify the JWT in the request header (as opposed to reading it from the cookies). If you need to learn more, visit this link on how to <a href="https://stackoverflow.com/questions/62338013/how-to-send-jwt-token-to-cookie-and-use-in-another-routes">send JWT tokens to Cookie</a>.</li></ul><h3>Conclusion</h3><ul><li>In the article, you’ve learned that we can use “cookies” in the case of a session approach and an “accessToken” in the case of a device-JWT approach for authentication. In both approaches, the client side must securely save the “cookie” or the “jwt token”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*cOOPKjECrujsBJdI.png" /></figure><h4>Written by Ben Mukebo.</h4><p><em>I am a software developer, familiar with a variety of different web technologies and frameworks, and keen on always finding ways to explain things as simply as possible.</em></p><p><em>If this article has been helpful, please hit the 👏 button and share it with others! 🚀 to show how much you liked it! 😄</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd923a0586a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to become a successful software developer.]]></title>
            <link>https://benmukebo.medium.com/how-to-become-a-successful-software-developer-6007a53d4deb?source=rss-cd794122db0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6007a53d4deb</guid>
            <category><![CDATA[teamwork]]></category>
            <category><![CDATA[time-management]]></category>
            <category><![CDATA[growth-mindset]]></category>
            <category><![CDATA[analytical-thinking]]></category>
            <dc:creator><![CDATA[Ben Mukebo]]></dc:creator>
            <pubDate>Sat, 13 Nov 2021 21:32:38 GMT</pubDate>
            <atom:updated>2022-09-25T00:05:25.994Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What are the key traits and qualities that every successful software developer is required to have?</strong></p><figure><img alt="Successful-Software-Developers" src="https://cdn-images-1.medium.com/max/1024/0*d6xXYuGJnvgjCp4P" /><figcaption>Photo by <a href="https://unsplash.com/@wocintechchat?utm_source=medium&amp;utm_medium=referral">Christina @ wocintechchat.com</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><strong>Previously I could never imagine that becoming a good software developer required Four major things that all successful software developers have in common: Growth Mindset, Analytical thinking, Teamwork, Time Management. Which characterizes all their careers as software developers</strong><em>.</em></blockquote><ul><li><em>Here I will discuss how having </em>a growth mindset <em>has helped me become a better and more </em>successful software developer<em>. I will talk about a specific example where having a growth mindset was helpful </em>in my career as a software developer.</li></ul><p><strong>What is a Growth Mindset</strong></p><p><em>A </em><a href="https://en.wikipedia.org/wiki/Mindset"><em>growth mindset</em></a><em> is a way of thinking and believing that we can accomplish what we desire through continuous work, learning from feedback, and talent development (through hard work, good strategies, input from others, and persistence).</em></p><p>A growth mindset is something you develop, not something you’re born with, and that comes from the belief that your basic qualities are things you can cultivate through effort.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HfVQl3yWDgAfHhZe" /><figcaption>Photo by <a href="https://unsplash.com/@mmintel?utm_source=medium&amp;utm_medium=referral">Marc Mintel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is the way to use it to build your confidence.</p><p>Yes, people differ greatly in aptitude, capacity, and talents, but everyone can change and grow through application, training, and experience.</p><p>Before adopting a growth mindset, I was facing and struggling with some imposter syndrome that really affected my progress, reduced my confidence, and turned me away from my dream goal and</p><p>since I realized that my entire life is a learning process. No matter how good I become at coding, I will always have to learn something new and I’m always facing a challenge I have to deal with. I can learn from it. That helps me to deal with and tackle imposter syndrome and have acceptance of the current situation.</p><p>The ability to see a challenge and grow from it is the basis of the growth mindset. This is why it is important to start cultivating a growth mindset as soon as possible.</p><p><strong>Conclusion</strong></p><p>I will end here by encouraging others to use their four qualities to help them be successful in their software development career<em>. Thank you for reading my article.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*v0_RTiD8_J-_B6Pb.png" /></figure><h4>Written by Ben Mukebo.</h4><p><em>I am a software developer, familiar with a variety of different web technologies and frameworks, and keen on always finding ways to explain things as simple as possible.</em></p><p><em>If this article has been helpful, please hit the 👏 button and share it with others! 🚀 to show how much you liked it! 😄</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6007a53d4deb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>