<?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 Mesut KILINCASLAN on Medium]]></title>
        <description><![CDATA[Stories by Mesut KILINCASLAN on Medium]]></description>
        <link>https://medium.com/@mesutas.dev?source=rss-b1c025774bd9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wr_yvZ9XBnknm0JEao2L3A.jpeg</url>
            <title>Stories by Mesut KILINCASLAN on Medium</title>
            <link>https://medium.com/@mesutas.dev?source=rss-b1c025774bd9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 15:47:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mesutas.dev/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[Private AI Agent vs ChatGPT]]></title>
            <link>https://medium.com/@mesutas.dev/private-ai-agent-vs-chatgpt-33cd6a18fd40?source=rss-b1c025774bd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/33cd6a18fd40</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai-agent-development]]></category>
            <category><![CDATA[secure-and-private-ai]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Mesut KILINCASLAN]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 11:24:23 GMT</pubDate>
            <atom:updated>2026-11-22T09:44:34.440Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mQlJbwlvlU989U7W" /><figcaption>Private AI Agent vs ChatGPT</figcaption></figure><p>If you already pay for ChatGPT Business, does your company still need a separate AI agent? ChatGPT is where your people work with AI. A private AI agent is a worker your business builds, scopes and deploys into its own product, channels and processes.</p><p>The full comparison covers:</p><ul><li>whether ChatGPT is private for business use</li><li>how the two differ on knowledge scope, tool access, network, retention and model choice</li><li>whether custom GPTs already do this</li><li>when to build your own agent on OpenAI’s developer stack</li><li>which option your business needs</li></ul><p>Read the full comparison: <a href="https://commt.co/blog/private-ai-agent-vs-chatgpt">https://commt.co/blog/private-ai-agent-vs-chatgpt</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33cd6a18fd40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Private AI Agents: What They Are & How to Choose One]]></title>
            <link>https://medium.com/@mesutas.dev/private-ai-agents-what-they-are-how-to-choose-one-620d049a376f?source=rss-b1c025774bd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/620d049a376f</guid>
            <category><![CDATA[secure-and-private-ai]]></category>
            <category><![CDATA[ai-agent-development]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[private-ai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Mesut KILINCASLAN]]></dc:creator>
            <pubDate>Wed, 14 Oct 2026 09:03:57 GMT</pubDate>
            <atom:updated>2026-11-22T09:38:50.181Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*azE4Lh8TGWr5hngb" /><figcaption>Private AI Agents</figcaption></figure><p>A private AI agent is one whose knowledge, tools, network access and data retention are each scoped on purpose by the organization running it. Self-hosting helps. So does a model that does not train on your data. Neither one alone makes an agent private.</p><p>The full guide covers:</p><ul><li>the four boundaries that define a private AI agent</li><li>self-hosted, private cloud and managed platform options compared</li><li>example tools for each type</li><li>why “we don’t train on your data” is not enough on its own</li><li>nine questions to ask a vendor before trusting it with sensitive data</li></ul><p>Read the full guide: <a href="https://commt.co/blog/what-is-a-private-ai-agent">https://commt.co/blog/what-is-a-private-ai-agent</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=620d049a376f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Control What an AI Agent Can Access]]></title>
            <link>https://medium.com/@mesutas.dev/how-to-control-what-an-ai-agent-can-access-ab3ef5e51da6?source=rss-b1c025774bd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab3ef5e51da6</guid>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[ai-privacy]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[data-privacy]]></category>
            <category><![CDATA[private-ai]]></category>
            <dc:creator><![CDATA[Mesut KILINCASLAN]]></dc:creator>
            <pubDate>Fri, 09 Oct 2026 06:31:01 GMT</pubDate>
            <atom:updated>2026-11-22T13:42:29.248Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tpZWdNByyLdKW4Bq" /><figcaption>What an AI Agent Can Access</figcaption></figure><p>An AI agent can reach the open internet, internal tools and connectors, a company’s knowledge bases and every record of what it did. None of that should be inherited from a platform’s defaults. Controlling what an agent can access means setting each boundary on purpose, per agent.</p><p>The full guide covers:</p><ul><li>network access: when an agent should reach the internet</li><li>tools and connectors: which tools an agent may call</li><li>knowledge and RAG access: how to stop an agent reading the wrong data</li><li>data retention: what gets kept and for how long</li><li>how the four boundaries work together</li></ul><p>Read the full guide: <a href="https://commt.co/blog/limiting-agent-reach">https://commt.co/blog/limiting-agent-reach</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab3ef5e51da6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Treating Claude Code Like ChatGPT. I Built It a Second Brain in Obsidian.]]></title>
            <link>https://medium.com/@mesutas.dev/stop-treating-claude-code-like-chatgpt-i-built-it-a-second-brain-in-obsidian-66b1167e74c6?source=rss-b1c025774bd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/66b1167e74c6</guid>
            <category><![CDATA[obsidian]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[second-brain]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Mesut KILINCASLAN]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 15:42:42 GMT</pubDate>
            <atom:updated>2026-08-31T14:46:37.537Z</atom:updated>
            <content:encoded><![CDATA[<p>How a solo founder turned a markdown vault into a persistent memory system for AI agents, and the skills that compound on top.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nKCoC_8n4xCLknGlGu-CrA.png" /><figcaption>claude-code-second-brain</figcaption></figure><h3>How I found this method</h3><p>In early April 2026, Andrej Karpathy posted a tweet I cannot stop thinking about.</p><blockquote>&gt; LLM Knowledge Bases. Something I’m finding very useful recently: using LLMs to build personal knowledge bases for various topics of research interest.</blockquote><blockquote>&gt; — Andrej Karpathy, [April 3, 2026](<a href="https://x.com/karpathy/status/2039805659525644595">https://x.com/karpathy/status/2039805659525644595</a>)</blockquote><p>This was not new in spirit. Tiago Forte sold the Building a Second Brain methodology to half the productivity internet. Zettelkasten goes back to a German sociologist with index cards in the 1960s. Both were about humans remembering things. Karpathy flipped the same idea for LLMs.</p><p>I read the tweet on a Friday. I rebuilt my workflow that weekend. Two months in, the system runs the company.</p><p>This is what I built, why it works and the skills and plugins that compound on top.</p><h3>Who I am, why this matters</h3><p>I am a solopreneur, run my company alone.</p><p>One founder, one keyboard, one terminal. No engineers, no PM, no marketing hire. Claude Code is the team. Obsidian is the office.</p><p>Six months ago I used Claude Code like ChatGPT. Open the session, paste the file, explain what we did yesterday, watch the model do good work, close the terminal. Tomorrow, repeat.</p><p>The model never remembered. I did not realize how expensive that was until I measured it.</p><h3>The Amnesia Problem (and what it costs)</h3><p>Default Claude Code is stateless. Every session starts cold. Nothing in the previous conversation survives.</p><p>This is fine for one-off chats. It is brutal for running a company.</p><p>The cost is three-shaped.</p><p><strong>Time</strong>. I re-explained the project map, recent decisions, and open tasks every morning. Conservatively, fifteen minutes per session, three sessions a day. That is forty-five minutes of pure context bootstrap, every working day.</p><p><strong>Tokens</strong>. Re-pasted context burns input tokens. Long history pastes blow past the prompt cache TTL, which means cache miss, which means the model re-reads everything from scratch. Token throughput goes up, latency goes up, the bill goes up and the model has not done any new work yet.</p><p><strong>Decision drift.</strong> Worst of the three. Without persistent memory, the model has no way to remember we already decided against a given pattern. So it proposes it again. I either catch it (cognitive tax) or I do not (wrong direction).</p><p>The fix is not a bigger context window. The fix is persistent context the model reads at session boot and writes back to during the session.</p><h3>The three memory layers</h3><p>I borrowed the structure of Claude Code itself. It already supports three layers of context. Most users only use one.</p><pre><br>┌──────────────────────────────────────────────┐<br>│  Layer 1: GLOBAL                             │<br>│  ~/.claude/CLAUDE.md                         │<br>│  Loaded for every project, every session.    │<br>│  Preferences, vault path, write rules.       │<br>└────────────────┬─────────────────────────────┘<br>                 │<br>                 ▼<br>┌──────────────────────────────────────────────┐<br>│  Layer 2: PROJECT                            │<br>│  &lt;project&gt;/CLAUDE.md                         │<br>│  Loaded when working in that project.        │<br>│  Voice rules, file map, conventions.         │<br>└────────────────┬─────────────────────────────┘<br>                 │<br>                 ▼<br>┌──────────────────────────────────────────────┐<br>│  Layer 3: VAULT                              │<br>│  Obsidian markdown files.                    │<br>│  Decisions, tasks, updates, patterns.        │<br>│  Read on demand, written on outcome.         │<br>└──────────────────────────────────────────────┘<br></pre><p>Layer 1 is the contract. It says: here is where the vault lives, here is when to write to it, here is how I want decisions formatted, here are the banned phrases.</p><p>Layer 2 narrows the contract. Per project: which sub-voice, which folder structure, which files mirror to which central index.</p><p>Layer 3 is the actual second brain. Plain markdown files in Obsidian. Read when needed. Written when something happens worth remembering.</p><h3>The vault</h3><p>The vault folder layout looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*s3MWJjEIVZOW_8mLDR2YVQ.png" /><figcaption>obsidian-vault</figcaption></figure><pre>~/Programming/Claude Memory/<br>├── MEMORY-INDEX.md          ← session boot reads first<br>├── TASKS.md                 ← central task board<br>├── Projects/<br>│   ├── Podwist/<br>│   │   ├── overview.md<br>│   │   ├── decisions.md<br>│   │   ├── tasks.md<br>│   │   └── updates/<br>│   ├── ClientX/<br>│   └── ...<br>└── preferences.md</pre><p><em>`MEMORY-INDEX.md`</em> is the table of contents. `<em>TASKS.md`</em> is one row per open task across every project. `<em>Projects/{name}/`</em> has overview, decisions, tasks and a folder of dated updates.</p><p>The format of a decision entry is fixed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q_R20U9uywX6LmgBNVaeaQ.png" /><figcaption>obsidian-vault-second-brain</figcaption></figure><pre>## 2026-06-15 — Stop using SaaS PKM, move to vault<br><br>**Status:** decided<br>**Tags:** #arch #workflow<br><br>### Context<br>SaaS tools (Notion, Linear) lock my data behind APIs the LLM cannot read directly.<br><br>### Decision<br>Move everything to plain markdown in an Obsidian vault. Wikilinks for cross-refs. Git for history.<br><br>### Consequences<br>Lose Notion&#39;s UI polish. Gain LLM-readable context, free hosting, offline access, full ownership.</pre><p>Why Obsidian and not Notion, Linear, or anything else.</p><p>Markdown is the LLM’s native tongue. No API, no auth dance, no scraping. The model reads files. Wikilinks let me cross-reference notes without thinking about IDs. The graph view turns the vault into a visual map of how the company thinks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kfirFomYrdP-oCfkjVFJiw.png" /><figcaption>obsidian-graph-second-brain</figcaption></figure><p>That graph is the second brain.</p><h3>The skills stack</h3><p>Skills are installable behaviors for Claude Code. Plugins are bundles of skills and tools. Both extend the default behavior beyond what comes out of the box.</p><p>I run ten that pay rent. Here is the trigger map.</p><pre>USER INPUT<br>    │<br>    ├── &quot;/brainstorm idea&quot;     → superpowers:brainstorming<br>    ├── &quot;/gsd next&quot;            → gsd (project + task mgmt)<br>    ├── &quot;/caveman&quot;             → caveman (terse output)<br>    ├── &quot;write LinkedIn post&quot;  → marketing-skills:copywriting<br>    ├── &quot;/graphify .&quot;          → graphify (project → graph)<br>    ├── &quot;edit vault file&quot;      → obsidian-cli<br>    ├── &quot;build component&quot;      → frontend-design<br>    ├── &quot;review UX of screen&quot;  → ui-ux-pro-max<br>    ├── &quot;design API&quot;           → system-design<br>    └── &quot;write brand post&quot;     → podwist-brand-voice (custom)<br>              │<br>              ▼<br>       Skill loads,<br>       overrides defaults,<br>       executes pattern.</pre><p>Quick tour.</p><ol><li><strong>superpowers:brainstorming:</strong> Vague idea in, structured spec out. Forces a design before any code. Saves me from building the wrong thing all weekend.</li><li><strong>gsd</strong>: Get-stuff-done family. `gsd:new-project`, `gsd:plan-phase`, `gsd:next`, `gsd:complete-milestone`. Replaces a PM. Phases become files. Tasks become rows.</li><li><strong>caveman:caveman:</strong> Cut the fluff. Fragments instead of paragraphs, code stays byte-perfect. I read three times faster.</li><li><strong>marketing-skills:</strong> Copywriting, content strategy, SEO audits, page CRO, email sequences. A marketing department compressed into invokable skills.</li><li><strong>obsidian-cli:</strong> Lets the model read and write vault files from inside a session. Without this, the vault is a one-way archive. With it, the vault is alive.</li><li><strong>graphify:</strong> Run `/graphify .` and any project folder becomes a searchable knowledge graph: code, SQL, docs, even PDFs. Then I ask *”what connects X to Y?”* from the terminal without re-reading the codebase. Graphify maps the code, the vault maps the thinking.</li><li><strong>frontend-design:</strong> Design system reasoning, component patterns, accessibility checks. The solo founder is also the solo designer.</li><li><strong>ui-ux-pro-max:</strong> Full UX critique. Takes a screen, returns a six-pillar audit. Catches the stuff I stop seeing after staring at the same screen for a week.</li><li><strong>system-design:</strong> Architecture patterns, decomposition, API design, scaling decisions. The principal engineer I do not employ.</li><li><strong>podwist-brand-voice:</strong> A custom skill I wrote myself. Encodes the brand voice rules, banned phrases, sub-voice splits, and format defaults. Every post written touches this skill first.</li></ol><p>That last one matters most. You can write your own skills. Once you do, your accumulated taste compounds. The model gets better at sounding like you with every rule you add.</p><p>Closing the loop on quality: `code-review`, `simplify`, `verify`, `run`. The engineering team I do not hire, on call from the terminal.</p><h3>How it compounds</h3><p>A concrete week.</p><p>Monday I ship a feature. The model logs the decision in `<em>Projects/Podwist/decisions.md</em>`. The reasoning includes the alternative we rejected and why.</p><p>Wednesday I open an unrelated project. We hit the same architectural fork. The model reads the decision from Monday, surfaces the reasoning, and references it by date. I do not re-think the trade-off. I extend the prior thinking.</p><p>Friday the marketing engine asks for a LinkedIn post. The model loads the brand voice skill and writes in the right register without me reminding it of the banned phrases.</p><p>Sunday I take notes on a customer call. The next morning the model reads those notes alongside the open tasks, sees the gap between what the customer asked for and what is on the roadmap and proposes the right next task.</p><p>The math of the solo company changes. One founder plus persistent memory is not three employees with Slack history. It is something else. The team does not forget. The decisions do not drift. The voice does not slip.</p><p>I do not onboard new context every morning. I extend it.</p><h3>Closing</h3><p>Claude Code without memory is rented intelligence. You pay per session, you start over each time, and nothing you teach it lasts.</p><p>With a vault, it is an asset. Setup is a weekend. Compounding is forever.</p><p>Two things before you go.</p><p><strong>What is in your vault?</strong> I am genuinely curious which folders other solo builders track. Drop a structure in the comments. The good ones get stolen and credited.</p><p><strong>If this was useful</strong>, I share more about building AI-native, engineering, solopreneurship and the challenges I experience along the way. Follow me on X at <a href="http://twitter.com/mesutas_dev"><strong>@mesutas_dev</strong></a> or here on Medium and come along for the journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66b1167e74c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Turn Slack Into a Feedback Tracker (No Extra Tools Needed)]]></title>
            <link>https://medium.com/@mesutas.dev/how-to-turn-slack-into-a-feedback-tracker-no-extra-tools-needed-cf3fd9794da8?source=rss-b1c025774bd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf3fd9794da8</guid>
            <category><![CDATA[feedback]]></category>
            <category><![CDATA[feedback-management]]></category>
            <category><![CDATA[slackbot]]></category>
            <category><![CDATA[slack]]></category>
            <category><![CDATA[slack-tips-and-tricks]]></category>
            <dc:creator><![CDATA[Mesut KILINCASLAN]]></dc:creator>
            <pubDate>Fri, 25 Jul 2025 11:37:54 GMT</pubDate>
            <atom:updated>2026-08-31T14:47:00.669Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DPfLR78Jo49_GrRvujAG6Q.png" /><figcaption>How to turn slack into feedback tracker</figcaption></figure><p>Let’s be honest, managing team feedback can quickly turn into digital chaos. Not long ago, our team found ourselves struggling to stay on top of feedback that was scattered everywhere. Some came through Slack messages, others were buried in Google Docs and a few just… disappeared into spreadsheet oblivion.</p><p>We knew we needed a centralized system something where we could see who submitted feedback, what it was about, attach related assets, assign ownership and track progress. That’s when our PM stepped up with a game-changing idea: Slack Feedback Tracker.</p><h3>One Tool, Endless Organization</h3><p>Instead of hunting down a new app or subscribing to another tool, he figured; why not just use what we already use all day? Slack.</p><p>Turns out, Slack’s <strong>Feedback Tracker template</strong> is exactly what we needed. It lets us collect feedback from direct messages, web forms or even app integrations and track everything — status updates, comments, follow-ups — right in Slack.</p><p>Let me walk you through how we set it up.</p><h3>🚀 Step-by-Step: How to Create a Feedback Tracker in Slack</h3><h3>1. Create a Channel from a Template</h3><ul><li>Click <strong>More</strong> in the Slack sidebar.</li><li>Select <strong>Channel</strong> → Click <em>Show all templates</em>.</li><li>Choose <strong>Feedback intake and triage</strong> from the gallery.</li><li>Name it something like #feedback-tracker.</li><li>Hit <strong>Create</strong> and Slack will spin up a pre-built channel complete with intake forms and structure.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CH-985mAdZRVMkDw_QfZCg.png" /><figcaption>slack-feedback-tracker</figcaption></figure><h3>2. Add a Template to an Existing Channel</h3><p>Already have a channel in use? No problem.</p><ul><li>Go to the existing channel.</li><li>Click the three dots at the top.</li><li>Select <strong>Templates</strong> → Browse and apply the feedback template.</li></ul><p>Now, everyone who wants to send feedback in this channel has to follow the built-in form, which keeps things clean and organized. Bonus: discussions can still happen within each thread, so nothing gets lost in the noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eWPmBmB_NoXvYSj9ZUqhUQ.png" /><figcaption>slack-feedback-tracker-form</figcaption></figure><h3>💡 Pro Tip: Connect Feedback From Your Apps</h3><p>Want to automate even further? You can connect your app or website to Slack using this format. That way, feedback gets submitted in the correct template instantly, keeping everything centralized and easy to track.</p><p>With just a few clicks, we turned Slack into a fully-functional feedback management system — no new tools, no extra costs. Just better organization, better visibility and way less stress.</p><p>If you’ve been struggling with scattered team feedback, I highly recommend giving this a try.</p><p><strong>If this was useful</strong>, I share more about building AI-native, engineering, solopreneurship and the challenges I experience along the way. Follow me on X at <a href="http://twitter.com/mesutas_dev"><strong>@mesutas_dev</strong></a> or here on Medium and come along for the journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf3fd9794da8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using GraphQL with React Native: Best Practices for Efficient Data Fetching]]></title>
            <link>https://medium.com/@mesutas.dev/using-graphql-with-react-native-best-practices-for-efficient-data-fetching-a0a42d01c671?source=rss-b1c025774bd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0a42d01c671</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[graphql-apollo-server]]></category>
            <category><![CDATA[react-native-development]]></category>
            <category><![CDATA[apollo-client]]></category>
            <dc:creator><![CDATA[Mesut KILINCASLAN]]></dc:creator>
            <pubDate>Sat, 19 Oct 2024 14:22:51 GMT</pubDate>
            <atom:updated>2026-08-31T14:47:25.682Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oWO_NuYiYh0kovEsQaSIuw.png" /><figcaption>Using GraphQL with React Native</figcaption></figure><h3>1. Introduction</h3><p>In the realm of mobile development, achieving efficient data fetching is paramount for optimal app performance and user experience. <strong>GraphQL</strong> and <strong>React Native</strong> are two powerful technologies that, when combined, can significantly enhance data management and UI responsiveness. GraphQL is a query language for your API and a server-side runtime for executing queries using a type system defined for your data. React Native, on the other hand, is a framework for building native apps using React, allowing developers to write applications for iOS and Android using a single codebase.</p><h3>2. Setting Up Apollo Client</h3><p>To integrate GraphQL with React Native, one popular approach is using the <strong>Apollo Client</strong>. Apollo Client is a comprehensive state management library for JavaScript that enables you to manage both local and remote data with GraphQL.</p><p>To get started, install the necessary packages:</p><pre>npm install @apollo/client graphql</pre><p>Next, set up Apollo Client in your React Native application:</p><pre>import { ApolloClient, InMemoryCache, ApolloProvider } from &#39;@apollo/client&#39;;<br> <br>const client = new ApolloClient({<br>    uri: &#39;&lt;https://your-graphql-endpoint.com/graphql&gt;&#39;,<br>    cache: new InMemoryCache() <br>});<br><br>const App = () =&gt; (<br>    &lt;ApolloProvider client={client}&gt;<br>        &lt;YourRootComponent /&gt;<br>    &lt;/ApolloProvider&gt; <br>);</pre><p>This setup initializes Apollo Client with your GraphQL endpoint and integrates it into your React Native app using the ApolloProvider component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IFwxFhb5OAYi65nWvdOrmw.jpeg" /></figure><h3>3. Writing Efficient GraphQL Queries</h3><p>Writing efficient GraphQL queries is crucial for reducing load times and improving app responsiveness. Here are some best practices:</p><p><strong>Fragment Usage</strong>: Reuse common fields across multiple queries by using fragments.</p><pre>fragment UserDetails on User {<br>    id<br>    name<br>    email<br>} <br>query GetUser($id: ID!) {<br>    user(id: $id) {<br>        ...UserDetails <br>    }<br>} <br>query GetUsers {<br>    users {<br>        ...UserDetails <br>    }<br>}</pre><p>Pagination: Use cursor-based pagination to efficiently fetch large lists of data.</p><pre>query GetPaginatedUsers($first: Int, $after: String) {<br>    users(first: $first, after: $after) {<br>        edges {<br>            node {<br>                id    <br>                name    <br>                email  <br>            } <br>        }<br>        pageInfo {<br>            endCursor<br>            hasNextPage<br>        }<br>    }<br>}</pre><h3>4. Handling Local State Management</h3><p>Apollo Client also allows you to manage local state alongside remote data. Here’s how you can define a local schema and resolvers:</p><pre>const client = new ApolloClient({<br>    uri: &#39;&lt;https://your-graphql-endpoint.com/graphql&gt;&#39;,<br>    cache: new InMemoryCache(),<br>    resolvers: {<br>        Mutation: {<br>            updateLocalState: (_, { newState }, { cache }) =&gt; {<br>                cache.writeData({ data: { localState: newState } });<br>                return null;   <br>            }<br>        }<br>    }<br>});</pre><p>This setup enables you to manage local state using the same GraphQL queries and mutations you use for remote data.</p><h3>5. Best Practices for Optimizing Data Fetching</h3><p>To optimize data fetching, consider the following best practices:</p><p><strong>Batching Queries</strong>: Use Apollo Link to batch multiple queries into a single network request.</p><pre>import { BatchHttpLink } from &#39;@apollo/client/link/batch-http&#39;;<br><br>const httpLink = new BatchHttpLink({<br>    uri: &#39;&lt;https://your-graphql-endpoint.com/graphql&gt;&#39;,<br>    batchInterval: 10<br>});<br><br>const client = new ApolloClient({<br>    link: httpLink,<br>    cache: new InMemoryCache()<br>});</pre><p><strong>Caching</strong>: Leverage Apollo Client’s caching capabilities to reduce redundant network requests.</p><ul><li><strong>Normalized Cache</strong>: Automatically normalizes and caches data based on your queries.</li><li><strong>Cache Updates</strong>: Manually update the cache after mutations to ensure UI consistency.</li></ul><pre>client.mutate({<br>    mutation: UPDATE_USER,<br>    variables: { id, name, email },<br>    update: (cache, { data: { updateUser } }) =&gt; {<br>        const data = cache.readQuery({ query: GET_USERS });<br>        cache.writeQuery({<br>            query: GET_USERS,<br>            data: { <br>                ...data, <br>                users: data.users.map(user =&gt; <br>                    user.id === updateUser.id ? updateUser : user <br>                ) <br>            } <br>        });<br>    }<br>});</pre><h3>6. Case Studie</h3><p><strong>Case Study</strong>: A leading e-commerce platform successfully implemented GraphQL in their React Native application. By switching from REST to GraphQL, they reduced data over-fetching and improved app performance. The outcome was a 30% improvement in load times, an enhanced user experience and streamlined state management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JCZwVl9byax3WOkJZ5WQqA.png" /></figure><h3>7. Conclusion</h3><p>Combining GraphQL with React Native can significantly enhance the performance and maintainability of your mobile applications. By implementing best practices such as efficient querying, state management and caching, developers can create more responsive and scalable applications. Leveraging the power of GraphQL and Apollo Client leads to optimal performance and an improved user experience, ensuring your app stands out in the competitive mobile landscape.</p><p>By following these guidelines, developers can ensure efficient data fetching in their React Native applications, fully utilizing the capabilities of GraphQL and Apollo Client for superior performance.</p><p>Until the next post happy coding fellas 😉.</p><p><strong>If this was useful</strong>, I share more about building AI-native, engineering, solopreneurship and the challenges I experience along the way. Follow me on X at <a href="http://twitter.com/mesutas_dev"><strong>@mesutas_dev</strong></a> or here on Medium and come along for the journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0a42d01c671" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native Migration: Unlocking Performance Gains with Fabric and TurboModules]]></title>
            <link>https://medium.com/@mesutas.dev/react-native-migration-unlocking-performance-gains-with-fabric-and-turbomodules-1861abae5bf9?source=rss-b1c025774bd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/1861abae5bf9</guid>
            <category><![CDATA[performance-improvement]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[app-migration]]></category>
            <category><![CDATA[legacy-modernization]]></category>
            <category><![CDATA[legacy-code]]></category>
            <dc:creator><![CDATA[Mesut KILINCASLAN]]></dc:creator>
            <pubDate>Thu, 10 Oct 2024 10:31:13 GMT</pubDate>
            <atom:updated>2026-08-31T14:48:05.449Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2EZ8uqPGRApaUaxS47OOEw.png" /><figcaption>React Native Migration: Unlocking Performance Gains with Fabric and TurboModules</figcaption></figure><p>In the fast-paced world of mobile app development, staying up-to-date with the latest technologies is crucial for maintaining performance, scalability and user satisfaction. React Native, a popular framework for building cross-platform mobile apps, has introduced a new architecture featuring Fabric and TurboModules. This new architecture is designed to enhance performance and flexibility, making it a compelling upgrade for developers. However, migrating a legacy React Native app to this new architecture presents its own set of challenges. In this article, we will explore these challenges, common pitfalls, solutions and the potential performance gains from a successful migration, while also learning from real-world experiences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LmVB38Lj198fqAoDyTsY1A.png" /><figcaption>React Native Performance Improvement</figcaption></figure><h3>Introduction to React Native’s New Architecture</h3><p>React Native’s new architecture marks a significant evolution in the framework’s capabilities. Fabric, the new rendering system, improves the UI layer by enabling more efficient rendering and layout calculations. This leads to smoother animations and a more responsive user interface. On the other hand, TurboModules optimize the way native modules are loaded and accessed, reducing startup times and improving overall app performance. These advancements promise substantial improvements, but transitioning to this new architecture requires careful consideration and planning.</p><h3>Challenges in Migrating a Legacy React Native App</h3><ol><li>Compatibility Issues:<br>- <strong>Problem</strong>: Ensuring that existing code and third-party libraries are compatible with Fabric and TurboModules.<br>- <strong>Solution</strong>: Incrementally test and migrate parts of the application to the new architecture, starting with less critical modules.</li><li>Performance Bugs:<br>- <strong>Problem</strong>: Potential performance regressions during the migration phase.<br>- <strong>Solution</strong>: Closely monitor performance metrics and use profiling tools to identify and address performance bottlenecks.</li><li>Complexity of Native Code:<br>- <strong>Problem</strong>: Migrating custom native code and modules to support the new architecture.<br>- <strong>Solution</strong>: Refactor and rewrite native modules to align with TurboModules requirements.</li><li>Documentation and Learning Curve:<br>- <strong>Problem</strong>: Limited documentation and the steep learning curve associated with new APIs and architecture paradigms.<br>- <strong>Solution</strong>: Utilize community resources, official documentation, and actively participate in developer forums.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qQy0ePVVx5-HAhi9KTvW0g.png" /><figcaption>Legacy React Native App Migration</figcaption></figure><h3>Common Pitfalls</h3><p>Several common pitfalls can hinder a migration project. A prevalent mistake is assuming that all existing code and libraries will seamlessly integrate with the new architecture. This assumption can lead to unforeseen compatibility issues. Additionally, inadequate testing of the app in various environments and scenarios post-migration can result in undetected bugs and performance issues. Lastly, underestimating the complexity of the migration can lead to inadequate allocation of time and resources, prolonging the transition process.</p><h3>Migration Strategies</h3><ol><li><strong>Incremental Migration</strong>:<br>- Start with non-critical components to ensure stability.<br>- Gradually migrate UI components to use Fabric.<br>- Convert custom native modules to TurboModules in stages.</li><li><strong>Testing</strong>:<br>- Comprehensive testing using unit tests, integration tests, and end-to-end tests.<br>- Utilize React Native’s testing libraries and tools.</li><li><strong>Performance Monitoring</strong>:<br>- Use profiling tools like React DevTools and native profilers.<br>- Regularly monitor performance metrics and address any regressions.</li><li><strong>Community and Support</strong>:<br>- Engage with the React Native community for support and shared experiences.<br>- Follow updates from the React Native core team for best practices and tutorials.</li></ol><h3>Potential Performance Gains</h3><p><strong>Improved Rendering Performance</strong>:</p><ul><li>Fabric’s synchronous and concurrent rendering capabilities lead to smoother UIs and faster updates.<br>- <strong>Enhanced Startup Times</strong></li><li>TurboModules significantly reduce app startup times by optimizing native module loading.<br>- <strong>Better Memory Management</strong>:</li><li>Direct JSI communication enables efficient memory usage and garbage collection.</li></ul><h3>Case Studies and Real-World Examples</h3><p>Many companies have successfully migrated their apps to React Native’s new architecture, reporting significant performance improvements and enhanced user experiences. Common themes in these successful migrations include thorough planning, incremental updates, and extensive testing. These real-world examples provide valuable lessons and highlight the importance of a structured approach to migration.</p><h3>Conclusion</h3><p>Migrating to React Native’s new architecture offers substantial benefits but requires careful planning and execution. Understanding the challenges and leveraging community resources can mitigate risks and facilitate a smoother transition. As the React Native ecosystem matures, more tools and libraries will become available to support developers in this migration process. By learning from the experiences of others and adopting best practices, developers can successfully transition their legacy apps to the new architecture, reaping the benefits of improved performance and flexibility.<br>See you in the next topic :)</p><p><strong>If this was useful</strong>, I share more about building AI-native, engineering, solopreneurship and the challenges I experience along the way. Follow me on X at <a href="http://twitter.com/mesutas_dev"><strong>@mesutas_dev</strong></a> or here on Medium and come along for the journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1861abae5bf9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a React Native Chat App: A Comprehensive Guide]]></title>
            <link>https://medium.com/@mesutas.dev/build-a-react-native-chat-app-a-comprehensive-guide-2852e5434e54?source=rss-b1c025774bd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2852e5434e54</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react-native-firebase]]></category>
            <category><![CDATA[react-native-development]]></category>
            <category><![CDATA[chat-app-development]]></category>
            <category><![CDATA[chat-app-using-firebase]]></category>
            <dc:creator><![CDATA[Mesut KILINCASLAN]]></dc:creator>
            <pubDate>Wed, 18 Sep 2024 10:18:17 GMT</pubDate>
            <atom:updated>2026-08-31T14:48:58.583Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S40cnOMjSv56ayd7" /></figure><p>Creating a chat application can be a rewarding project that combines various aspects of front-end and back-end development. React Native, with its ability to create cross-platform mobile applications, is an excellent choice for this task. In this guide, we will walk through the necessary tech stack, best practices and a step-by-step implementation of a chat app using React Native. By the end, you’ll have a solid understanding of how to build a functional and optimized chat application.</p><h3>Tech Stack and Libraries</h3><p>To build a React Native chat app, you’ll need a combination of front-end, back-end, and real-time communication tools. Below is the tech stack and libraries you will use:</p><ol><li><strong>React Native</strong>: The core framework for building the chat app.</li><li><strong>Redux</strong>: For state management.</li><li><strong>Firebase/Firestore</strong>: For real-time database and authentication.</li><li><strong>React Navigation</strong>: For navigating between different screens.</li><li><strong>Expo</strong>: To quickly set up and develop the app.</li><li><strong>Gifted Chat</strong>: A popular library for building chat UIs.</li></ol><h3>Step-by-Step Guide to Build a React Native Chat App</h3><h3>Step 1: Setting Up the Development Environment</h3><p>Before you start coding, ensure you have the necessary tools installed:</p><ol><li><strong>Node.js</strong>: Install Node.js from <a href="https://nodejs.org/">nodejs.org</a>.</li><li><strong>Expo CLI</strong>: Install Expo CLI by running npm install -g expo-cli.</li><li><strong>Firebase Account</strong>: Set up a Firebase project at <a href="https://firebase.google.com/">firebase.google.com</a>.</li></ol><h3>Step 2: Initializing the React Native Project</h3><p>Use Expo CLI to create a new React Native project:</p><pre>expo init ChatApp<br>cd ChatApp<br>expo start</pre><h3>Step 3: Setting Up Firebase</h3><ol><li><strong>Install Firebase SDK</strong>: Run npm install firebase.</li><li><strong>Configure Firebase</strong>: Create a firebase.js file and add your Firebase configuration:</li></ol><pre>// firebase.js<br>import firebase from &#39;firebase/app&#39;;<br>import &#39;firebase/firestore&#39;;<br>import &#39;firebase/auth&#39;;<br><br>const firebaseConfig = {<br>  apiKey: &quot;YOUR_API_KEY&quot;,<br>  authDomain: &quot;YOUR_AUTH_DOMAIN&quot;,<br>  projectId: &quot;YOUR_PROJECT_ID&quot;,<br>  storageBucket: &quot;YOUR_STORAGE_BUCKET&quot;,<br>  messagingSenderId: &quot;YOUR_MESSAGING_SENDER_ID&quot;,<br>  appId: &quot;YOUR_APP_ID&quot;<br>};<br><br>if (!firebase.apps.length) {<br>  firebase.initializeApp(firebaseConfig);<br>}<br><br>const db = firebase.firestore();<br>const auth = firebase.auth();<br><br>export { db, auth };</pre><h3>Step 4: Creating Authentication Screens</h3><p>SignUpScreen.js</p><pre>import React, { useState } from &#39;react&#39;;<br>import { View, TextInput, Button } from &#39;react-native&#39;;<br>import { useDispatch } from &#39;react-redux&#39;;<br>import { auth } from &#39;./firebase&#39;;<br><br>const SignUpScreen = ({ navigation }) =&gt; {<br>  const [email, setEmail] = useState(&#39;&#39;);<br>  const [password, setPassword] = useState(&#39;&#39;);<br><br>  const handleSignUp = () =&gt; {<br>    auth.createUserWithEmailAndPassword(email, password)<br>      .then(userCredentials =&gt; {<br>        const user = userCredentials.user;<br>        dispatch({ type: &#39;SET_USER&#39;, payload: user });<br>        console.log(&#39;Registered with:&#39;, user.email);<br>      })<br>      .catch(error =&gt; alert(error.message));<br>  };<br><br>  return (<br>    &lt;View&gt;<br>      &lt;TextInput placeholder=&quot;Email&quot; value={email} onChangeText={setEmail} /&gt;<br>      &lt;TextInput placeholder=&quot;Password&quot; value={password} onChangeText={setPassword} secureTextEntry /&gt;<br>      &lt;Button title=&quot;Sign Up&quot; onPress={handleSignUp} /&gt;<br>      &lt;Button title=&quot;Already have an account? Login&quot; onPress={() =&gt; navigation.navigate(&#39;Login&#39;)} /&gt;<br>    &lt;/View&gt;<br>  );<br>};<br><br>export default SignUpScreen;</pre><p>LoginScreen.js</p><pre>import React, { useState } from &#39;react&#39;;<br>import { View, TextInput, Button } from &#39;react-native&#39;;<br>import { useDispatch } from &#39;react-redux&#39;;<br>import { auth } from &#39;./firebase&#39;;<br><br>const LoginScreen = ({ navigation }) =&gt; {<br>  const [email, setEmail] = useState(&#39;&#39;);<br>  const [password, setPassword] = useState(&#39;&#39;);<br><br>  const handleLogin = () =&gt; {<br>    auth.signInWithEmailAndPassword(email, password)<br>      .then(userCredentials =&gt; {<br>        const user = userCredentials.user;<br>        dispatch({ type: &#39;SET_USER&#39;, payload: user });<br>        console.log(&#39;Logged in with:&#39;, user.email);<br>      })<br>      .catch(error =&gt; alert(error.message));<br>  };<br><br>  return (<br>    &lt;View&gt;<br>      &lt;TextInput placeholder=&quot;Email&quot; value={email} onChangeText={setEmail} /&gt;<br>      &lt;TextInput placeholder=&quot;Password&quot; value={password} onChangeText={setPassword} secureTextEntry /&gt;<br>      &lt;Button title=&quot;Login&quot; onPress={handleLogin} /&gt;<br>      &lt;Button title=&quot;Don&#39;t have an account? Sign Up&quot; onPress={() =&gt; navigation.navigate(&#39;SignUp&#39;)} /&gt;<br>    &lt;/View&gt;<br>  );<br>};<br><br>export default LoginScreen;</pre><h3>Step 5: Setting Up Navigation</h3><p>Install React Navigation libraries:</p><pre>npm install @react-navigation/native @react-navigation/stack<br>expo install react-native-gesture-handler react-native-reanimated react-native-screens react-native-safe-area-context @react-native-community/masked-view</pre><p>Create a basic navigation structure:</p><pre>// App.js<br>import React from &#39;react&#39;;<br>import { NavigationContainer } from &#39;@react-navigation/native&#39;;<br>import { createStackNavigator } from &#39;@react-navigation/stack&#39;;<br><br>import LoginScreen from &#39;./LoginScreen&#39;;<br>import SignUpScreen from &#39;./SignUpScreen&#39;;<br>import ChatScreen from &#39;./ChatScreen&#39;;<br><br>const Stack = createStackNavigator();<br><br>export default function App() {<br>  return (<br>    &lt;NavigationContainer&gt;<br>      &lt;Stack.Navigator initialRouteName=&quot;Login&quot;&gt;<br>        &lt;Stack.Screen name=&quot;Login&quot; component={LoginScreen} /&gt;<br>        &lt;Stack.Screen name=&quot;SignUp&quot; component={SignUpScreen} /&gt;<br>        &lt;Stack.Screen name=&quot;Chat&quot; component={ChatScreen} /&gt;<br>      &lt;/Stack.Navigator&gt;<br>    &lt;/NavigationContainer&gt;<br>  );<br>}</pre><h3>Step 6: Creating the Chat UI</h3><p>Install the Gifted Chat library:</p><pre>npm install react-native-gifted-chat</pre><p>Create the ChatScreen component:</p><pre>// screens/ChatScreen.js<br>import React, { useState, useCallback, useEffect } from &#39;react&#39;;<br>import { GiftedChat } from &#39;react-native-gifted-chat&#39;;<br>import { db, auth } from &#39;./firebase&#39;;<br><br>const ChatScreen = () =&gt; {<br>  const [messages, setMessages] = useState([]);<br><br>  useEffect(() =&gt; {<br>    const unsubscribe = db.collection(&#39;chats&#39;).orderBy(&#39;createdAt&#39;, &#39;desc&#39;).onSnapshot(snapshot =&gt; {<br>      setMessages(snapshot.docs.map(doc =&gt; ({<br>        _id: doc.data()._id,<br>        text: doc.data().text,<br>        createdAt: doc.data().createdAt.toDate(),<br>        user: doc.data().user<br>      })));<br>    });<br><br>    return unsubscribe;<br>  }, []);<br><br>  const onSend = useCallback((messages = []) =&gt; {<br>    setMessages(previousMessages =&gt; GiftedChat.append(previousMessages, messages));<br>    const { _id, createdAt, text, user } = messages[0];<br>    db.collection(&#39;chats&#39;).add({<br>      _id,<br>      createdAt,<br>      text,<br>      user<br>    });<br>  }, []);<br><br>  return (<br>    &lt;GiftedChat<br>      messages={messages}<br>      onSend={messages =&gt; onSend(messages)}<br>      user={{<br>        _id: auth.currentUser.email,<br>        name: auth.currentUser.email<br>      }}<br>    /&gt;<br>  );<br>};<br><br>export default ChatScreen;</pre><h3>Step 7: State Management with Redux</h3><p>Install Redux and related libraries:</p><pre>npm install redux react-redux</pre><p>Set up Redux store and reducers:</p><pre>// store.js<br>import { createStore, combineReducers } from &#39;redux&#39;;<br>import { Provider } from &#39;react-redux&#39;;<br>import userReducer from &#39;./reducers/userReducer&#39;;<br><br>const rootReducer = combineReducers({<br>  user: userReducer<br>});<br><br>export const store = createStore(rootReducer);<br><br>// reducers/userReducer.js<br>const initialState = {<br>  user: null<br>};<br><br>export default function userReducer(state = initialState, action) {<br>  switch (action.type) {<br>    case &#39;SET_USER&#39;:<br>      return { ...state, user: action.payload };<br>    default:<br>      return state;<br>  }<br>}</pre><h3>Step 8: Testing and Optimization</h3><p>Test your application thoroughly across different devices and network conditions. Use tools like React Native Debugger and Firebase Analytics to monitor performance and user engagement.</p><h3>Best Practices for Building a React Native Chat App</h3><ol><li><strong>Modular Architecture</strong>: Keep your codebase modular and organized.</li><li><strong>Error Handling</strong>: Implement robust error handling and user feedback mechanisms.</li><li><strong>Security</strong>: Secure your Firebase setup and manage user authentication appropriately.</li><li><strong>Performance</strong>: Optimize images, reduce unnecessary re-renders, and use efficient data structures.</li></ol><h3>Conclusion</h3><p>Building a chat app with React Native involves integrating several technologies and libraries. By following this guide, you can create a functional and optimized chat application. Remember to keep your code modular, handle errors gracefully, and always test your application under various conditions. Happy coding!</p><p><strong>If this was useful</strong>, I share more about building AI-native, engineering, solopreneurship and the challenges I experience along the way. Follow me on X at <a href="http://twitter.com/mesutas_dev"><strong>@mesutas_dev</strong></a> or here on Medium and come along for the journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2852e5434e54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Role-Based Access Control in Next.js with NextAuth]]></title>
            <link>https://medium.com/@mesutas.dev/rbac-in-next-js-with-nextauth-b438fe59eeeb?source=rss-b1c025774bd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b438fe59eeeb</guid>
            <category><![CDATA[role-based-access-control]]></category>
            <category><![CDATA[dynamic-routing]]></category>
            <category><![CDATA[middleware-nextjs]]></category>
            <category><![CDATA[nextauth]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Mesut KILINCASLAN]]></dc:creator>
            <pubDate>Tue, 12 Mar 2024 19:39:17 GMT</pubDate>
            <atom:updated>2026-08-31T14:43:32.683Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8m1KbJGo0503WEBbISxU0g.png" /></figure><p>In the rapidly evolving world of web development, ensuring that your application has robust and secure access control is paramount. One of the challenges we often face is implementing a flexible yet straightforward role-based access control (RBAC) system that scales with our application’s needs. In this blog post, we’ll dive into how you can leverage Next.js and NextAuth to create a dynamic RBAC system that can handle complex access patterns, including deeply nested and dynamic routes.</p><h3>Define the Access Control List (ACL)</h3><p>At the core of our RBAC system is the access control listACL. This object defines which roles have access to specific endpoints within our application. For example, a &quot;admin&quot; can access a wide range of endpoints, from the homepage to detailed project views and payment information. In contrast, a &quot;visitor&quot; has more limited access, focusing mainly on informational endpoints.</p><p>The beauty of this setup lies in its simplicity and flexibility. By defining roles and their associated endpoints in a central object, we can easily update access rights as our application grows and evolves.</p><pre>const roleAccessMap = {<br>  &quot;admin&quot;: [<br>    &quot;/&quot;,<br>    &quot;/companies&quot;,<br>    &quot;/companies/[id]&quot;,<br>    &quot;/tickets&quot;,<br>    &quot;/tickets/[id]&quot;,<br>    &quot;/team&quot;,<br>    &quot;/payments&quot;,<br>    &quot;/payments/[id]&quot;,<br>    &quot;/analytics&quot;,<br>  ],<br>  &quot;cs&quot;: [<br>    &quot;/&quot;,<br>    &quot;/companies&quot;,<br>    &quot;/companies/[id]&quot;,<br>    &quot;/tickets&quot;,<br>    &quot;/tickets/[id]&quot;,<br>    &quot;/team&quot;,<br>  ],<br>  &quot;developer&quot;: [<br>    &quot;/&quot;,<br>    &quot;/projects&quot;,<br>    &quot;/projects/[id]&quot;,<br>    &quot;/account&quot;,<br>    &quot;/company&quot;,<br>    &quot;/tickets&quot;,<br>    &quot;/tickets/[id]&quot;,<br>    &quot;/team&quot;,<br>  ],<br>  &quot;visitor&quot;: [<br>    &quot;/&quot;,<br>    &quot;/projects&quot;,<br>    &quot;/account&quot;,<br>    &quot;/company&quot;,<br>    &quot;/support&quot;,<br>  ],<br>};</pre><h3>Deep Link Access Control Logic</h3><p>Handling dynamic endpoints, such as /companies/[id] or /tickets/[id], requires a more nuanced approach. This is where our doesRoleHaveAccessToURL function shines. By converting our defined routes into regex patterns, we can accurately determine whether a role has access to a requested URL, even if that URL includes dynamic segments.</p><p>This approach ensures that our access control logic remains concise and maintainable, regardless of how complex our application’s routing becomes.</p><pre>function doesRoleHaveAccessToURL(role, url) {<br>  const accessibleRoutes = roleAccessMap[role] || [];<br>  return accessibleRoutes.some(route =&gt; {<br>    // Create a regex from the route by replacing dynamic segments<br>    const regexPattern = route.replace(/\[.*?\]/g, &quot;[^/]+&quot;).replace(&quot;/&quot;, &quot;\\/&quot;);<br>    const regex = new RegExp(`^${regexPattern}$`);<br>    return regex.test(url);<br>  });<br>}</pre><h3>Middleware for Authentication and Role Control</h3><p>Integrating this RBAC system with NextAuth is straightforward thanks to Next.js middleware. Our custom middleware function checks the user’s role against the requested URL’s access rights. If the user doesn’t have the appropriate access, they’re redirected to a 403 error, enhancing the application’s security posture.</p><pre>export default withAuth(<br>  function middleware(req) {<br>    // Redirect to login page if there is no accessible token<br>    if (!req.nextauth.token) {<br>      return NextResponse.redirect(&quot;/auth/login&quot;);<br>    }<br><br>    const role = req.nextauth.token.role;<br>    let haveAccess = doesRoleHaveAccessToURL(role,req.nextUrl.pathname)<br>    if(!haveAccess)<br>    {<br>      // Redirect to login page if user has no access to that particular page<br>      return NextResponse.rewrite(new URL(&quot;/403&quot;, req.url));<br>    }<br>    <br>    // Allow<br>  },<br>);</pre><h3>Fine-Grained In-Page Access Levels</h3><p>Beyond controlling route access, our system provides a mechanism for managing in-page action permissions through a custom hook, useRoleAccessLevel. This hook takes a page name and optionally a user role, then returns the permissions for editing or removing content on that page. This allows for a nuanced control of UI elements based on the user&#39;s capabilities, enhancing the application&#39;s security and user experience.</p><p>First we need to define the role access level object for each page that we wanna set accesses.</p><pre>const roles = {<br>  &#39;admin&#39;: {<br>    projects: { edit: 1, remove: 0 },<br>    ticket: { edit: 1, remove: 1 },<br>    company: { edit: 1, remove: 0 },<br>  },<br>  &#39;developer&#39;: {<br>    projects: { edit: 1, remove: 0 },<br>    ticket: { edit: 1, remove: 1 },<br>    company: { edit: 1, remove: 0 },<br>  },<br>  &#39;visitor&#39;: {<br>    projects: { edit: 1, remove: 0 },<br>    ticket: { edit: 1, remove: 0 },<br>    company: { edit: 0, remove: 0 },<br>  },<br>};</pre><p>Then let’s define the hook to recognize the active user role and active page;</p><pre>// It&#39;s optional to define page and role here<br>const useRoleAccess = ({page, role}: {page?: string; role?: string}) =&gt; {<br>  const session = useSession();<br>  const router = useRouter();<br><br>  if (session.status === &#39;loading&#39; || session.status === &quot;unauthenticated&quot;) return {};<br><br>  if (!role) {<br>    role = session.data &amp;&amp; session.data.user.role;<br>  }<br><br>  if (!page) page = router.pathname;<br><br>  const accessLevels = roles[role]?.[page];<br><br>  return { editLevel: accessLevels.edit, removeLevel: accessLevels.remove};<br>};<br><br>export default useRoleAccess;</pre><p>Using this hook, developers can conditionally render elements or enable actions, effectively tailoring the UI to match the user’s permissions in the page.</p><pre>const { editLevel, removeLevel } = useRoleAccess();</pre><h3>Conclusion</h3><p>Implementing a sophisticated RBAC system in NextJS with NextAuth not only enhances the security of your application but also provides a seamless and dynamic user experience. By carefully mapping roles to routes, employing regex for dynamic route matching, and leveraging hooks for in-page permissions, developers can create highly customizable and secure applications.</p><p><strong>If this was useful</strong>, I share more about building AI-native, engineering, solopreneurship and the challenges I experience along the way. Follow me on X at <a href="http://twitter.com/mesutas_dev"><strong>@mesutas_dev</strong></a> or here on Medium and come along for the journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b438fe59eeeb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>