<?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 Oruçhan Asar on Medium]]></title>
        <description><![CDATA[Stories by Oruçhan Asar on Medium]]></description>
        <link>https://medium.com/@oruchan.asar?source=rss-b1e1ec3e853d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NWyeglFWZyV947cQnJSRPQ.jpeg</url>
            <title>Stories by Oruçhan Asar on Medium</title>
            <link>https://medium.com/@oruchan.asar?source=rss-b1e1ec3e853d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 00:05:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oruchan.asar/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[What If We Coded for the Planet?]]></title>
            <link>https://medium.com/@oruchan.asar/what-if-we-coded-for-the-planet-20fa6da04d9d?source=rss-b1e1ec3e853d------2</link>
            <guid isPermaLink="false">https://medium.com/p/20fa6da04d9d</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[future]]></category>
            <category><![CDATA[green-energy]]></category>
            <dc:creator><![CDATA[Oruçhan Asar]]></dc:creator>
            <pubDate>Thu, 10 Jul 2025 10:30:40 GMT</pubDate>
            <atom:updated>2025-07-10T10:30:40.332Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GfAnmoRcaY3O0CYKXekZDg.png" /></figure><p><strong>Imagining a Greener World Through Energy-Efficient Programming Languages like C and Rust</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/0*hpjY2AdQaFgrnCUO.png" /><figcaption><a href="https://greenlab.di.uminho.pt/wp-content/uploads/2017/10/sleFinal.pdf">https://greenlab.di.uminho.pt/wp-content/uploads/2017/10/sleFinal.pdf</a></figcaption></figure><p>Years ago, I came across a fascinating table comparing the energy, time, and memory efficiency of popular programming languages. At the very top were C and Rust — two low-level, high-performance languages. While they’re not as widely used as Python or JavaScript in day-to-day web and app development, their raw power and efficiency got me thinking: <em>What would happen if the entire world wrote its software in these languages?</em> Could this change significantly reduce our energy consumption and carbon emissions? Would we end up with a greener, more sustainable world?</p><p>In this article, I’ll walk you through the environmental, economic, and technological consequences of living in a world coded exclusively in C or Rust.</p><h3>Global Energy and CO₂ Savings</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hq9FoovYqNuU0Et--ZlPKQ.png" /></figure><p>This chart from the <a href="https://www.iea.org/data-and-statistics/charts/data-centre-electricity-consumption-by-region-base-case-2020-2030">International Energy Agency</a> highlights the projected increase in electricity consumption by data centers across major regions such as the United States, China, and Europe through 2030.</p><p>Let’s start with the big picture. According to the International Energy Agency, electricity consumption by data centers is rapidly rising and projected to exceed 900 TWh globally by 2030. As of 2024, data centers are responsible for around <strong>1–2% of global electricity consumption</strong>, emitting nearly <a href="https://blog.enconnex.com/data-center-carbon-footprint-scope-1-2-3-emissions"><strong>300 megatonnes of CO₂ annually</strong></a>. Languages like Python and Ruby, while great for productivity, are <strong>50 to 75 times less energy-efficient</strong> than C or Rust.</p><p>If we replaced all high-level application code with C or Rust equivalents, global data center energy usage could drop by as much as <strong>30%</strong>, conservatively. That’s a potential <strong>reduction of ~90 megatonnes of CO₂ annually</strong>. To put that in perspective:</p><ul><li><a href="https://www.device42.com/data-center-infrastructure-management-guide/data-center-carbon-footprint/">That’s like removing <strong>20 million cars</strong> from the road each year.</a></li><li><a href="https://www.device42.com/data-center-infrastructure-management-guide/data-center-carbon-footprint/">Or planting <strong>1.4 billion trees</strong>.</a></li><li><a href="https://www.device42.com/data-center-infrastructure-management-guide/data-center-carbon-footprint/">Or powering <strong>6 million homes</strong> for an entire year.</a></li></ul><h4>Energy Efficiency Gain</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*Br0WU-6YkPDXCUGI7iBkew.png" /></figure><h3>Less Water, Fewer Servers, Cleaner Planet</h3><p>Data centers not only consume electricity but also massive amounts of water for cooling. <a href="https://eng.ox.ac.uk/case-studies/the-true-cost-of-water-guzzling-data-centres/">In the U.S., up to <strong>43% of data center electricity is used for cooling</strong>, and traditional cooling methods can consume significant amounts of water. For example, a relatively small 1-megawatt data center — which uses enough electricity to power 1,000 homes — can use <strong>26 million liters of water per year</strong></a>. Many data centers rely on evaporative cooling, where this water is lost as it transforms heat into vapor. Less power-hungry code means less heat, which translates to less cooling required. If switching to C or Rust could reduce cooling needs by even 25%, we’d save over <strong>150 billion liters of water annually</strong> worldwide.</p><p>Moreover, efficient code means fewer servers are needed to handle the same workload. That reduces demand for mining rare earth materials, decreases electronic waste, and lightens the overall environmental load of the tech industry.</p><h4>Environmental Impact Summary</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*toFJIjLXuiVkhqoZg48hxw.png" /></figure><h3>The Cost of Control: Developer Productivity</h3><p>Writing software in C is like performing brain surgery with a scalpel. It’s powerful, but one slip can crash an entire system. Memory management, pointer arithmetic, and lack of modern abstractions make C development slower and more error-prone.</p><p>Rust aims to solve many of these issues with a modern type system, a borrow checker, and no garbage collector. It offers nearly the same efficiency as C but adds much more safety. However, Rust has its own learning curve, and writing code in Rust is still significantly slower than in Python or JavaScript, especially for beginners.</p><h4>Development Time Comparison</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*w896v9qf7QywUz3o1ak5UA.png" /></figure><h3>Trade-offs: Should Energy Be the Only Concern?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*7i-19Egu9-f_4pupeJOwYA.png" /></figure><h3>Developer &amp; Software Ecosystem</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*jkY2gHaAZxaIC15iXFpGrQ.png" /></figure><h3>Application Innovation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*1IfPeB7GXV2HxeqXqBopQA.png" /></figure><h3>Business &amp; Economy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*axOPxKr7Hf0w9Bk-g1P3ig.png" /></figure><h3>AI and Data Science</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*WSS_upJ6GPhLtPMJ06utcA.png" /></figure><h3>Security and Safety</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*zMefvG_FRHUsbIh8tj2QuQ.png" /></figure><h3>A More Realistic Future: Hybrid Ecosystems</h3><p>Instead of rewriting the world in Rust or C, the more viable approach is a <strong>hybrid system</strong>:</p><ul><li>Use <strong>Rust or C for performance-critical components</strong>: OS kernels, embedded systems, blockchain nodes, game engines, and core infrastructure.</li><li>Use <strong>higher-level languages for the rest</strong>: Python, JavaScript, and others where developer speed, library ecosystems, and prototyping matter more.</li></ul><p>This gives us the best of both worlds: efficiency where it matters, and flexibility where it fuels innovation.</p><h3>Final Thoughts</h3><p>While switching the entire world to Rust overnight is impractical, this thought experiment reveals a powerful truth: <strong>the way we write code has real environmental consequences</strong>. As developers, we hold a unique responsibility — not only to build great software, but also to make sustainable choices where it matters. Whether it’s optimizing critical systems in Rust, or blending it with higher-level languages for balance, the future of green tech may very well begin at the keyboard.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20fa6da04d9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top Libraries for Product Tours & Highlights]]></title>
            <link>https://medium.com/dogus-teknoloji/top-libraries-for-product-tours-highlights-5976077cb3bf?source=rss-b1e1ec3e853d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5976077cb3bf</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[product-tour]]></category>
            <category><![CDATA[yazilim]]></category>
            <category><![CDATA[product-guide]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Oruçhan Asar]]></dc:creator>
            <pubDate>Thu, 15 May 2025 08:57:51 GMT</pubDate>
            <atom:updated>2025-06-17T10:52:09.327Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7_Pf9nAAiWEP4eYayM8KhA.png" /></figure><p>Here are some <strong>popular and well-supported JavaScript libraries</strong> you can use to implement product tours, feature highlights, and contextual help:</p><ol><li><a href="https://driverjs.com/"><strong>Driver.js</strong></a></li><li><a href="https://docs.react-joyride.com/"><strong>React Joyride</strong></a></li><li><a href="https://introjs.com/"><strong>Intro.js</strong></a></li><li><a href="https://shepherdjs.dev/"><strong>Shepherd.js</strong></a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*7RVL4CnnnHrs7DlUiGdRqA.png" /></figure><h4>Key Takeaways:</h4><ul><li>✅ <strong>Best Overall for React Apps:</strong> <strong>React Joyride</strong></li><li>✅ <strong>Best Lightweight Vanilla JS Option:</strong> <strong>Driver.js</strong></li><li>⚠️ <strong>AGPL License Warning</strong>: <strong>Intro.js</strong> and <strong>Shepherd.js</strong> require commercial licenses for commercial use.</li><li>🪶 <strong>Smallest Bundle:</strong> <strong>Driver.js (82.5 kB)</strong></li></ul><h3>If you’re using <strong>Next.js 15</strong> (React-based, App Router), here’s a focused recommendation:</h3><h4>Best Option: React Joyride</h4><p>🔹 <strong>Why it’s a good fit:</strong></p><ul><li><strong>Made for React</strong> — It’s a React-first library with good integration into component lifecycles.</li><li><strong>Declarative API</strong> — You define the steps as a prop, making it easier to maintain.</li><li><strong>Proven Stability</strong> — 340k+ weekly downloads, strong community, and mature ecosystem.</li><li><strong>Customizable</strong> — You can fully theme it, use custom components, and handle events like onStepChange, onClose, etc.</li><li><strong>Next.js Compatibility</strong> — Works well with React 18 features (including SSR/CSR separation, Suspense, etc.)</li></ul><p>⚠️ <strong>Consider:</strong></p><ul><li>It’s a bit larger (498 kB unpacked), but in practice, it’s not a dealbreaker unless you are very performance-sensitive.</li></ul><h4>Alternative: Driver.js (if you want light &amp; framework-agnostic)</h4><p>🔹 <strong>Why consider it:</strong></p><ul><li>Lightweight and zero dependencies</li><li>Excellent element highlighting with backdrop</li><li>Easy to set up and can be used with React/Next.js</li><li>MIT licensed and updated frequently</li></ul><p>⚠️ <strong>Downside:</strong></p><ul><li>Not React-specific: You’ll need to handle DOM refs manually and work around hydration issues in SSR environments (especially with useEffect and dynamic imports).</li></ul><h4>Avoid for Next.js (unless licensing is OK):</h4><ul><li><strong>Intro.js &amp; Shepherd.js</strong>:</li><li>AGPL license → <strong>not safe for commercial projects</strong> unless you buy a license</li><li>Larger size and not React-first → more work to integrate smoothly in a modern Next.js 15 app</li></ul><h4>Final Recommendation:</h4><p>| If you’re building a full React experience with state &amp; component control → <strong>Use </strong><strong>React Joyride</strong>.<br>| If you want lightweight, DOM-first, fast setup → <strong>Use </strong><strong>Driver.js</strong> with dynamic import in client components.</p><p>Here’s a <strong>sample integration snippet</strong> for both <strong>React Joyride</strong> and <strong>Driver.js</strong> in a <strong>Next.js 15 (App Router)</strong> app.</p><h4>Option 1: <strong>React Joyride</strong> in Next.js 15 (Recommended for React-first apps)</h4><pre>npm install react-joyride</pre><pre>// components/TourProvider.tsx<br>&quot;use client&quot;;<br><br>import React, { useState } from &quot;react&quot;;<br>import Joyride, { CallBackProps, Step } from &quot;react-joyride&quot;;<br><br>const steps: Step[] = [<br>  {<br>    target: &quot;.feature-1&quot;,<br>    content: &quot;This is your first feature!&quot;,<br>  },<br>  {<br>    target: &quot;.feature-2&quot;,<br>    content: &quot;Here&#39;s another cool feature!&quot;,<br>  },<br>];<br><br>export default function TourProvider() {<br>  const [run, setRun] = useState(true);<br><br>  const handleJoyrideCallback = (data: CallBackProps) =&gt; {<br>    // handle step change, close, etc.<br>    if (data.status === &quot;finished&quot; || data.status === &quot;skipped&quot;) {<br>      setRun(false);<br>    }<br>  };<br><br>  return (<br>    &lt;Joyride<br>      steps={steps}<br>      run={run}<br>      continuous<br>      showProgress<br>      showSkipButton<br>      callback={handleJoyrideCallback}<br>      styles={{<br>        options: {<br>          zIndex: 10000,<br>        },<br>      }}<br>    /&gt;<br>  );<br>}</pre><pre>// app/page.tsx or any client component<br>import TourProvider from &quot;@/components/TourProvider&quot;;<br><br>export default function Home() {<br>  return (<br>    &lt;div&gt;<br>      &lt;TourProvider /&gt;<br>      &lt;h1 className=&quot;feature-1&quot;&gt;Welcome to the App&lt;/h1&gt;<br>      &lt;p className=&quot;feature-2&quot;&gt;Let me guide you!&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h4>Option 2: <strong>Driver.js</strong> in Next.js 15</h4><pre>npm install driver.js</pre><pre>// components/DriverTour.tsx<br>&quot;use client&quot;;<br><br>import { useEffect } from &quot;react&quot;;<br>import { driver } from &quot;driver.js&quot;;<br>import &quot;driver.js/dist/driver.css&quot;;<br><br>export default function DriverTour() {<br>  useEffect(() =&gt; {<br>    const driverObj = driver({<br>      showProgress: true,<br>      allowClose: true,<br>      overlayClickBehavior: &quot;nextStep&quot;,<br>      overlayColor: &quot;rgba(0, 0, 0, 0.6)&quot;,<br>      stagePadding: 8,<br>      stageRadius: 6,<br>      popoverOffset: 12,<br>      showButtons: [&quot;previous&quot;, &quot;next&quot;, &quot;close&quot;],<br>      nextBtnText: &quot;Next →&quot;,<br>      prevBtnText: &quot;← Back&quot;,<br>      doneBtnText: &quot;Got it!&quot;,<br>      onNextClick: (el, step) =&gt; {<br>        console.log(&quot;Next clicked&quot;, step);<br>      },<br>      onPrevClick: (el, step) =&gt; {<br>        console.log(&quot;Previous clicked&quot;, step);<br>      },<br>      onCloseClick: (el, step) =&gt; {<br>        console.log(&quot;Tour closed&quot;, step);<br>      },<br>      steps: [<br>        {<br>          element: &quot;.page-header&quot;,<br>          popover: {<br>            title: &quot;Header&quot;,<br>            description: &quot;This is your page header&quot;,<br>          },<br>        },<br>        {<br>          element: &quot;.top-nav&quot;,<br>          popover: {<br>            title: &quot;Navigation&quot;,<br>            description: &quot;Use this to move between pages&quot;,<br>          },<br>        },<br>        {<br>          element: &quot;.sidebar&quot;,<br>          popover: {<br>            title: &quot;Sidebar&quot;,<br>            description: &quot;Access important sections quickly&quot;,<br>          },<br>        },<br>        {<br>          element: &quot;.footer&quot;,<br>          popover: {<br>            title: &quot;Footer&quot;,<br>            description: &quot;Here is some useful info or links&quot;,<br>          },<br>        },<br>      ],<br>    });<br><br>    driverObj.drive();<br>  }, []);<br><br>  return null;<br>}</pre><pre>// app/page.tsx<br>import DriverTour from &quot;@/components/DriverTour&quot;;<br><br>export default function Home() {<br>  return (<br>    &lt;div&gt;<br>      &lt;DriverTour /&gt;<br>      &lt;header className=&quot;page-header&quot;&gt;Header Area&lt;/header&gt;<br>      &lt;nav className=&quot;top-nav&quot;&gt;Top Navigation&lt;/nav&gt;<br>      &lt;aside className=&quot;sidebar&quot;&gt;Sidebar&lt;/aside&gt;<br>      &lt;footer className=&quot;footer&quot;&gt;Footer&lt;/footer&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Conclusion</h3><p>Both <strong>React Joyride</strong> and <strong>Driver.js</strong> are powerful tools for building guided tours and highlighting features in your <strong>Next.js 15</strong> application.</p><ul><li>If you prefer a <strong>React-first</strong> approach with component-driven logic and fine-grained control, <strong>React Joyride</strong> is a great choice.</li><li>If you want a <strong>lightweight, framework-agnostic</strong>, and visually polished solution that’s easy to trigger on demand, <strong>Driver.js</strong> is ideal — especially for quick onboarding and highlighting specific elements.</li></ul><p>For Next.js 15 with the App Router, <strong>Driver.js integrates smoothly</strong> with client components, and its API makes it easy to define steps or highlight elements. The examples provided above show how to seamlessly use it in your app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5976077cb3bf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dogus-teknoloji/top-libraries-for-product-tours-highlights-5976077cb3bf">Top Libraries for Product Tours &amp; Highlights</a> was originally published in <a href="https://medium.com/dogus-teknoloji">Doğuş Teknoloji</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Modern Dashboard with Next.js 15, Redux Toolkit, TanStack Table, and Shadcn/UI]]></title>
            <link>https://medium.com/@oruchan.asar/building-a-modern-dashboard-with-next-js-15-redux-toolkit-tanstack-table-and-shadcn-ui-5fa1bfa5f2b7?source=rss-b1e1ec3e853d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fa1bfa5f2b7</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[redux-toolkit]]></category>
            <category><![CDATA[shadcn-ui]]></category>
            <category><![CDATA[tanstack-table]]></category>
            <category><![CDATA[dashboard]]></category>
            <dc:creator><![CDATA[Oruçhan Asar]]></dc:creator>
            <pubDate>Sun, 11 May 2025 14:39:23 GMT</pubDate>
            <atom:updated>2025-05-11T14:39:23.976Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JGTWipZdxrE2oAGFFhLaXA.png" /></figure><p>Creating modern, scalable dashboards requires a thoughtful combination of frontend technologies and architectural patterns. In this article, we explore how <a href="https://dashboard-example-alpha.vercel.app/"><strong>Dashboard Example</strong></a> utilizes <strong>Next.js 15</strong>, <strong>Redux Toolkit</strong>, <strong>TanStack Table</strong>, and <strong>shadcn/ui</strong> to deliver a fast, maintainable, and feature-rich admin panel.</p><p>The application fetches data from <a href="https://jsonplaceholder.typicode.com/"><strong>JSONPlaceholder</strong></a>, a free online REST API used for prototyping and testing.</p><p>This project showcases a clean architecture and focuses on modularity, developer experience, and performance — ideal for real-world applications like CMS dashboards, admin panels, or data-driven UIs.</p><p><strong>GitHub Repository:</strong> <a href="https://github.com/Oruchan-Asar/dashboard-example">https://github.com/Oruchan-Asar/dashboard-example</a></p><h3>Technology Stack</h3><h4>Core Frameworks</h4><ul><li><strong>Next.js 15</strong><br> Provides hybrid rendering (SSR/SSG), dynamic routing, and powerful app routing via the /app directory.</li><li><strong>React 19</strong><br> The latest version enhances concurrent rendering and delivers better performance with features like automatic batching and useOptimistic.</li><li><strong>TypeScript</strong><br> Adds static type safety, reducing runtime bugs and improving development efficiency.</li><li><strong>Redux Toolkit (RTK Query)</strong><br> Handles global state and API data fetching with minimal boilerplate. RTK Query simplifies caching, re-fetching, and data synchronization.</li></ul><h4>UI and Styling</h4><ul><li><strong>Tailwind CSS</strong><br> A utility-first CSS framework for consistent styling and rapid prototyping.</li><li><strong>shadcn/ui</strong><br> A beautiful, accessible component library built on top of Radix UI and styled with Tailwind. It’s highly composable and ideal for modern UIs.</li><li><strong>TanStack Table</strong><br> A powerful headless table solution that supports sorting, pagination, filtering, and virtualization. Perfect for building responsive and interactive tables.</li></ul><h3>Project Structure</h3><p>The codebase follows a modular and scalable structure:</p><pre>├── app/              # App router directory (Next.js 15)<br>│   ├── albums/       # Feature-based routes<br>│   ├── posts/<br>│   ├── todos/<br>│   └── users/<br>├── components/       # Shared React components<br>│   ├── ui/<br>├── hooks/            # Custom hooks<br>├── lib/              # Utility functions and helper modules<br>│   ├── features/<br>│   ├── interfaces/<br>├── public/           # Static files (e.g., images, icons)</pre><p>This organization enables code splitting, maintainability, and logical feature boundaries. Each route in the app/ directory can have its own loading state, error handling, and layout, thanks to the new Next.js app router.</p><h3>Key Features</h3><h4>1. RTK Query for API Calls</h4><p>RTK Query handles all CRUD operations with endpoints like /users, /posts, and /albums, automatically caching responses and minimizing network requests.</p><pre>const { data: users, isLoading } = useGetUsersQuery();</pre><h4>2. <strong>Pagination and Filtering with TanStack Table</strong></h4><p>Every data table in the app (e.g., users, albums) is powered by TanStack Table. This allows:</p><ul><li>Client-side pagination</li><li>Column sorting and filtering</li><li>Responsive layouts with Tailwind</li></ul><pre>&lt;UsersTable data={users} columns={columns} /&gt;</pre><h4>3. Reusable Components with Shadcn/UI</h4><p>Components like buttons, cards, dropdowns, and modals are built using shadcn/ui, offering consistent styling and accessibility out of the box.</p><pre>import { Button } from &quot;@/components/ui/button&quot;;<br><br>&lt;Button variant=&quot;outline&quot;&gt;Add User&lt;/Button&gt;</pre><h3>Conclusion</h3><p>This project highlights how combining <strong>Next.js 15</strong>, <strong>RTK Query</strong>, <strong>TanStack Table</strong>, and <strong>shadcn/ui</strong> results in a robust dashboard solution that is:</p><ul><li>Highly maintainable</li><li>Scalable</li><li>Developer-friendly</li><li>Visually consistent and performant</li></ul><p>Whether you’re building an admin panel, internal tool, or data-heavy SPA, this stack offers everything you need to get started quickly without sacrificing long-term maintainability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fa1bfa5f2b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is Debounce Literally?]]></title>
            <link>https://medium.com/@oruchan.asar/what-is-debounce-literally-a39ff3ce7034?source=rss-b1e1ec3e853d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a39ff3ce7034</guid>
            <category><![CDATA[debouncing-in-react]]></category>
            <category><![CDATA[debouncing]]></category>
            <category><![CDATA[debounce]]></category>
            <dc:creator><![CDATA[Oruçhan Asar]]></dc:creator>
            <pubDate>Sat, 03 May 2025 16:17:35 GMT</pubDate>
            <atom:updated>2025-05-03T16:17:35.495Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F9JtvzbNupvte-SvT5X0tg.png" /></figure><p><strong>Debouncing</strong> means:<br> “<em>Wait for a moment of silence before doing the thing.</em>”</p><p>Imagine you’re typing in a search box. Debounce will <strong>wait</strong> until you’ve <strong>stopped typing</strong> for a while (e.g., 300ms) before making the API call.<br>It <strong>resets the timer</strong> on every keystroke.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*A-ORF_KcUFJZctn4yQMK6A.png" /></figure><h3>How It Works (Internally)</h3><p>Here’s a behind-the-scenes breakdown of how debounce works step-by-step:</p><h4>1. debounce(func, delay) returns a new function.</h4><p>This new function keeps track of a timer (usually let timer; in a closure).</p><h4>2. When the returned function is called:</h4><ul><li>If there’s already a timer → <strong>clear it</strong> (cancel the previous plan).</li><li>Set a new timer → wait for delay milliseconds.</li><li>When the delay finishes <strong>without interruption</strong>, run the func.</li></ul><h4>Memory Representation</h4><p>In memory, it looks like:</p><pre>let timer = null;<br><br>input -&gt; [reset timer] -&gt; [start new timer]<br>      -&gt; [reset timer] -&gt; [start new timer]<br>      -&gt; [no input] =&gt; Timer finishes → run `func`</pre><h3>Example 1: Search Input Debounce</h3><pre>function debounce(func, delay) {<br>  let timer;<br>  return function (...args) {<br>    clearTimeout(timer);<br>    timer = setTimeout(() =&gt; {<br>      func.apply(this, args);<br>    }, delay);<br>  };<br>}<br><br>const searchHandler = debounce((query) =&gt; {<br>  console.log(&#39;Fetching results for:&#39;, query);<br>}, 500);<br><br>// Simulating typing<br>searchHandler(&quot;a&quot;);   // ⏱️ timer started<br>searchHandler(&quot;ap&quot;);  // ⏱️ previous timer cleared, new one set<br>searchHandler(&quot;app&quot;); // ⏱️ again<br>// ...wait 500ms<br>// ✅ &quot;Fetching results for: app&quot; logged</pre><h4>Backend Process Behind The Scenes</h4><pre>Typing:<br> - t=0ms  → input &quot;a&quot;  → set timer (t+500)<br> - t=50ms → input &quot;ap&quot; → clear old timer, new timer (t+550)<br> - t=80ms → input &quot;app&quot;→ clear old timer, new timer (t+580)<br> - ...<br> - t=580ms+ → run the actual function (search)<br><br>No backend API call is made until the user stops typing for 500ms.</pre><h3>Bonus: Debounce vs Throttle (Quick Glance)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*s7jV_zO_rrbMA6T8cU5v6w.png" /></figure><h3>Articles &amp; Tutorials</h3><ul><li><a href="https://www.freecodecamp.org/news/javascript-debounce-example">Debounce — How to Delay a Function in JavaScript (JS ES6 Example)</a></li><li><a href="https://css-tricks.com/debouncing-throttling-explained-examples/">Debouncing and Throttling Explained Through Examples</a></li><li><a href="https://www.joshwcomeau.com/snippets/javascript/debounce/">JoshWComeau — debounce</a></li></ul><h3>Here are some popular and reliable JavaScript libraries</h3><ol><li><a href="https://lodash.com/docs/4.17.15#debounce">Lodash</a></li><li><a href="https://underscorejs.org/#debounce">Underscore.js</a></li><li><a href="https://www.npmjs.com/package/use-debounce">use-debounce (for React Hooks)</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a39ff3ce7034" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Hoisting Actually Works (Step-by-Step)]]></title>
            <link>https://medium.com/@oruchan.asar/how-hoisting-actually-works-step-by-step-2d0ec4136922?source=rss-b1e1ec3e853d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d0ec4136922</guid>
            <category><![CDATA[hoisting-in-javascript]]></category>
            <category><![CDATA[hoisting]]></category>
            <dc:creator><![CDATA[Oruçhan Asar]]></dc:creator>
            <pubDate>Sun, 27 Apr 2025 21:17:13 GMT</pubDate>
            <atom:updated>2025-04-27T21:17:13.798Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gxD7huERXJPYxKeiAX4STA.png" /></figure><h3><strong>1. Code Execution Phases</strong></h3><p>When JavaScript runs your code, it first goes through <strong>two main phases</strong>:</p><ul><li><strong>Memory Creation Phase</strong> (also called “Creation Phase” or “Compile Phase”)</li><li><strong>Execution Phase</strong></li></ul><h3><strong>2. Memory Creation Phase (Before the code runs)</strong></h3><p>In this phase:</p><ul><li>The JavaScript engine <strong>scans your code</strong> from top to bottom.</li><li>It <strong>creates “memory spaces”</strong> in the <strong>Global Execution Context (GEC)</strong> for:<br>- <strong>Variables<br>- Functions</strong></li></ul><p>How?</p><ul><li><strong>var variables</strong> are <strong>hoisted</strong> and assigned a value of undefined.</li><li><strong>let and </strong><strong>const variables</strong> are <strong>hoisted</strong> too, but placed in a <strong>&quot;Temporal Dead Zone (TDZ)&quot;</strong> (more on that soon).</li><li><strong>Function declarations</strong> are hoisted <strong>with their entire body</strong> (so you can call them even before their definition).</li></ul><p>Memory Phase Example:</p><pre>console.log(a); // ???<br>console.log(b); // ???<br>console.log(add(2, 3)); // ???<br><br>var a = 10;<br>let b = 20;<br><br>function add(x, y) {<br>  return x + y;<br>}</pre><p><strong>During the Memory Phase</strong>, JS does this in the background:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*BK8xaXVCQ9F6WYeNAGtPWw.png" /></figure><ul><li>a is set to undefined.</li><li>b is reserved but not initialized yet → <strong>TDZ</strong> (Temporal Dead Zone).</li><li>add is <strong>fully stored</strong>, not just undefined.</li></ul><h3><strong>3. Execution Phase</strong></h3><p>In this phase:</p><ul><li>JS starts running your code <strong>line by line</strong>.</li></ul><p>What happens here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*6wL_QyKSssOb-L_qVkgEZg.png" /></figure><h3><strong>Behind the Scenes: Where Are Things Stored?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*OIR4zNi_atvvd-zs4k9JAw.png" /></figure><p>var attaches variables to the window (in browsers) → window.a exists, but window.b does not!</p><h3>Full Visual Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*L7gac4DYPJtBVBvYFZ0Zfg.png" /></figure><h3>Some tricky hoisting interview questions:</h3><p>1️⃣ Question:</p><pre>console.log(typeof foo); // ?<br>var foo = function() {<br>  console.log(&#39;Hello!&#39;);<br>};</pre><p><strong>Answer:</strong> &quot;undefined&quot;</p><p><strong>Explanation:</strong></p><ul><li>During the <strong>Memory Phase</strong>, var foo is hoisted and initialized with undefined.</li><li>typeof undefined returns &quot;undefined&quot;.</li><li>The function expression (function() { ... }) is <strong>NOT hoisted</strong> — only the variable name foo is hoisted, <strong>not the function body</strong>.</li></ul><p>2️⃣ Question:</p><pre>function test() {<br>  console.log(a); <br>  console.log(foo());<br>  <br>  var a = 1;<br>  <br>  function foo() {<br>    return 2;<br>  }<br>}<br><br>test();</pre><p><strong>Answer:</strong> &quot;undefined&quot;, 2</p><p><strong>Explanation:</strong></p><ul><li>In the <strong>Memory Phase</strong> inside test():</li><li>a is hoisted as undefined.</li><li>foo is hoisted with its full function body.</li><li>During execution:</li><li>console.log(a) → prints undefined</li><li>console.log(foo()) → calls the hoisted foo() → returns 2</li></ul><p>3️⃣ Question:</p><pre>var a = 1;<br><br>function b() {<br>  a = 10;<br>  return;<br>  function a() {}<br>}<br><br>b();<br>console.log(a);</pre><p><strong>Explanation:</strong></p><ul><li>Inside function b(), <strong>there’s a hoisted local </strong><strong>function a()</strong>.</li><li>So a = 10; assigns 10 to the <strong>local a</strong>, not the global one!</li><li>The global a (var a = 1) stays <strong>untouched</strong>.</li><li>After b() is called, console.log(a) prints 1.</li></ul><p>⚡️ <em>Trick:</em> Because of function a() hoisting, a inside b refers to a local binding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d0ec4136922" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Changing SVG Colors in Nextjs: Using JSX Components for Dynamic Icon Color]]></title>
            <link>https://medium.com/@oruchan.asar/changing-svg-colors-in-nextjs-using-jsx-components-for-dynamic-icon-color-59352da27d8a?source=rss-b1e1ec3e853d------2</link>
            <guid isPermaLink="false">https://medium.com/p/59352da27d8a</guid>
            <category><![CDATA[svg-icon]]></category>
            <category><![CDATA[svg]]></category>
            <category><![CDATA[navbar]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Oruçhan Asar]]></dc:creator>
            <pubDate>Fri, 15 Sep 2023 22:07:58 GMT</pubDate>
            <atom:updated>2023-09-16T09:07:39.277Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0CJvNwP5F38BRpVPFWQFCA.png" /></figure><p>SVG icons are popular for adding visual elements to web applications due to their scalability and adaptability. However, changing the color of SVG icons dynamically in response to user interactions can be a bit tricky when using static SVG files. In this article, we will explore how to overcome this limitation by using JSX components to create SVG icons, allowing us to easily change their colors in a Next application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*u8REDmf6nVDVq-WIMeQ4jw.png" /></figure><h3>The Challenge of Changing SVG Colors</h3><p>Imagine you have a tab menu in your Next application, and you want to change the color of the icons when a user interacts with them. You may initially attempt to achieve this by importing SVG files and rendering them as &lt;Image /&gt; elements. However, you soon realize that changing the color of these SVG icons is not straightforward with this approach.</p><p>Here’s an example of how it might look:</p><pre>import Image from &quot;next/image&quot;;<br>import userIcon from &quot;@/public/tabMenuIcons/userIcon.svg&quot;;<br>import projectIcon from &quot;@/public/tabMenuIcons/projectIcon.svg&quot;;<br>import blogIcon from &quot;@/public/tabMenuIcons/blogIcon.svg&quot;;<br>import bookmarkIcon from &quot;@/public/tabMenuIcons/bookmarkIcon.svg&quot;;<br><br>export default function ChangeSvgColor() {<br>  const tabs = [<br>    { icon: userIcon, name: &quot;About&quot; },<br>    { icon: projectIcon, name: &quot;Projects&quot; },<br>    { icon: blogIcon, name: &quot;Blogs&quot; },<br>    { icon: bookmarkIcon, name: &quot;Bookmarks&quot; },<br>  ];<br>  return (<br>    &lt;div className=&quot;flex gap-4 border-b-2 w-fit&quot;&gt;<br>      {tabs?.map((tab, index) =&gt; (<br>        &lt;div<br>          key={index}<br>          className=&quot;flex items-center gap-2 px-1 py-2 transition-all duration-300 border-b-2 cursor-pointer stroke-[#9BA2AE] text-[#9BA2AE] hover:stroke-blue-500 border-b-transparent hover:border-b-2 hover:border-blue-500 hover:text-blue-500 active:border-blue-500&quot;<br>        &gt;<br>          &lt;Image src={tab.icon} alt={`${tab.name} icon`} /&gt;<br>          &lt;p className=&quot;text-sm font-medium&quot;&gt;{tab.name}&lt;/p&gt;<br>        &lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*qPbqcgwZVK-ui1LJcquzCw.png" /></figure><p>As you can see, this approach doesn’t allow us to change the SVG icon’s color as desired.</p><h3>Using JSX Components for SVG Icons</h3><p>We can create our SVG icons as JSX components to overcome this limitation. This way, we can easily customize the SVG elements, including their color. Let’s see how this can be done:</p><h4>1. Create JSX Components for SVG Icons</h4><p>Instead of using static SVG files, we can define our SVG icons as JSX components. For example, here’s how you can create a user icon as a JSX component:</p><pre>export default function UserIcon() {<br>  return (<br>    &lt;svg<br>      xmlns=&quot;http://www.w3.org/2000/svg&quot;<br>      viewBox=&quot;0 0 24 24&quot;<br>      fill=&quot;currentColor&quot;<br>      className=&quot;w-6 h-6&quot;<br>    &gt;<br>      &lt;path<br>        fillRule=&quot;evenodd&quot;<br>        d=&quot;M7.5 6a4.5 4.5 0 119 0 4.5 4.5 0 01-9 0zM3.751 20.105a8.25 8.25 0 0116.498 0 .75.75 0 01-.437.695A18.683 18.683 0 0112 22.5c-2.786 0-5.433-.608-7.812-1.7a.75.75 0 01-.437-.695z&quot;<br>        clipRule=&quot;evenodd&quot;<br>      /&gt;<br>    &lt;/svg&gt;<br>  );<br>}</pre><h4>2. Use JSX Components in Your Next Application</h4><p>Now that we have our SVG icons as JSX components, we can easily use them in our Next application. Here’s how you can integrate them into your tab menu component:</p><pre>import UserIcon from &quot;@/public/tabMenuIcons/UserIcon&quot;;<br>import ProjectIcon from &quot;@/public/tabMenuIcons/ProjectIcon&quot;;<br>import BlogIcon from &quot;@/public/tabMenuIcons/BlogIcon&quot;;<br>import BookmarkIcon from &quot;@/public/tabMenuIcons/BookmarkIcon&quot;;<br><br>export default function ChangeSvgColor() {<br>  const tabs = [<br>    { icon: &lt;UserIcon /&gt;, name: &quot;About&quot; },<br>    { icon: &lt;ProjectIcon /&gt;, name: &quot;Projects&quot; },<br>    { icon: &lt;BlogIcon /&gt;, name: &quot;Blogs&quot; },<br>    { icon: &lt;BookmarkIcon /&gt;, name: &quot;Bookmarks&quot; },<br>  ];<br>  return (<br>    &lt;div className=&quot;flex gap-4 border-b-2 w-fit&quot;&gt;<br>      {tabs?.map((tab, index) =&gt; (<br>        &lt;div<br>          key={index}<br>          className=&quot;flex items-center gap-2 px-1 py-2 transition-all duration-300 border-b-2 cursor-pointer stroke-[#9BA2AE] text-[#9BA2AE] hover:stroke-blue-500 border-b-transparent hover:border-b-2 hover:border-blue-500 hover:text-blue-500 active:border-blue-500&quot;<br>        &gt;<br>          {tab.icon}<br>          &lt;p className=&quot;text-sm font-medium&quot;&gt;{tab.name}&lt;/p&gt;<br>        &lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>By using JSX components for our SVG icons, we can easily customize their appearance, including color, and achieve the desired interaction effect when a user hovers over or clicks on them.</p><h3>Conclusion</h3><p>In this article, we explored how to overcome the challenge of changing the color of SVG icons dynamically in a Next application. By creating SVG icons as JSX components, we gained greater flexibility and control over their appearance, making it easy to customize their colors and achieve our web application’s desired user interaction effects. This approach not only enhances the user experience but also simplifies the management of SVG icons in your Next project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59352da27d8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NextJS 13 App Backend Development]]></title>
            <link>https://medium.com/@oruchan.asar/nextjs-13-app-backend-development-d044c804c3?source=rss-b1e1ec3e853d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d044c804c3</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Oruçhan Asar]]></dc:creator>
            <pubDate>Tue, 13 Jun 2023 21:11:13 GMT</pubDate>
            <atom:updated>2023-06-13T21:20:59.599Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pGaCZSANVgJI6hgHi8aK6Q.png" /></figure><p>This report provides an overview of key components and functionalities implemented in a backend application. It covers topics such as database connection, user registration API, user authentication and token generation, JSON Web Token (JWT) verification, permission checks, and user model schema. Each section discusses the purpose, implementation, and usage of the respective code snippets. The report aims to provide a comprehensive understanding of the backend development aspects necessary for building a secure and scalable web application.</p><h3>Database Connection Code</h3><pre>import mongoose from &quot;mongoose&quot;;<br><br>const MONGODB_URI = process.env.MONGODB_URI;<br><br>if (!MONGODB_URI) {<br>  throw new Error(<br>    &quot;Please define the MONGODB_URI environment variable inside .env.local&quot;<br>  );<br>}<br><br>let cached = { conn: null, promise: null };<br><br>async function dbConnect() {<br>  if (cached.conn) {<br>    return cached.conn;<br>  }<br><br>  if (!cached.promise) {<br>    const opts = {<br>      bufferCommands: false,<br>    };<br><br>    cached.promise = mongoose.connect(MONGODB_URI, opts);<br>  }<br><br>  try {<br>    cached.conn = await cached.promise;<br>  } catch (e) {<br>    cached.promise = null;<br>    throw e;<br>  }<br><br>  return cached.conn;<br>}<br><br>export default dbConnect;</pre><h4>Overview</h4><p>The provided code is a module that establishes a connection to a MongoDB database using Mongoose, a popular Object-Document Mapping (ODM) library for MongoDB and Node.js. The code ensures that the connection is established only once and reused for subsequent calls to improve performance.</p><h4>Dependencies</h4><p>The code assumes that the required dependencies, including <strong>mongoose</strong>, are installed and can be imported.</p><pre>import mongoose from &quot;mongoose&quot;;</pre><h4>MongoDB URI Configuration</h4><p>The code expects a MongoDB URI to be defined as an environment variable named <strong>MONGODB_URI</strong>. This URI specifies the address of the MongoDB database that the application will connect to.</p><pre>const MONGODB_URI = process.env.MONGODB_URI;</pre><p>If the <strong>MONGODB_URI</strong> is not defined, an error is thrown to alert the developer to define the environment variable properly.</p><h4>Connection Caching</h4><p>To optimize performance and avoid unnecessary connections to the database, the code implements a caching mechanism using the <strong>cached</strong> object.</p><pre>let cached = { conn: null, promise: null };</pre><p>The <strong>cached</strong> object stores the connection and promises to establish the connection. It is initially set to <strong>null</strong> for both properties.</p><h4>Database Connection Function</h4><p>The <strong>dbConnect</strong> function is an asynchronous function that handles the database connection. It first checks if a connection is already established and returns it if available.</p><pre>async function dbConnect() {<br>  if (cached.conn) {<br>    return cached.conn;<br>  }</pre><p>If no connection is available, it checks if a connection promise is already in progress. If not, it creates a new connection promise using the <strong>mongoose.connect</strong> method with the provided MongoDB URI and additional options.</p><pre>if (!cached.promise) {<br>  const opts = {<br>    bufferCommands: false,<br>  };<br><br>  cached.promise = mongoose.connect(MONGODB_URI, opts);<br>}</pre><p>The <strong>bufferCommands: false</strong> option disables command buffering, ensuring that each command is executed immediately rather than being buffered and executed later.</p><p>Next, the code awaits the connection promise and assigns the resulting connection to the <strong>cached.conn</strong> property. If an error occurs during the connection attempt, the promise is set to <strong>null</strong>, and the error is thrown.</p><pre>try {<br>  cached.conn = await cached.promise;<br>} catch (e) {<br>  cached.promise = null;<br>  throw e;<br>}</pre><p>Finally, the function returns the established connection.</p><h4>Export</h4><p>The <strong>dbConnect</strong> function is exported as the default export of the module, making it accessible to other parts of the application.</p><pre>export default dbConnect;</pre><h3>User Registration API</h3><pre>import dbConnect from &quot;@/lib/dbConnect&quot;;<br>import User from &quot;@/models/User&quot;;<br>import bcrypt from &quot;bcryptjs&quot;;<br><br>export async function POST(request) {<br>  try {<br>    await dbConnect();<br>    const { name, email, password } = await request.json();<br><br>    const existingUser = await User.findOne({ email });<br>    if (existingUser) {<br>      return new Response(<br>        JSON.stringify({ success: false, message: &quot;User already exists&quot; }),<br>        { status: 400 }<br>      );<br>    }<br><br>    const hashedPassword = await bcrypt.hash(password, 10);<br><br>    const user = await User.create({<br>      name,<br>      email,<br>      password: hashedPassword,<br>    });<br><br>    return new Response(JSON.stringify({ success: true, data: user }), {<br>      status: 201,<br>    });<br>  } catch (error) {<br>    return new Response(<br>      JSON.stringify({ success: false, message: error.message }),<br>      { status: 500 }<br>    );<br>  }<br>}</pre><h4>Overview</h4><p>The provided code is an API endpoint for user registration. It receives a POST request with user details, checks if the user already exists, hashes the password using bcrypt, creates a new user record, and returns the result as a JSON response.</p><h4>Dependencies</h4><p>The code assumes that the required dependencies, such as <strong>dbConnect</strong>, <strong>User</strong> model, and <strong>bcryptjs</strong>, are properly imported.</p><pre>import dbConnect from &quot;@/lib/dbConnect&quot;;<br>import User from &quot;@/models/User&quot;;<br>import bcrypt from &quot;bcryptjs&quot;;</pre><h4>Database Connection</h4><p>The <strong>dbConnect</strong> function is imported and called at the beginning of the <strong>POST</strong> function to establish a connection with the MongoDB database.</p><pre>await dbConnect();</pre><p>This ensures that a connection is available before performing any database operations.</p><h4>Request Handling</h4><p>The <strong>POST</strong> function takes the <strong>request</strong> object as a parameter, representing the incoming HTTP request. It extracts the user details from the request&#39;s JSON payload using <strong>await request.json()</strong>.</p><pre>const { name, email, password } = await request.json();</pre><h4>User Existence Check</h4><p>The code checks if a user with the given <strong>email</strong> already exists in the database by querying the <strong>User</strong> model using <strong>findOne</strong>.</p><pre>const existingUser = await User.findOne({ email });<br>if (existingUser) {<br>  return new Response(<br>    JSON.stringify({ success: false, message: &quot;User already exists&quot; }),<br>    { status: 400 }<br>  );<br>}</pre><p>If an existing user is found, it returns a JSON response indicating the failure with a status code of 400 (Bad Request).</p><h4>Password Hashing</h4><p>The code uses <strong>bcrypt</strong> to hash the <strong>password</strong> before storing it in the database. It generates a hash with a cost factor of 10 using <strong>bcrypt.hash</strong>.</p><pre>const hashedPassword = await bcrypt.hash(password, 10);</pre><h4>User Creation</h4><p>The code creates a new user record in the database using the <strong>User.create</strong> method from the <strong>User</strong> model.</p><pre>const user = await User.create({<br>  name,<br>  email,<br>  password: hashedPassword,<br>});</pre><p>The user object is populated with the provided <strong>name</strong>, <strong>email</strong>, and the hashed <strong>password</strong>.</p><h4>Response Handling</h4><p>If the user creation is successful, the code returns a JSON response with the created user data and a status code of 201 (Created).</p><pre>return new Response(JSON.stringify({ success: true, data: user }), {<br>  status: 201,<br>});</pre><p>If any errors occur during the execution, the code catches the error, constructs an appropriate error message JSON response, and returns it with a status code of 500 (Internal Server Error).</p><pre>return new Response(<br>  JSON.stringify({ success: false, message: error.message }),<br>  { status: 500 }<br>);</pre><h3>User Authentication and Token Generation</h3><pre>import { SignJWT } from &quot;jose&quot;;<br>import { jwtSecretKey } from &quot;@/lib/auth.js&quot;;<br>import { NextResponse } from &quot;next/server&quot;;<br>import User from &quot;@/models/User&quot;;<br>import bcrypt from &quot;bcryptjs&quot;;<br><br>export async function POST(request) {<br>  const body = await request.json();<br><br>  const { email, password } = body;<br><br>  if (await isValidCredentials(email, password)) {<br>    const user = await User.findOne({ email });<br><br>    const role = user?.role || &quot;user&quot;;<br><br>    const token = await generateToken(email, role);<br><br>    const response = NextResponse.json({<br>      success: true,<br>    });<br><br>    setTokenCookie(response.cookies, token);<br><br>    return response;<br>  }<br><br>  return NextResponse.json({ success: false });<br>}<br><br>async function generateToken(email, role) {<br>  const token = await new SignJWT({ email, role })<br>    .setProtectedHeader({ alg: &quot;HS256&quot; })<br>    .setIssuedAt()<br>    .setExpirationTime(&quot;2h&quot;)<br>    .sign(jwtSecretKey());<br><br>  return token;<br>}<br><br>function setTokenCookie(cookieJar, token) {<br>  cookieJar.set({ name: &quot;token&quot;, value: token, path: &quot;/&quot; });<br>}<br><br>async function isValidCredentials(email, password) {<br>  const user = await User.findOne({ email });<br><br>  return user &amp;&amp; (await bcrypt.compare(password, user?.password));<br>}</pre><h4>Overview</h4><p>The provided code handles user authentication and token generation for a POST request. It verifies the user’s credentials, generates a JWT (JSON Web Token) containing the user’s email and role, and sets the token as a cookie in the response.</p><h4>Dependencies</h4><p>The code assumes that the necessary dependencies, such as <strong>SignJWT</strong> from the &quot;jose&quot; library, <strong>jwtSecretKey</strong> from &quot;@/lib/auth.js&quot;, <strong>NextResponse</strong> from &quot;next/server&quot;, the <strong>User</strong> model, and <strong>bcryptjs</strong>, are properly imported.</p><h4>User Authentication and Token Generation</h4><p>The <strong>POST</strong> function receives a request object and extracts the email and password from the request body.</p><pre>export async function POST(request) {<br>  const body = await request.json();<br><br>  const { email, password } = body;</pre><p>The function then checks if the credentials are valid by calling the <strong>isValidCredentials</strong> function, which verifies the email and password against the stored user data.</p><pre>if (await isValidCredentials(email, password)) {<br>    // Valid credentials<br>} else {<br>    // Invalid credentials<br>}</pre><p>If the credentials are valid, the function retrieves the user from the database based on the email and determines the user’s role. It then generates a JWT by calling the <strong>generateToken</strong> function, passing the email and role as parameters.</p><pre>const user = await User.findOne({ email });<br><br>const role = user?.role || &quot;user&quot;;<br><br>const token = await generateToken(email, role);</pre><p>After generating the token, the function creates a response using <strong>NextResponse.json</strong> with a success flag. It then calls the <strong>setTokenCookie</strong> function to set the token as a cookie in the response.</p><pre>const response = NextResponse.json({<br>  success: true,<br>});<br><br>setTokenCookie(response.cookies, token);<br><br>return response;</pre><p>If the credentials are invalid, the function returns a response with a success flag set to false.</p><pre>return NextResponse.json({ success: false });</pre><p>The <strong>generateToken</strong> function creates a new <strong>SignJWT</strong> instance, sets the protected header with the algorithm, and adds the email and role as payload data. It sets the issued at (iat) claim and the expiration time (exp) claim. Finally, it signs the token using the JWT secret key obtained from <strong>jwtSecretKey</strong> and returns the generated token.</p><pre>async function generateToken(email, role) {<br>  const token = await new SignJWT({ email, role })<br>    .setProtectedHeader({ alg: &quot;HS256&quot; })<br>    .setIssuedAt()<br>    .setExpirationTime(&quot;2h&quot;)<br>    .sign(jwtSecretKey());<br><br>  return token;<br>}</pre><p>The <strong>setTokenCookie</strong> function sets the token as a cookie in the provided <strong>cookieJar</strong>. It sets the cookie name as &quot;token&quot;, the value as the token itself, and the path as &quot;/&quot;.</p><pre>function setTokenCookie(cookieJar, token) {<br>  cookieJar.set({ name: &quot;token&quot;, value: token, path: &quot;/&quot; });<br>}</pre><p>The <strong>isValidCredentials</strong> function queries the user with the provided email and checks if the stored password matches the provided password using <strong>bcrypt.compare</strong>. It returns <strong>true</strong> if the user exists and the password is valid, otherwise <strong>false</strong>.</p><pre>async function isValidCredentials(email, password) {<br>  const user = await User.findOne({ email });<br><br>  return user &amp;&amp; (await bcrypt.compare(password, user?.password));<br>}</pre><h3>JSON Web Token (JWT) Verification and Permission Check</h3><pre>import { jwtVerify } from &quot;jose&quot;;<br><br>export const jwtSecretKey = () =&gt; {<br>  const secretKey = process.env.JWT_SECRET_KEY;<br><br>  if (!secretKey) {<br>    throw new Error(&quot;JWT secret key is not available&quot;);<br>  }<br><br>  return secretKey;<br>};<br><br>export async function verifyToken(token) {<br>  try {<br>    const decodedToken = await jwtVerify(token, jwtSecretKey());<br>    const isExpired = isTokenExpired(decodedToken);<br><br>    return !isExpired;<br>  } catch (error) {<br>    console.error(&quot;Error while verifying token:&quot;, error);<br>    return false;<br>  }<br>}<br><br>export async function checkPermission(token) {<br>  try {<br>    const decodedToken = await jwtVerify(token, jwtSecretKey());<br>    const userRole = decodedToken.payload.role;<br><br>    return userRole === &quot;admin&quot;;<br>  } catch (error) {<br>    console.error(&quot;Error while checking permission:&quot;, error);<br>    return false;<br>  }<br>}<br><br>function isTokenExpired(decodedToken) {<br>  const currentTime = Math.floor(Date.now() / 1000);<br>  if (decodedToken) {<br>    return decodedToken.payload.exp &lt;= currentTime;<br>  }<br>  return true;<br>}</pre><h4>Overview</h4><p>The provided code consists of functions for verifying a JSON Web Token (JWT) and checking the permission level based on the decoded token. It utilizes the “jose” library for JWT verification and performs various token-related operations.</p><h4>Dependencies</h4><p>The code assumes that the required dependencies, such as <strong>jwtVerify</strong> from the &quot;jose&quot; library, are properly imported.</p><pre>import { jwtVerify } from &quot;jose&quot;;</pre><h4>JWT Secret Key Configuration</h4><p>The <strong>jwtSecretKey</strong> function retrieves the JWT secret key from the environment variable <strong>JWT_SECRET_KEY</strong>. It throws an error if the secret key is not available.</p><pre>export const jwtSecretKey = () =&gt; {<br>  const secretKey = process.env.JWT_SECRET_KEY;<br><br>  if (!secretKey) {<br>    throw new Error(&quot;JWT secret key is not available&quot;);<br>  }<br><br>  return secretKey;<br>};</pre><p>The function returns the secret key as a string.</p><h4>Token Verification</h4><p>The <strong>verifyToken</strong> function verifies the validity of a given token. It attempts to decode the token using <strong>jwtVerify</strong> from the &quot;jose&quot; library and the JWT secret key obtained from <strong>jwtSecretKey</strong>.</p><pre>export async function verifyToken(token) {<br>  try {<br>    const decodedToken = await jwtVerify(token, jwtSecretKey());<br>    const isExpired = isTokenExpired(decodedToken);<br>    <br>    return !isExpired;<br>  } catch (error) {<br>    console.error(&quot;Error while verifying token:&quot;, error);<br>    return false;<br>  }<br>}</pre><p>If the token verification is successful and the token is not expired (based on the <strong>isTokenExpired</strong> function), the function returns <strong>true</strong>. Otherwise, it logs an error and returns <strong>false</strong>.</p><h4>Permission Check</h4><p>The <strong>checkPermission</strong> function verifies if the given token has the necessary permission level (e.g., &quot;admin&quot;). It decodes the token using <strong>jwtVerify</strong> and the JWT secret key obtained from <strong>jwtSecretKey</strong>, and then checks the <strong>role</strong> field in the token&#39;s payload.</p><pre>export async function checkPermission(token) {<br>  try {<br>    const decodedToken = await jwtVerify(token, jwtSecretKey());<br>    const userRole = decodedToken.payload.role;<br><br>    return userRole === &quot;admin&quot;;<br>  } catch (error) {<br>    console.error(&quot;Error while checking permission:&quot;, error);<br>    return false;<br>  }<br>}</pre><p>If the permission check is successful (i.e., the <strong>role</strong> field is &quot;admin&quot;), the function returns <strong>true</strong>. Otherwise, it logs an error and returns <strong>false</strong>.</p><h4>Token Expiration Check</h4><p>The <strong>isTokenExpired</strong> function checks if a decoded token is expired by comparing the token&#39;s <strong>exp</strong> (expiration) claim with the current time.</p><pre>function isTokenExpired(decodedToken) {<br>  const currentTime = Math.floor(Date.now() / 1000);<br>  if (decodedToken) {<br>    return decodedToken.payload.exp &lt;= currentTime;<br>  }<br>  return true;<br>}</pre><p>If the <strong>decodedToken</strong> is available, it compares the expiration timestamp (<strong>exp</strong>) with the current time (<strong>currentTime</strong>). If the token has already expired, the function returns <strong>true</strong>. If the <strong>decodedToken</strong> is not available (e.g., invalid or missing token), it assumes the token is expired and returns <strong>true</strong> as well.</p><h3>User Model Schema</h3><pre>import mongoose from &quot;mongoose&quot;;<br><br>const UserSchema = new mongoose.Schema({<br>  name: {<br>    type: String,<br>    required: true,<br>    maxlength: 60,<br>  },<br>  email: {<br>    type: String,<br>    required: true,<br>    maxlength: 60,<br>    unique: true,<br>  },<br>  password: {<br>    type: String,<br>    required: true,<br>    maxlength: 60,<br>  },<br>  shipping_address: {<br>    type: mongoose.Schema.Types.Mixed,<br>    required: true,<br>  },<br>  role: {<br>    type: String,<br>    enum: [&quot;admin&quot;, &quot;user&quot;],<br>    default: &quot;user&quot;,<br>  },<br>});<br><br>const User = mongoose.models.User || mongoose.model(&quot;User&quot;, UserSchema);<br><br>export default User;</pre><h4>Overview</h4><p>The provided code defines a MongoDB schema for the User model using Mongoose. It specifies the fields, data types, and validation rules for each field.</p><h4>Dependencies</h4><p>The code assumes that the <strong>mongoose</strong> library is properly imported.</p><pre>import mongoose from &quot;mongoose&quot;;</pre><h4>User Schema Definition</h4><p>The code defines the User schema using the <strong>mongoose.Schema</strong> class and specifies the fields and their properties.</p><pre>const UserSchema = new mongoose.Schema({<br>  name: {<br>    type: String,<br>    required: true,<br>    maxlength: 60,<br>  },<br>  email: {<br>    type: String,<br>    required: true,<br>    maxlength: 60,<br>    unique: true,<br>  },<br>  password: {<br>    type: String,<br>    required: true,<br>    maxlength: 60,<br>  },<br>  shipping_address: {<br>    type: mongoose.Schema.Types.Mixed,<br>    required: true,<br>  },<br>  role: {<br>    type: String,<br>    enum: [&quot;admin&quot;, &quot;user&quot;],<br>    default: &quot;user&quot;,<br>  },<br>});</pre><p>The User schema consists of the following fields:</p><ul><li><strong>name</strong>: Represents the user&#39;s name. It is of type <strong>String</strong>, required, and has a maximum length of 60 characters.</li><li><strong>email</strong>: Represents the user&#39;s email address. It is of type <strong>String</strong>, required, has a maximum length of 60 characters, and must be unique.</li><li><strong>password</strong>: Represents the user&#39;s password. It is of type <strong>String</strong>, required, and has a maximum length of 60 characters.</li><li><strong>shipping_address</strong>: Represents the user&#39;s shipping address. It is of type <strong>Mixed</strong>, required, and can hold any type of value.</li><li><strong>role</strong>: Represents the user&#39;s role. It is of type <strong>String</strong> and can have the values &quot;admin&quot; or &quot;user&quot;. The default value is set to &quot;user&quot;.</li></ul><h4>User Model</h4><p>The code creates the User model using <strong>mongoose.model</strong> and assigns it to the <strong>User</strong> variable.</p><pre>const User = mongoose.models.User || mongoose.model(&quot;User&quot;, UserSchema);</pre><p>The <strong>User</strong> model is either retrieved from the existing models or created as a new model if it doesn&#39;t exist.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d044c804c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customizing the Login Page of Keycloak Docker Image]]></title>
            <link>https://medium.com/@oruchan.asar/customizing-the-login-page-of-keycloak-docker-image-eefac226fd7a?source=rss-b1e1ec3e853d------2</link>
            <guid isPermaLink="false">https://medium.com/p/eefac226fd7a</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[keycloak]]></category>
            <dc:creator><![CDATA[Oruçhan Asar]]></dc:creator>
            <pubDate>Sat, 04 Feb 2023 21:31:32 GMT</pubDate>
            <atom:updated>2023-02-05T07:53:22.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*rglZVoiipkepUyzj-2pT5A.png" /></figure><p>In this article, I will show you how to customize the login page of Keycloak using a Docker image. Here are the steps to get started:</p><ol><li>Create and run a Docker container for Keycloak:</li></ol><pre>docker run -p 8080:8080 --name keycloak -e KEYCLOAK_USER=admin -e KEYCLOAK_PASSWORD=admin jboss/keycloak</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j0C5yYsgcb7Z-xUcF6xycw.png" /></figure><p>2. Access the Keycloak container by visiting <a href="http://localhost:8080/"><strong>http://localhost:8080/</strong></a> in your browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kLjhAjeKZ9Azf_hCHAOC_w.png" /></figure><p>3. Log in to the administration console using the credentials <strong>admin</strong> and <strong>admin</strong>.</p><p>4. Navigate to the <strong>Realm Settings</strong> page and select the <strong>Themes</strong> option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aRrfz0UmMEkAO5AD8bRuKA.png" /></figure><p>We will add new theme here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-fHPnszdnx7BRNTbZgeFYg.png" /></figure><p>5. Download and extract the Keycloak distribution package (<a href="https://github.com/keycloak/keycloak/releases/download/20.0.3/keycloak-20.0.3.zip">keycloak-20.0.3.zip</a>) from the GitHub repository.</p><p>After extracting you should have a directory named keycloak-20.0.3.</p><p>While creating custom themes, especially when overriding templates, it may be useful to use the built-in templates as a reference. These can be found within the theme directory of ../lib/lib/main/org.keycloak.keycloak-themes-20.0.3.jar, which can be opened using any standard ZIP archive tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oenl1vOU999Knt6Asmc8mw.png" /></figure><p>6. Copy the <strong>keycloak</strong> folder from the <strong>themes</strong> directory within the distribution package to a location where you want to work on it.</p><p>7. Open the <strong>keycloak</strong> folder with an IDE of your choice and make changes to the CSS and images as desired.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*14wcPoQM7irvwGyJFg2aTQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*H_siYxZHK1dSvjNgXJ2y1Q.png" /></figure><p>8. To add the custom theme to the Keycloak container, follow these steps:</p><pre>docker exec -it &lt;CONTAINER_ID&gt; bin/bash</pre><ul><li>Create a directory for your theme in the container</li></ul><pre>cd /opt/jboss/keycloak/themes<br>mkdir &lt;CUSTOM_THEME&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xr9X8N5a6ahJH3PlO7VxsQ.png" /></figure><ul><li>Copy the changed keycloak theme into the docker continer</li></ul><pre>docker cp keycloak/. &lt;CONTAINER_ID&gt;:/opt/jboss/keycloak/themes/&lt;CUSTOM_THEME&gt;<br>docker restart &lt;CONTAINER_ID&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZLa48AHRs4IiDAwsSnVXWA.png" /></figure><p>9. Log in to the administration console again and select your custom theme.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LwnmJh6ipcYS67NPjJypqA.png" /></figure><p>I hope this guide will help you in customizing the login page of your Keycloak Docker image. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eefac226fd7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>