<?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 Michael Epelboim on Medium]]></title>
        <description><![CDATA[Stories by Michael Epelboim on Medium]]></description>
        <link>https://medium.com/@sdrmike?source=rss-89682b68f8e5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CV_HSvs1-MakNggJNjotXg.jpeg</url>
            <title>Stories by Michael Epelboim on Medium</title>
            <link>https://medium.com/@sdrmike?source=rss-89682b68f8e5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 17:20:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sdrmike/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[Who Owns Creativity? The Ethical Battle Over AI-Generated Content]]></title>
            <link>https://sdrmike.medium.com/who-owns-creativity-the-ethical-battle-over-ai-generated-content-0d19984333e0?source=rss-89682b68f8e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d19984333e0</guid>
            <category><![CDATA[creativity]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[innovation]]></category>
            <category><![CDATA[ethics]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Michael Epelboim]]></dc:creator>
            <pubDate>Sat, 29 Mar 2025 20:22:37 GMT</pubDate>
            <atom:updated>2025-03-30T07:28:29.611Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IiaionuijRgRz1hmbXNZXQ@2x.jpeg" /><figcaption>Photo by <a href="https://m.facebook.com/My-Life-Through-A-Lens-1680393972205305/">&quot;My Life Through A Lens&quot;</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>The GPT‑4o Incident</h4><p>Between March 27 and 29, 2025, social media erupted with AI-generated art mimicking Studio Ghibli’s iconic style. OpenAI’s GPT‑4o image generator powered the trend, with users on X (formerly Twitter) sharing stylized portraits and landscapes under the hashtag #GhibliStyle. Even OpenAI CEO Sam Altman participated by updating his profile picture with an AI-generated, Ghibli-inspired portrait.</p><p>The trend sparked backlash, prompting OpenAI to update its policy. Users could no longer request images in the style of specific living artists, although mimicking broader studio aesthetics (such as Ghibli’s) remained permitted. Critics called the policy contradictory — after all, studio aesthetics are shaped by individual artists.</p><h4>Human Creativity vs. AI Mimicry</h4><p>Human artists develop their craft over years, blending personal experiences and cultural influences into original work. Studio Ghibli’s films, for instance, are celebrated for exploring themes like humanity’s relationship with nature — ideas that reflect the studio’s creative ethos.</p><p>AI tools like GPT‑4o take a different approach. They analyze vast datasets of existing art to replicate patterns. While humans reinterpret their influences (for example, a painter studying Monet’s use of light to develop a new technique), AI generates outputs based solely on statistical correlations. Ask for “Ghibli-style art,” and GPT‑4o might blend soft colors with fantastical creatures — but it doesn’t understand the deeper themes behind the style.</p><p>This raises a key question: Should AI’s practice of data scraping be treated the same as human inspiration under fair use laws?</p><ul><li><em>Human fair use</em>: A writer analyzing Hemingway’s prose to refine their own voice.</li><li><em>AI “fair use”</em>: An algorithm scanning thousands of novels to generate text in Hemingway’s style.</li></ul><p>Without human intent or emotion, AI’s version of “creativity” remains a technical feat rather than an artistic one.</p><h4>Legal and Ethical Gray Areas</h4><p>Lawsuits such as Andersen v. Stability AI highlight the legal confusion surrounding AI and copyright. In the EU, companies must now disclose what data trains their AI models. In contrast, the U.S. lacks similar mandates, leaving room for companies to scrape data under broad “fair use” arguments. A different approach can be seen in Japan’s Article 30‑4 of the Copyright Act, which permits the ingestion of copyrighted materials for analysis and AI training (even commercially) provided the practice does not harm the market or the copyright holder’s interests</p><p>AI firms defend their practices by arguing that broad data access fuels innovation. For instance, tools like MidJourney allow small creators to prototype designs without expensive software. Yet, artists are increasingly demanding transparency. Projects like “Have I Been Trained?” let creators check whether their work was used to train AI — even though incomplete data limits the tool’s reliability.</p><p>The core conflict remains: should AI innovation override individual creators’ rights?</p><h4>The Cultural Cost of Style Replication</h4><p>The #GhibliStyle trend took a troubling turn when users applied the aesthetic to sensitive topics such as historical tragedies or political violence. These AI-generated images — whimsical reinterpretations of real-world pain — drew criticism for trivializing serious events.</p><p>Studio Ghibli’s films often explore nuanced emotional and philosophical themes. Using its style as a one-click filter risks reducing its cultural depth to a superficial gimmick. Hayao Miyazaki, Ghibli’s co-founder, has been vocal about his disdain for AI art, calling it “an insult to life itself” in a 2016 documentary. While his comment predates tools like GPT‑4o, it underscores a fear shared by many artists: that AI could erode the meaning behind their work.</p><h4>The AI Industry’s Defense</h4><p>AI companies maintain that their tools democratize creativity. Independent game developers, for example, use AI to quickly prototype character designs — saving both time and resources. Writers experiment with ChatGPT to overcome creative blocks, and educators generate custom illustrations for their students.</p><p>“AI unlocks possibilities that were once limited to those with the resources or technical skills,” companies claim. They also emphasize that AI-generated content often serves only as a starting point — a rough draft for humans to refine.</p><p>Yet this argument sidesteps key ethical questions. Does democratizing creativity justify using artists’ work without consent? And who benefits most — the public, or the companies profiting from these tools?</p><h4>Conclusion: Creativity at a Crossroads</h4><p>The GPT‑4o debate reflects a broader struggle across the AI industry. Similar issues apply to text generators, video tools, and music models. While some companies now partner with creators or license training data, most still rely on disputed fair use claims. The landscape is further complicated by jurisdictional differences: the EU demands data transparency, the U.S. navigates a patchwork of copyright protections, and Japan permits certain uses that can promote innovation but stir ethical concerns.</p><p>The path forward hinges on balance. Clear rules could ensure that AI enhances human creativity without exploiting it:</p><ul><li><strong>Transparency</strong>: Require AI companies to disclose training data sources.</li><li><strong>Compensation</strong>: Explore systems to credit and pay creators when their work fuels AI models.</li><li><strong>Ethical guardrails</strong>: Prevent tools from replicating the styles of living artists or trivializing cultural works.</li></ul><p>Technology should empower creators, not replace them. After all, algorithms may mimic a style, but they’ll never replicate the human spark behind it (at least not yet)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d19984333e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cursor Rules — Why Your AI Agent is Ignoring You (and How to Fix It)]]></title>
            <link>https://sdrmike.medium.com/cursor-rules-why-your-ai-agent-is-ignoring-you-and-how-to-fix-it-5b4d2ac0b1b0?source=rss-89682b68f8e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b4d2ac0b1b0</guid>
            <category><![CDATA[mdc]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[cursor]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Michael Epelboim]]></dc:creator>
            <pubDate>Fri, 21 Mar 2025 03:35:43 GMT</pubDate>
            <atom:updated>2025-03-29T03:20:21.618Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cursor Rules: Why Your AI Agent Is Ignoring You (and How to Fix It)</h3><p>Frustrated with inconsistent project rules? Here’s how to make Cursor behave.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ISe91S_KZQ7PIDD-Ydaqtg.png" /></figure><h3>Do you use Cursor to write code, or just to watch the AI agent freestyle like it’s auditioning for a talent show?</h3><h4>If you’re frustrated because your carefully crafted project rules are being ignored, you’re not alone. Let’s talk about why this happens — and how to fix it before you lose your mind.</h4><p>Lately, it seems like the user experience is taking a hit. The models don’t seem to suggest as good code as they used to, and the agent seems to follow its heart instead of your instructions. For me, the biggest frustration lately has been with the project rules. I’ve spent a lot of time writing (or searching online for) good rules for many types of files, frameworks, and workflows — only to see them applied inconsistently or, sometimes, not at all.</p><p>When all my attempts to figure out a solution didn’t produce good results, I finally decided to check the documentation. Like I learned: <em>When every attempt fails, read the manual!</em> But that didn’t help much either. I guess the folks at Cursor are so busy keeping the product up to date with the incredibly fast developments in AI that they simply don’t have time to update the documentation after every push to production.</p><p>So, I employed my sleuthing skills. I’ve been searching for answers, googling, perplexitying?, forums, blogs, tik toks, youtubes, discords, weibo, you name it. Slowly, I was able to piece together what seems to be a working solution.</p><p>Let me explain (though I have no real way to verify that what I’m about to say is 100% accurate — it just seems to work for me, so take it with a grain of salt):</p><h4>The Agent and the Rules:</h4><p>The agent that we chat with doesn’t generate the code. It’s an AI, but its job is to relay information and choose the right context and prompt for the models that generate the code. Sometimes the agent gets to select which rules to <strong>include</strong>; sometimes it selects which rules to <strong>exclude</strong>.</p><p>In it’s own words:</p><blockquote><strong>Me</strong>: Do you have access to rules?<br><strong>Agent</strong>: Yes, I can see several rules in the provided context:<br> 1. &lt;custom_instructions&gt; with specific rules about: (my user rules are listed here)<br> 2. &lt;available_instruction_rules&gt; (my project rules with a description are listed here in the format &lt;rule name&gt;: &lt;rule description&gt;<br> 3. &lt;cursor_rules_context&gt; with a list of rules: (these are my alwaysApply:true rules)</blockquote><blockquote><strong>Me</strong>: What are instruction rules?<br><strong>Agent</strong>: Instruction rules (or Cursor rules) are extra documentation provided by the user to help guide AI interactions with the codebase. They serve as standardized guidelines for specific scenarios.<br>The available instruction rules are:<br> #. &lt;name&gt;: &lt;Brief description&gt;<br> These rules are meant to be applied when relevant to a specific task. When I receive a query, I first look at what context is provided in the message. I decide which rules are relevant. I can fetch the full content of any of these rules using the fetch_rules tool if we need more detailed information about a specific rule and I can attach the rule to the &lt;cursor_rules_context&gt; if it’s not already attached.</blockquote><blockquote><strong>Me</strong>: What are the instruction on what to do with &lt;cursor_rules_context&gt;?<br><strong>Agent</strong>: Looking at the &lt;cursor_rules_context&gt;, I see this header text:<br> Cursor Rules are extra documentation provided by the user to help the AI understand the codebase.<br> Use them if they seem useful to the users most recent query, but do not use them if they seem unrelated.<br> They tell me to:<br>- Use the rules if they’re relevant to the current query<br>- Don’t use them if they’re not related</blockquote><p>To better control how rules are managed by the system we just need to know how to set them up correctly and know how to invoke them correctly. What this will achieve is to get the rule into the query context, but it will then be up to it’s content and its relevance to the query that ensures they are used or not.</p><p>When we create a rule we are creating a .mdc file (Cursor markdown?). If we explore that file as a regular markdown we notice it includes a <strong>frontmatter</strong> section:</p><pre>---<br>description:<br>globs:<br>alwaysApply:<br>---</pre><h4>How to explore the .mdc file as markdown?</h4><blockquote>Well, the answer is to disable the special UI for .mdc files and present them as regular markdown (this way it’s also very straightforward to programmatically generate rules). To do this go to your Cursor user or workspace settings and add the following:</blockquote><pre>&quot;workbench.editorAssociations&quot;: {<br> &quot;*.mdc&quot;: &quot;default&quot;<br> }</pre><p>But this is <strong>not your typical YAML frontmatter</strong> and shouldn’t be treated as such, or else you will always get strings. If you refer to it as a mdc in your markdown, the agent will know how to handle it:</p><pre>```mdc<br>---<br>description:<br>globs:<br>alwaysApply:<br>---<br>```</pre><h4>There are 4 combinations in the frontmatter that we can use and each will clearly define how the rule gets added to the context</h4><ol><li><strong>Always</strong> add the rule to the context :</li></ol><pre>```mdc<br>---<br>description:  # Empty<br>globs:        # Empty<br>alwaysApply: true<br>---<br>```</pre><p>2. Automatically add a rule to the context <strong>if the user attaches or mentions a file in the CHAT that matches the rule’s glob pattern</strong>. (This means the rule won’t be automatically added if the agent just works on a file that matches the glob pattern):</p><pre>```mdc<br>---<br>description:   # Empty<br>globs: src/**/*.ts,src/**/*.tsx<br>alwaysApply: false<br>---<br>```</pre><blockquote>for now, it seems we cannot combine types with { } in globs. (e.g. src/**/*.{ts,tsx})</blockquote><p>3. Let the agent decide from the context of the query whether to consider a rule useful based <strong>only</strong> on its <strong>description</strong>. If the rule gets selected, then the agent requests the full contents and adds it to the context.:</p><pre>```mdc<br>---<br>description: (description for the agent to decide if the rule seems relevant)<br>globs:    # Empty<br>alwaysApply: false<br>---<br>```</pre><p>4. A rule with the following setup will never be added to the context automatically. Only if it’s explicitly mentioned in the chat:</p><pre>```mdc<br>---<br>description:  #Empty<br>globs:    # Empty<br>alwaysApply: false<br>---<br>```</pre><p>There you have it!</p><h4>A few thoughts on how to use ‘description’:</h4><ul><li>Remember that this is for the AI Agent to consider the rule, not for you!</li><li>Say what it’s for, or when to use it. Experiment!</li><li>Sometimes saying less is better.</li><li>I’ve used: When the user types ‘compile’<em> — very direct and specific.</em></li><li>Remember not to have both globs and description defined in the same rule. If the rule is set to match a specific pattern, don’t crowd the list of rules that the agent needs to consider from context (the more rules there are for the agent consider, the higher the chances it will miss something important).</li><li>You can use the following guidelines:<br> - Consistent “<strong>USE WHEN</strong>” prefix makes it clear these are trigger conditions.<br> - Consistent verb format (gerund form: creating, writing, modifying)<br> - Clear action-based conditions<br> - Example: USE WHEN writing or modifying tests</li></ul><h4>Final Thought:</h4><p>The rules implementation and methodology seems to be evolving constantly, changes are being made (some improve the experience and some degrade it), so what seems the best strategy today, might not be the best strategy tomorrow. And since the change is happening so fast, I understand why the documentation can’t keep up (as frustrating as that is)!</p><p>Hope this helps.</p><p><em>(Update – 03/28/25) To have new rules or changes to other rules take effect, you need to start a new chat.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b4d2ac0b1b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adaptation is Key: Navigating Change in Business, Technology, and Careers]]></title>
            <link>https://sdrmike.medium.com/adaptation-is-key-navigating-change-in-business-technology-and-careers-579eac4b6782?source=rss-89682b68f8e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/579eac4b6782</guid>
            <category><![CDATA[business-strategy]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[future-of-work]]></category>
            <category><![CDATA[adaptation]]></category>
            <dc:creator><![CDATA[Michael Epelboim]]></dc:creator>
            <pubDate>Tue, 18 Mar 2025 10:44:22 GMT</pubDate>
            <atom:updated>2025-03-18T10:44:22.964Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A split-screen image illustrating adaptation in business and technology. The left side depicts global challenges with visuals of a globe, rising bar graphs, and icons for inflation and supply chains. The right side represents the AI revolution, featuring a glowing brain, AI circuits, and a robot hand shaking a human hand. A bridge connects the two sides, symbolizing adaptation as the link between challenges and opportunities." src="https://cdn-images-1.medium.com/max/1024/1*SNxHlhE1AV_S8hV7sJsH8A.jpeg" /></figure><p>Adaptation has always been a critical skill, but today, the pace and scale of change demand an unprecedented level of flexibility. Whether you’re a business owner, a consumer, or a professional, the ability to adapt is no longer optional — it’s essential for survival and success. This article explores three key areas where adaptation is crucial: the shifting global landscape, the rapid evolution of artificial intelligence (AI), and the changing nature of professional roles.</p><h4>Adapting to Global Realities</h4><p>The world is in a state of flux, and businesses and consumers alike are feeling the pressure. Economic uncertainty, driven by factors such as geopolitical tensions, climate change, and inflation, has created a more cautious environment. For example, the ongoing war in Ukraine and the lingering effects of trade policies, such as tariffs introduced (and threatened) by the Trump administration, have disrupted supply chains and increased costs. As someone with a background in international trade, I’ve seen firsthand how these disruptions ripple through global markets, affecting everything from procurement strategies to inventory management.</p><p>Small businesses, in particular, face unique challenges. Many lack the resources for advanced tools like specialized procurement departments or inventory forecasting software. From my personal experience working with U.S. customers, I’ve observed that concerns about cash flow and rising costs are leading to reduced SKU diversity and lower inventory volumes. Consumers, too, are feeling the pinch. The perception that “everything is getting more expensive” has become a shared experience, whether justified by actual costs or not. This cautious spending behavior is reshaping markets and forcing businesses to rethink their strategies.</p><h4>The AI Revolution: A Catalyst for Change</h4><p>While global uncertainties demand caution, the rapid advancement of AI technology requires bold adaptation. The AI revolution is progressing at an astonishing pace, with new breakthroughs and applications emerging daily. Businesses and individuals must navigate this transformative wave to stay relevant.</p><p>AI is already reshaping industries by solving complex problems and improving existing solutions. However, it also poses challenges. Some products and services are becoming obsolete, while others must evolve to integrate AI-driven workflows. For instance, many new apps now feature conversational AI interfaces, allowing users to interact with them more intuitively. This trend raises a critical question for businesses: should you update your existing products to include similar capabilities, or risk falling behind?</p><p>Having worked in software development, I’ve seen how AI is transforming the way we build and deliver solutions. The opportunities AI presents are immense, but they require proactive adaptation. Companies that embrace AI to enhance their offerings or streamline operations will thrive, while those that resist change may struggle to survive.</p><h4>Personal Adaptation: The Future of Work</h4><p>Adaptation isn’t just a challenge for businesses, it’s deeply personal. My background in both international trade and software development has given me a unique perspective on how industries and professionals must evolve. As a software developer, I’ve seen firsthand how AI is transforming the way we work. The first step in adapting to this new reality is to embrace AI as a tool. For developers, this means using AI to assist with coding tasks, a shift that should already be underway.</p><p>The next step is to prepare for a future where AI can write entire applications independently, and do it well. While AI still requires guidance and supervision, its capabilities are advancing rapidly. This is why understanding the fundamentals of programming languages and frameworks is more important than memorizing specific implementations. The ability to think critically and solve problems will remain invaluable, even as AI takes on more of the technical workload.</p><p>Looking ahead, I believe our roles will shift from writing code to orchestrating AI-driven workflows. This includes setting up and customizing coding agents, as well as managing their interactions to ensure successful project outcomes. My future role might as well be ‘Full Stack Orchestrator”. In this new landscape, adaptability will be the key to staying relevant and thriving in our careers.</p><h4>Conclusion</h4><p>Adaptation is no longer a choice, it’s a necessity. Whether you’re navigating global economic challenges, leveraging AI to stay competitive, or redefining your professional role, the ability to adapt will determine your success. My experiences in international trade and software development have shown me that the world is changing rapidly, and those who embrace change with curiosity and resilience will be best positioned to thrive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=579eac4b6782" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Hooks: the popular ones and some custom hooks]]></title>
            <link>https://sdrmike.medium.com/react-hooks-the-popular-ones-and-some-custom-hooks-5911049fae9b?source=rss-89682b68f8e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5911049fae9b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Michael Epelboim]]></dc:creator>
            <pubDate>Sun, 21 May 2023 09:58:54 GMT</pubDate>
            <atom:updated>2023-05-21T09:58:54.958Z</atom:updated>
            <content:encoded><![CDATA[<p>A dive into react hooks, with examples</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*YF_VUjY9Vz1r210DwU5JBA.png" /></figure><p>If you’re part of the world of React developers, the concept of Hooks must be no stranger to you. Introduced in React 16.8, Hooks have become a go-to solution for state management and side effects in functional components. This article walks you through eight of the most popular React Hooks and concludes with a discussion on creating custom Hooks.</p><h3>1. useState</h3><p>useState is the simplest Hook and a great starting point to understand Hooks in general. It allows you to add state to functional components. When you call useState, you provide the initial state, and it returns an array with the current state and a function that allows you to update it.</p><pre>const [state, setState] = useState(initialState);</pre><p>For example, if we were creating a simple counter:</p><pre>const Counter = () =&gt; {<br>  const [count, setCount] = useState(0);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;You clicked {count} times&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;<br>        Click me<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>This Hook declares a state variable count, initialized to 0. To update count, you just need to call setCount().</p><h3>2. useEffect</h3><p>useEffect lets you perform side effects in functional components, such as data fetching, setting up a subscription, or manually changing the DOM.</p><p>Consider a component that fetches user data from an API:</p><pre>const UserProfile = ({userId}) =&gt; {<br>  const [user, setUser] = useState(null);<br><br>  useEffect(() =&gt; {<br>    const fetchData = async () =&gt; {<br>      const result = await axios(`https://api.example.com/user/${userId}`);<br>      setUser(result.data);<br>    };<br><br>    fetchData();<br>  }, [userId]);  // The effect depends on the userId that is passed as a prop<br><br>  return user ? (&lt;h2&gt;{user.name}&lt;/h2&gt;) : (&lt;p&gt;Loading...&lt;/p&gt;);<br>};</pre><p>The effect runs after every render by default. However, if you pass an array of dependencies (userId int he example), the effect runs only when the dependencies change.</p><h3>3. useContext</h3><p>useContext allows you to access the context without having to wrap a component in a Context Consumer. It accepts a context object (the value returned from React.createContext) and returns the current context value, as given by the closest context provider for the given context.</p><p>Here’s a simple theme toggle component:</p><pre>const themes = {<br>  light: {<br>    foreground: &quot;#000000&quot;,<br>    background: &quot;#eeeeee&quot;<br>  },<br>  dark: {<br>    foreground: &quot;#ffffff&quot;,<br>    background: &quot;#222222&quot;<br>  }<br>};<br><br>const ThemeContext = React.createContext(themes.light);<br><br>function ThemeTogglerButton() {<br>  const theme = useContext(ThemeContext);<br><br>  return (<br>    &lt;button style={{background: theme.background, color: theme.foreground}}&gt;<br>      Toggle Theme<br>    &lt;/button&gt;<br>  );<br>}</pre><h3>4. useReducer</h3><p>useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one. It also lets you optimize performance for components that trigger deep updates because you can dispatch actions deep down.</p><p>An example use case is a simple counter where you can increment, decrement, or reset the value:</p><pre>const initialState = {count: 0};<br><br>function reducer(state, action) {<br>  switch (action.type) {<br>    case &#39;increment&#39;:<br>      return {count: state.count + 1};<br>    case &#39;decrement&#39;:<br>      return {count: state.count - 1};<br>    case &#39;reset&#39;:<br>      return initialState;<br>    default:<br>      throw new Error();<br>  }<br>}<br><br>function Counter() {<br>  const [state, dispatch] = useReducer(reducer, initialState);<br>  return (<br>    &lt;&gt;<br>      Count: {state.count}<br>      &lt;button onClick={() =&gt; dispatch({type: &#39;reset&#39;})}&gt;Reset&lt;/button&gt;<br>      &lt;button onClick={() =&gt; dispatch({type: &#39;increment&#39;})}&gt;+&lt;/button&gt;<br>      &lt;button onClick={() =&gt; dispatch({type: &#39;decrement&#39;})}&gt;-&lt;/button&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>Here, reducer is a function that determines how the state changes in response to actions, and dispatch is the method to dispatch actions to the reducer.</p><h3>5. useRef</h3><p>useRef returns a mutable ref object whose .current property is initialized with the passed argument (initialValue). The returned object will persist for the full lifetime of the component. It can be used to access DOM elements directly.</p><p>A common use case for useRef is to access a child imperatively:</p><pre>function TextInputWithFocusButton() {<br>  const inputEl = useRef(null);<br>  const onButtonClick = () =&gt; {<br>    // `current` points to the mounted text input element<br>    inputEl.current.focus();<br>  };<br>  return (<br>    &lt;&gt;<br>      &lt;input ref={inputEl} type=&quot;text&quot; /&gt;<br>      &lt;button onClick={onButtonClick}&gt;Focus the input&lt;/button&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><h3>6. useMemo</h3><p>useMemo will only recompute the memoized value when one of the dependencies has changed. This optimization helps to avoid expensive calculations on every render.</p><p>Consider a component that performs an expensive calculation:</p><pre>function MyComponent({ a, b }) {<br>  const result = useMemo(() =&gt; {<br>    let output = 0;<br>    // Imagine a really expensive computation here<br>    for (let i = 0; i &lt; 100000000000; i++) {<br>      output = a + b + i;<br>    }<br>    return output;<br>  }, [a, b]);  // Only re-run the expensive function if `a` or `b` changes<br><br>  return &lt;h2&gt;{result}&lt;/h2&gt;;<br>}</pre><h3>7. useCallback</h3><p>useCallback returns a memoized version of the callback function that only changes if one of the dependencies has changed. It’s useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.</p><p>Here’s an example with a search input that waits for the user to stop typing before executing:</p><pre>function Search({ query, setQuery }) {<br>  const debouncedSearch = useCallback(<br>    debounce(q =&gt; {<br>      // Make your API call here<br>    }, 500),<br>    [],<br>  );<br><br>  useEffect(() =&gt; {<br>    debouncedSearch(query);<br>  }, [query, debouncedSearch]);<br><br>  return &lt;input value={query} onChange={(e) =&gt; setQuery(e.target.value)} /&gt;;<br>}</pre><h3>8. useLayoutEffect</h3><p>useLayoutEffect has the same signature as useEffect, but it fires synchronously after all DOM mutations. Use this to read layout from the DOM and synchronously re-render. Updates scheduled inside useLayoutEffect will be flushed synchronously, before the browser has a chance to paint.</p><p>A use case is to prevent scroll jumping:</p><pre>function ScrollingList({ items, position }) {<br>  const ref = useRef(null);<br><br>  useLayoutEffect(() =&gt; {<br>    ref.current.scrollTop = position;<br>  }, [position]); // Only runs if position changes<br><br>  return (<br>    &lt;div ref={ref}&gt;<br>      {items.map(item =&gt; &lt;div key={item.id}&gt;{item.name}&lt;/div&gt;)}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>The ScrollingList component restores its scroll position right after the DOM has been updated but before it&#39;s been painted, preventing a visible jump.</p><h3>Creating Custom Hooks</h3><p>Custom Hooks are essentially JavaScript functions whose name starts with “use”. They can call other Hooks and even other custom Hooks.</p><h3>1. useFormInput</h3><p>Let’s create a custom Hook, useFormInput, which manages form input state.</p><pre>function useFormInput(initialValue) {<br>  const [value, setValue] = useState(initialValue);<br>  <br>  function handleChange(e) {<br>    setValue(e.target.value);<br>  }<br><br>  return {<br>    value,<br>    onChange: handleChange<br>  };<br>}</pre><p>This custom Hook first initializes a state variable `value` with an initial value. It then defines a function `handleChange()` that updates `value` when the user types in the input field. Finally, it returns an object containing `value` and `handleChange`. You can now use this Hook in your functional components like this:</p><pre>function MyForm() {<br>  const name = useFormInput(&quot;&quot;);<br>  const password = useFormInput(&quot;&quot;);<br><br>  return (<br>    &lt;form&gt;<br>      &lt;input type=&quot;text&quot; {...name} placeholder=&quot;Name&quot; /&gt;<br>      &lt;input type=&quot;password&quot; {...password} placeholder=&quot;Password&quot; /&gt;<br>    &lt;/form&gt;<br>  );<br>}</pre><p>Here, we’re spreading out the object returned by useFormInput into the input elements. This is the equivalent of setting value={name.value} and onChange={name.onChange}.</p><h3>2. useLocalStorage</h3><p>Let’s take a look at another custom hook: useLocalStorage. This hook allows you to read and write to local storage, just like you&#39;d manage state with useState.</p><pre>import { useState, useEffect } from &#39;react&#39;;<br><br>function useLocalStorage(key, initialValue) {<br>  const [storedValue, setStoredValue] = useState(() =&gt; {<br>    try {<br>      const item = window.localStorage.getItem(key);<br>      return item ? JSON.parse(item) : initialValue;<br>    } catch (error) {<br>      console.log(error);<br>      return initialValue;<br>    }<br>  });<br><br>  const setValue = value =&gt; {<br>    try {<br>      const valueToStore =<br>        value instanceof Function ? value(storedValue) : value;<br>      setStoredValue(valueToStore);<br>      window.localStorage.setItem(key, JSON.stringify(valueToStore));<br>    } catch (error) {<br>      console.log(error);<br>    }<br>  };<br><br>  return [storedValue, setValue];<br>}</pre><p>This custom hook first tries to get the value from local storage, and if it’s not there, it returns the initialValue. The setValue function is used to update both the state and the local storage value.</p><p>You can use this custom hook just like you’d use useState:</p><pre>function MyComponent() {<br>  const [name, setName] = useLocalStorage(&#39;name&#39;, &#39;Anonymous&#39;);<br><br>  return (<br>    &lt;input <br>      type=&quot;text&quot;<br>      value={name}<br>      onChange={e =&gt; setName(e.target.value)}<br>    /&gt;<br>  );<br>}</pre><p>In this component, name is stored in local storage. Even if you refresh the page, the input field will keep displaying the same value, thanks to the power of local storage.</p><p>In conclusion, Hooks have not only simplified the way we handle state and lifecycle methods in functional components, but they’ve also given us the flexibility to create our own custom Hooks. This allows us to write more readable and maintainable React code, bringing productivity to new heights.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5911049fae9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails 7: API-only app with Devise and JWT for authentication]]></title>
            <link>https://sdrmike.medium.com/rails-7-api-only-app-with-devise-and-jwt-for-authentication-1397211fb97c?source=rss-89682b68f8e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1397211fb97c</guid>
            <category><![CDATA[devise-jwt]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[rails-7]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[devise]]></category>
            <dc:creator><![CDATA[Michael Epelboim]]></dc:creator>
            <pubDate>Mon, 07 Nov 2022 05:32:39 GMT</pubDate>
            <atom:updated>2024-01-31T06:02:00.344Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*jJ_Oo1l1L4vvoRAlA2A8AA.png" /></figure><p>The project:</p><p>I set up to build a movie watchlists app where users can browse movies and add them to new or existing watchlists, and they can mark the movies as watched/unwatched. I decided to also document the process.</p><p>The backend is coded as a Rails API-only app and it will connect to a React/Next.JS front-end app</p><p>Each one of the articles in the series deals with a different part of creating the app and will include a walkthrough, some explanations, and some challenges I faced while coding it and how I solved them.</p><p>My <a href="https://sdrmike.medium.com/building-an-app-from-concept-to-deployment-using-headless-rails-api-and-react-with-next-js-8d52cc343755">previous article</a> covered the concept, design, and database architecture for the app.</p><p>The popularity of using Rails as an API client has been rising now that many easy-to-use and deploy front-end frameworks exist. A single backend codebase can be used in both web and native applications by detaching the backend from the front end. Even if we don’t use the Rails feature that allows us to have logic in the view layer, all the other benefits still apply, mainly setting up and getting running the app quickly, without having to make a lot of trivial decisions.</p><p>In this article, I will show how to set up a Rails-API-only app with user authentication using Devise and JWT, and serialization using jsonapi-serializer.</p><p>I am using the following versions:</p><ul><li>Ruby: 3.1.1</li><li>Rails: 7.0.4</li><li>PostgreSQL: 14.5</li></ul><p>Let’s start with a few explanations of what things are and why I chose them:</p><h4><strong>What is Authentication and why JWT:</strong></h4><p>HTTP is a stateless protocol. Every call made to the server is like a new call with no memory or “state” of the previous calls. But in reality, in applications, we generally maintain session information, for example, log-in data, to allow users to have access to certain parts and features of the application without having to log in (authenticate) with every request.</p><p>There are 2 main approaches to authentication management:</p><ul><li>Cookies based approach</li><li>JWT (JSON Web Token) approach</li></ul><p>For this application we are choosing the JWT way:</p><p>After successful authentication (verifying that the username and password match), the server generates an <strong>accessToken</strong> by encrypting the “userId” and “expiresIn” information and then sends it to the client (the browser). The browser receives this token, saves it, and then includes it with every subsequent request.</p><p>In this way, no session information is saved in the database. All the information on the current user or the “bearer” is stored in the token itself and with every request, the server will know the user just by decrypting the token, with no need for a database search for the session. Only the server that has the <em>access token secret</em> can decrypt the JWT token.</p><p>One disadvantage for user experience (or advantage from a security point of view) of using a JWT token is that it <strong>must</strong> have an expiration time, so if we are planning an application where the user never signs out, there are better approaches than this.</p><p>To manage authentication and sessions in our Rails app, we will use the gems: <a href="https://github.com/heartcombo/devise">Devise</a> and <a href="https://github.com/waiting-for-dev/devise-jwt">Devise-JWT</a>.</p><h4>Create the Rails API app</h4><pre>rails new movie-watchlists-api --api –d postgresql --skip-test</pre><p>-- api : Preconfigure a smaller stack for API-only apps</p><p>- d : Preconfigure for the selected database</p><p>-- skip-test : Skip test files</p><h4>Enabling CORS</h4><p>CORS (cross-origin resource sharing) is an HTTP-header-based security mechanism that defines who’s allowed to interact with your API. CORS is built into all modern web browsers.</p><p>In the most simple scenario, CORS will block all requests from a different origin than your API. “Origin” in this case is the combination of protocol, domain, and port.</p><p>Since our backend and front end will be hosted on different servers, we have to manually set up the application to accept requests from a different origin.</p><p>Luckily, there is a gem that will set this up for us with minimal configuration, just uncomment the following line from the gemfile:</p><pre>gem &#39;rack-cors&#39;</pre><p>run bundle install and uncomment the contents of the file config/initializers/cors.rb :</p><pre><em>Rails</em>.application.config.middleware.insert_before 0, <em>Rack</em>::Cors do</pre><pre>  allow do</pre><pre>    origins &#39;*&#39; # later change to the domain of the frontend app</pre><pre>    resource &#39;*&#39;,</pre><pre>             headers: :any,</pre><pre>             methods: %i[get post put patch delete options head],</pre><pre>             expose: [:Authorization]</pre><pre>  end</pre><pre>end</pre><p>You need to pay close attention to the <strong>origins</strong> parameter. Remember that CORS needs to match protocol, domain, and port. You’ll need to specify all three correctly. So if you put http://example.com:80, but the call will come from http://example.com:8080 or https://example.com:443, then you’ll still get blocked. Leaving it as ‘*’ allows anyone to connect to your API. When first creating the app and for testing purposes, leaving it as ‘*’ is a good idea, but remember to change it when you are ready to deploy.</p><p>By default, the rack-cors gem only exposes certain headers like Content-Type, Last-Modified, etc., so we have to manually expose the ‘Authorization’ header to cross-origin requests, which will be used to dispatch and receive JWT tokens.</p><h4>devise, devise-JWT and jsonapi-serializer</h4><ul><li>devise is a gem that handles users and authentication. It takes care of all the controllers necessary for user creation (users_controller) and user sessions (users_sessions_controller). I initially wondered whether devise, which is designed to use in full-stack Rails apps, is a good choice for API-only mode, but with a few small tweaks, it works and does the job.</li><li>devise-jwt, a gem, is an extension to devise which handles the use of JWT tokens for user authentication.</li><li>jsonapi-serializer is a gem that will serialize ruby objects in JSON format.</li></ul><p>in gemfile add:</p><pre>gem &#39;devise&#39;<br>gem &#39;devise-jwt&#39;<br>gem &#39;jsonapi-serializer&#39;</pre><p>bundle install</p><h4>Set up devise:</h4><p>Run the following to create the <strong>installation</strong> files:</p><pre>rails g devise:install</pre><p>We need to tell devise we will not use navigational formats by making sure the array is empty in config/initializers/devise.rb. uncomment and edit the following line:</p><pre>config.navigational_formats = []</pre><p>This will prevent devise from using flash messages which are a default feature and are not present in Rails api mode.</p><p>We also need to add the following line at the end of config/environments/development.rb</p><pre>config.action_mailer.default_url_options = { host: &#39;localhost&#39;, port: 3001 }</pre><p>We will use port 3001 in our Rails app development and leave port 3000 for the React front-end app. To enable this, we also need to update the port PUMA (the default Rails server) will use in config/puma.rb</p><pre>port <em>ENV</em>.fetch(&#39;PORT&#39;) { 3001 }</pre><p>Next, we create the <strong>devise model</strong> for the user. It can be named anything. we will use User</p><pre>rails g devise User</pre><p>then run the first migration by executing:</p><pre>rails db:create db:migrate</pre><p>Next, we generate the <strong>devise controllers</strong> (sessions and registrations) to handle sign-ins and sign-ups</p><pre>rails g devise:controllers users -c sessions registrations</pre><p>we use the -c flag to specify a controller.</p><p>For devise to know it can respond to JSON format (and not try to render a view), we need to instruct the controllers:</p><pre>class Users::SessionsController &lt; Devise::SessionsController<br>  respond_to :json<br>end</pre><p>All the commented code can be removed since we will be writing our own methods to handle the steps.</p><pre>class Users::RegistrationsController &lt; Devise::RegistrationsController<br>  respond_to :json<br>end</pre><p>Then we must override the default routes provided by devise and add route aliases.</p><pre>Rails.application.routes.draw do<br>  devise_for :users, path: &#39;&#39;, path_names: {<br>    sign_in: &#39;login&#39;,<br>    sign_out: &#39;logout&#39;,<br>    registration: &#39;signup&#39;<br>  },<br>  controllers: {<br>    sessions: &#39;users/sessions&#39;,<br>    registrations: &#39;users/registrations&#39;<br>  }<br>end</pre><p>Now, the endpoints will be set to login, logout, and signup.</p><p>Devise works by allowing certain default parameters during user registration, for example, email, password, password confirmation, remember me, etc. In the application we are building we also want to let the user add a name and a picture (or avatar). To achieve this, we need to “sanitize” (or permit) these new parameters. We should add the following lines to the Application Controller:</p><pre>class ApplicationController &lt; ActionController::API</pre><pre>  before_action :configure_permitted_parameters, if: :devise_controller?</pre><pre>  protected</pre><pre>  def configure_permitted_parameters</pre><pre>    devise_parameter_sanitizer.permit(:sign_up, keys: %i[name avatar])</pre><pre>    devise_parameter_sanitizer.permit(:account_update, keys: %i[name avatar])</pre><pre>  end</pre><pre>end</pre><p>Here we permit the use of name and avatar for signup and updates of the user.</p><p>We now need to create a migration to add the name to the Users table:</p><pre>rails g migration AddNameToUsers name:string</pre><p>run rails db:migrate</p><p><em>(I will discuss the process of adding pictures or avatars in a different article)</em></p><h4>Set up devise-jwt</h4><p>devise-jwt will handle token dispatch and authentication, which doesn’t come with devise out of the box.</p><p>JWTs need to be created with a secret key that is private. It shouldn’t be revealed to the public. When we receive a JWT from the client, we can verify it with that secret key stored on the server.</p><p>We can generate a secret by typing the following in the terminal:</p><pre>bundle exec rails secret</pre><p>We will then add it to the encrypted credentials file so it won’t be exposed:</p><pre>#VSCode <br>EDITOR=&#39;code --wait&#39; rails credentials:edit</pre><p>Then we add a new key: value in the encrypted .yml file.</p><pre># Other secrets...  </pre><pre># Used as the base secret for Devise-JWT <br>devise_jwt_secret_key: (copy and paste the generated secret here)</pre><p>Inside the devise initializer, we will specify that on every login POST request it should append the JWT token to the ‘Authorization’ header as “Bearer + token” when there’s a successful response sent back, and on a logout DELETE request, the token should be revoked.</p><p>in config/initializers/devise.rb at the end add the following:</p><pre>config.jwt do |jwt|<br>    jwt.secret = <em>Rails</em>.application.credentials.devise_jwt_secret_key!</pre><pre>    jwt.dispatch_requests = [<br>      [&#39;POST&#39;, %r{^/login$}]<br>    ]<br>    jwt.revocation_requests = [<br>      [&#39;DELETE&#39;, %r{^/logout$}]<br>    ]<br>    jwt.expiration_time = 30.minutes.to_i<br>end</pre><p>In the JWT requests, we should delimit the regex with ^ and $ to avoid unintentional matches.</p><p>We are also setting the expiration time of the token to 30 minutes after which the user will need to authenticate again.</p><p><strong>Revocation strategy:</strong></p><p>As previously explained, tokens have an expiration date, they will become useless after that, but, because of their nature, they cannot realistically be revoked before that.</p><p>When would we want to revoke a token? When the user logs out.</p><p>Why would we want to revoke tokens? The bearer of the token has access granted to it, no further authentication is needed. So if a token is still active, and it somehow falls into the wrong hands, someone could access protected content and tamper with things.</p><p>The devise-jwt gem offers 3 different revocation strategies. We will use the JTIMatcher method.</p><p>from devise-jwt documentation:</p><blockquote>Here, the model class acts as the revocation strategy. It needs a new string column named JTI to be added to the user. JTI stands for JWT ID, and it is a standard claim meant to uniquely identify a token.</blockquote><blockquote>It works like the following:</blockquote><blockquote>When a token is dispatched for a user, the JTI claim is taken from the JTI column in the model (which has been initialized when the record has been created).</blockquote><blockquote>At every authenticated action, the incoming token JTI claim is matched against the JTI column for that user. The authentication only succeeds if they are the same.</blockquote><blockquote>When the user requests to sign out its JTI column changes, so that provided token won&#39;t be valid anymore.</blockquote><p>To use it, we need to add the JTI column in the user model. so we must create a new migration:</p><pre>rails g migration addJtiToUsers jti:string:index:unique</pre><p>And then make sure to add null: false to the add_column line and unique: true to the add_index line.</p><p>the migration file should look like this:</p><pre>class AddJtiToUsers<em> &lt; ActiveRecord::Migration</em>[7.0]</pre><pre>  def change</pre><pre>    add_column :users, :jti, :string, null: false</pre><pre>    add_index :users, :jti, unique: true</pre><pre>  end</pre><pre>end</pre><p>rails db:migrate</p><p>Then we have to add the strategy to the user model and configure it to use the correct revocation strategy:</p><pre>class User &lt; ApplicationRecord<br>  <strong>include Devise::JWT::RevocationStrategies::JTIMatcher</strong><br><br>  devise :database_authenticatable, :registerable, :recoverable, :validatable, <strong>:jwt_authenticatable</strong>, <strong>jwt_revocation_strategy: self</strong><br>end</pre><h4>Working with jsonapi_serializer:</h4><p>This serializer creates JSON responses following the JSON:API convention.</p><p>Since we already installed the gem using bundle install, we will create a serializer for the User model. We will call it every time we want to send user data from our API backend.</p><pre>rails g serializer user id email name</pre><p><em>(we will add the picture or avatar later)</em></p><p>It generates a serializer with the attributes mentioned that we can later call using the following command:</p><pre>UserSerializer.new(#user).serializable_hash[:data][:attributes]</pre><p>replace #user with the actual variable containing the user information.</p><p>After all the setups above, now we need to write the behavior of the app for user registration, login, and logout.</p><p>We will use some devise helper methods that tell the app what to do in different situations:</p><p>- respond_with: how to respond in the case of a POST (after registration or logging in)</p><p>- respond_to_on_destroy: how to respond to DELETE (after logging out)</p><p>in app/controllers/users/registrations_controller.rb:</p><pre>class Users::RegistrationsController &lt; Devise::RegistrationsController<br>  respond_to :json<br>  private<br><br>  def <strong>respond_with</strong>(current_user, _opts = {})<br>    if resource.persisted?<br>      render json: {<br>        status: {code: 200, message: &#39;Signed up successfully.&#39;},<br>        data: UserSerializer.new(current_user).serializable_hash[:data][:attributes]<br>      }<br>    else<br>      render json: {<br>        status: {message: &quot;User couldn&#39;t be created successfully. #{current_user.errors.full_messages.to_sentence}&quot;}<br>      }, status: :unprocessable_entity<br>    end<br>  end<br>end</pre><p>in app/controllers/users/sessions_controller.rb:</p><pre>class Users::SessionsController<em> &lt; Devise::SessionsController<br>  </em>respond_to :json</pre><pre>  private</pre><pre>  def <strong>respond_with</strong>(<em>current_user</em>, <em>_opts</em> = {})<br>    render json: {<br>      status: { <br>        code: 200, message: &#39;Logged in successfully.&#39;,<br>        data: { user: <em>UserSerializer</em>.new(<em>current_user</em>).serializable_hash[:data][:attributes] }<br>      }<br>    }, status: :ok<br>  end</pre><pre>  def <strong>respond_to_on_destroy<br>    </strong>if request.headers[&#39;Authorization&#39;].present?<br>      jwt_payload = <em>JWT</em>.decode(request.headers[&#39;Authorization&#39;].split(&#39; &#39;).last, <em>Rails</em>.application.credentials.devise_jwt_secret_key!).first</pre><pre>      current_user = <em>User</em>.find(jwt_payload[&#39;sub&#39;])<br>    end<br>    <br>    if current_user<br>      render json: {<br>        status: 200,<br>        message: &#39;Logged out successfully.&#39;<br>      }, status: :ok<br>    else<br>      render json: {<br>        status: 401,<br>        message: &quot;Couldn&#39;t find an active session.&quot;<br>      }, status: :unauthorized<br>    end<br>  end<br>end</pre><p>Since we created a Rails API-only app, sessions are disabled by default, but devise relies on sessions to function. Before Rails 7, sessions were passed as a hash, so even if they were disabled, devise could still write into <strong>a</strong> session hash. Since Rails 7, a session is an ActionDispatch::Session object, which is not writable on Rails API-only apps, because the ActionDispatch::Session is disabled. If we try to use devise in this configuration we will get the error:</p><p>ActionDispatch::Request::Session::DisabledSessionError (Your application has sessions disabled. To write to the session you must first configure a session store):</p><p>I was able to find a workaround to this problem by instructing devise to create a fake session hash. We add the following file app/controllers/concerns/rack_sessions_fix.rb:</p><pre>module RackSessionsFix</pre><pre>  extend <em>ActiveSupport</em>::Concern</pre><pre>  class FakeRackSession<em> &lt; Hash<br>    </em>def enabled?<br>      false<br>    end</pre><pre>    def destroy; end<br>  end</pre><pre>  included do<br>    before_action :set_fake_session</pre><pre>    private</pre><pre>    def set_fake_session<br>      request.env[&#39;rack.session&#39;] ||= <em>FakeRackSession</em>.new<br>    end</pre><pre>  end<br>end</pre><p>And we make sure to include this concern in our sessions_controller.rb and registrations_controller.rb before respond_to :json</p><pre>class Users::...Controller &lt; Devise::...Controller</pre><pre>  <strong>include RackSessionsFix</strong></pre><pre>  respond_to :json</pre><pre>  ...</pre><pre>end</pre><p>And that’s it. We can now create users, log in and log out.</p><h4>Testing with Postman:</h4><p>In our application terminal, run rails s to start the server.</p><p><strong>Creating a user:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qJpFkLxi0M7tTEPBmW9Ypg.jpeg" /><figcaption>Testing user creation with Postman</figcaption></figure><p>It is important to note the format in which the information should be submitted.</p><p><strong>Logging in:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tCGoNbCrN558P_Q2CzcAGA.jpeg" /><figcaption>Testing logging in with Postman</figcaption></figure><p>After we log in, we can check that the authorization token was received:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tXfNjg7hzq_J0a_Ly5By2w.jpeg" /></figure><p><strong>Logging out:</strong></p><p>When we log out the authorization token needs to be passed, for testing, we have to manually add it to Postman:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2VUyj0iIAdidFb7LWnUmkw.jpeg" /><figcaption>Testing logging out with Postman</figcaption></figure><p>For now, this is the testing we will make.</p><p>In the next article, I will explain how to add a profile picture to the User model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1397211fb97c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an app: from concept to deployment using headless Rails-API and React with Next.JS]]></title>
            <link>https://sdrmike.medium.com/building-an-app-from-concept-to-deployment-using-headless-rails-api-and-react-with-next-js-8d52cc343755?source=rss-89682b68f8e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d52cc343755</guid>
            <category><![CDATA[product-design]]></category>
            <category><![CDATA[figma]]></category>
            <category><![CDATA[rails-api]]></category>
            <category><![CDATA[schema-design]]></category>
            <dc:creator><![CDATA[Michael Epelboim]]></dc:creator>
            <pubDate>Thu, 27 Oct 2022 17:42:04 GMT</pubDate>
            <atom:updated>2022-10-27T17:42:04.853Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an app: from concept to deployment using headless Rails-API and React with Next.JS — Part 1</h3><h3>Part 1. The concept, prototype, and schema</h3><p><strong>Background:</strong></p><p>While learning to code in a Bootcamp, one of the projects we had to finish was a simple movie watchlist application. The application should introduce some movies to the user that they can add to a watchlist. I came up with an idea that turned out to be more complex than required and that if pursued, would take me more than the 2 days allocated for this. I completed an iteration of this idea, which was too simple for my taste, and barely met the class requirements.</p><p>Months after finishing the Bootcamp, while scrolling through my old repositories on GitHub, I came across this app and decided that with my skills at the time, I could improve it to a “portfolio-worthy” level, even make it an app I would use.</p><p>While the basic idea of the application remains the same, I decided to rewrite the whole thing and that this was an excellent opportunity to practice all sorts of skills related to building an application:</p><ul><li>UX/UI</li><li>Coding</li><li>Online research</li><li>Asking questions online on sites like StackOverflow</li><li>Working with external APIs</li><li>Deployment</li></ul><p><strong>The app:</strong></p><p>I am creating a movie watchlist application that allows users to discover or search for movies and, if logged in, to create watchlists and add or remove movies from them. Within the watchlist, users can mark the movies as watched.</p><p>The data on the movies will be obtained through TMDB’s APIs</p><p>The steps that I will follow to create this application are:</p><ol><li>Define the concept, map the user journeys</li><li>Create a prototype on Figma</li><li>Finalize the schema</li><li>Write the backend as a headless Rails-API, using Postman for testing</li><li>Deploy the backend using Fly.io</li><li>Write the frontend using React and Next.JS</li><li>Deploy the frontend using Vercel</li></ol><p><strong>Pain points:</strong></p><p>While there are many watchlist applications, I haven’t found one that has the features I mostly use or want, organized and displayed simply. I would like to see some specific information on the movies I look for including the streaming service provider, and for the watchlists, an average score of all the movies in it, as well as a total unplayed running time.</p><p><strong>User Journeys:</strong></p><p>The user, as a guest, will be able to search for movies and see the details of each movie, including an overview, score, genre, cast, director, trailer, recommended movies, and when available, the streaming service in the US that currently has that movie in their catalog.</p><p>The user will be able to create an account, and when signed in, will be able to create, edit and delete watchlists, add or remove movies in each watchlist, and mark each movie as watched or unwatched. Each watchlist will display the average score of all the movies in it as well as the total unwatched runtime.</p><p>Logged-in users will have easy access to their watchlists from the homepage as well as a history of the visited movies.</p><p><strong>The Prototype:</strong></p><p>I decided to go for a dark mode with red fonts, similar to Netflix, for familiarity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z0nGBZMBL-KqBEGZ2wefoA.jpeg" /><figcaption>Landing page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iBD8_FgEg9Siuc1evgow-g.jpeg" /><figcaption>Watchlist detail page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p6-xUNMqKmKE9lSy9GJRVw.jpeg" /><figcaption>Movie detail page</figcaption></figure><p>The full Figma design can be found here:</p><p><a href="https://www.figma.com/community/file/1121715218417063090">Figma</a></p><p><strong>The database schema:</strong></p><p>When creating schemas I find using the platform created by Ondřej Žára to be most useful, to the point, and visually clear. A blank schema can be created at:</p><p><a href="https://ondras.zarovi.cz/sql/demo/">WWW SQL Designer</a></p><p>Mine looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G32Ty3mdld2bzddNnSNC3A.jpeg" /></figure><p>I decided to use PostgreSQL as my database of choice, because of its integration with Rails, hence the foreign key connections.</p><p>My main tables will be:</p><ul><li>Movies</li><li>Users</li><li>Watchlists</li><li>Cast</li><li>Genres.</li></ul><p>The reset will be joint tables.</p><p>In <strong>part 2</strong> I will go into detail on how I built the backend with Ruby on Rails as a headless API app, using Devise and JWT for authentication.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d52cc343755" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>