<?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 coderSloth on Medium]]></title>
        <description><![CDATA[Stories by coderSloth on Medium]]></description>
        <link>https://medium.com/@codersloth?source=rss-69186b461ea------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*i1dcwZm2QcqnobK7P31UHg.jpeg</url>
            <title>Stories by coderSloth on Medium</title>
            <link>https://medium.com/@codersloth?source=rss-69186b461ea------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 17:02:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@codersloth/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Install Claude as a GitHub Action on a Pro or Max Subscription]]></title>
            <link>https://codersloth.medium.com/how-to-install-claude-as-a-github-action-on-a-pro-or-max-subscription-a8de7dc18c32?source=rss-69186b461ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8de7dc18c32</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[claude-code]]></category>
            <dc:creator><![CDATA[coderSloth]]></dc:creator>
            <pubDate>Sun, 03 May 2026 03:10:51 GMT</pubDate>
            <atom:updated>2026-05-03T05:02:25.629Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*vsDK3MVwvAmY0_KSoeuHVw.png" /></figure><p>If you have a Claude Pro or Max subscription and want Claude to respond to issues and pull requests in your GitHub repository (repo), the setup isn’t as obvious as it looks. Most of the setup guides assume you’ll authenticate with an ANTHROPIC_API_KEY from the developer console, which means you’re on pay-as-you-go billing. However, Pro and Max subscribers can authenticate with an OAuth token instead, and the workflow will use your existing subscription quota.</p><p>This guide walks through the subscription-based setup end to end. It also covers which Claude integrations are actually available on GitHub, who can use each one, and what they do.</p><h3>Who can use Claude on GitHub</h3><p>Anthropic offers two GitHub integrations with different eligibility rules:</p><ul><li><strong>Claude Code GitHub Action</strong>: This is called with @claude in an issue or PR comment. It’s available to anyone with a way to authenticate to Claude: an Anthropic API key (any account), a Pro or Max subscription, or an enterprise plan via Amazon Bedrock or Google Vertex AI. If you’re a Pro or Max user, this is the integration you’ll be using.</li><li><strong>Code Review</strong>: This is a managed service that automatically reviews pull requests using a fleet of agents on Anthropic’s infrastructure. Code Review is currently in research preview and is only available on Team and Enterprise plans. Pro and Max users can’t enable it, nor can organizations with Zero Data Retention turned on.</li></ul><h3>The setup for Pro and Max subscribers</h3><p>There are four required pieces: the Claude GitHub App (so Claude can read and write to your repo), an OAuth token (so the workflow can authenticate as your subscription), a repository secret (where the token lives), and a workflow file (which tells GitHub Actions what to run and when). You need to be a repository admin to do all of this. You don’t need the /install-github-app command or the gh CLI for this (both are optional).</p><p><strong>1. Install the Claude GitHub App<br></strong>Go to <a href="https://github.com/apps/claude">https://github.com/apps/claude</a> and install it. You’ll be asked which repos to grant access to: pick the specific repo or repos you want Claude to operate in rather than granting access to everything. The app needs read and write permissions for Contents, Issues, and Pull requests so it can post comments and push commits.</p><p><strong>2. Generate an OAuth token</strong><br>If you don’t have Claude Code installed locally, install it first npm install -g @anthropic-ai/claude-code and log in with your subscription. Then, in any terminal, run: claude setup-token.</p><p>This opens a browser, walks you through an OAuth flow, and prints a long-lived token to the terminal. Copy it — you’ll only see it once. The token is tied to your personal account and counts usage against your subscription limits.</p><p><strong>3. Add the token as a secret<br></strong>In the GitHub repo where you installed the app, go to <em>Settings → Secrets and variables → Actions → New repository secret</em>. Set the Name to CLAUDE_CODE_OAUTH_TOKEN exactly, with Value set to the token you copied during step 2.</p><p><strong>4. Create the workflow file<br></strong>GitHub Actions reads workflow files from .github/workflows/. If that directory doesn’t exist in your repo, create it at the root of your project. The following command will create both directories at once if they don’t already exist, and will not overwrite existing ones: mkdir -p .github/workflows.</p><p>Then create .github/workflows/claude.yml with this content:</p><pre>name: Claude<br><br>on:<br>  issue_comment:<br>    types: [created]<br>  pull_request_review_comment:<br>    types: [created]<br>  issues:<br>    types: [opened, assigned]<br>  pull_request_review:<br>    types: [submitted]<br><br>jobs:<br>  claude:<br>    if: |<br>      contains(github.event.comment.body, &#39;@claude&#39;) ||<br>      contains(github.event.issue.body, &#39;@claude&#39;) ||<br>      contains(github.event.review.body, &#39;@claude&#39;)<br>    runs-on: ubuntu-latest<br>    permissions:<br>      contents: write<br>      pull-requests: write<br>      issues: write<br>      id-token: write<br>    steps:<br>      - uses: actions/checkout@v4<br>        with:<br>          fetch-depth: 1<br><br>      - uses: anthropics/claude-code-action@v1<br>        with:<br>          claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}</pre><p>The key difference from the documented quickstart is that final block: claude_code_oauth_token instead of anthropic_api_key. This is required for users on Pro or Max subscriptions. Everything else mirrors the standard configuration, which supports explicitly calling @claude with a prompt in a comment on GitHub. It can be modified if needed to run Claude on a schedule or via some other automation.</p><p>Commit the file and push it to your default branch. GitHub will pick up the workflow automatically. You can confirm it registered by visiting the repo’s <strong>Actions</strong> tab and looking for a workflow named <strong>Claude</strong>.</p><p><strong>5. Test it</strong></p><p>Open or pick an existing issue in the repo and post a comment that includes @claude. For example: @claude can you summarize what this issue is asking for?</p><p>Within a minute or two, the <strong>Actions</strong> tab should show a run starting, and Claude should reply as a comment on the issue.</p><h3>How to use it</h3><p>Once it’s working, you trigger Claude by mentioning @claude in an issue body, an issue comment, a PR comment, or a PR review. Claude reads the surrounding context and acts on what you asked. Some patterns that work well:</p><ul><li>@claude implement this feature based on the issue description: Claude opens a PR addressing the issue.</li><li>@claude review this PR: Claude analyzes the diff and posts review comments.</li><li>@claude how should I structure the database schema for this?: Claude responds with a written answer in the comment thread.</li><li>@claude fix the failing tests: Claude inspects the failure, edits the code, and pushes a commit.</li></ul><p>You can also add a CLAUDE.md file at the root of your repo to give Claude project-specific guidance, such as coding standards, file-layout conventions, and things to avoid. Claude reads it on every run, so it’s the easiest way to keep behavior consistent without re-explaining context in every comment.</p><h3>What this costs</h3><p>Claude subscription quotas still apply. Heavy use of the action — long sessions, large repos, frequent invocations — eats into the same five-hour and weekly limits as your interactive Claude Code sessions. If you’re already using Claude Code intensively day-to-day, expect the GitHub Action to compound that usage rather than running freely on the side.</p><p>A practical mitigation is to cap the session length in the workflow with claude_args: &quot;--max-turns 5&quot; or similar. This stops Claude from looping on a hard problem and quietly burning through your quota.</p><p>You’ll also be charged for GitHub Actions minutes, which are billed by GitHub. Public repos get unlimited free minutes, while private repos get a monthly allowance that depends on your GitHub plan. Each @claude invocation consumes minutes for as long as the job runs.</p><h3>Things that commonly go wrong</h3><ul><li><strong>Claude doesn’t respond to</strong> @claude: Check that the GitHub App is installed on the specific repo (not just on your account). Ensure the repo has a secret named CLAUDE_CODE_OAUTH_TOKEN, the workflow file is on your default branch, and the comment uses @claude rather than /claude.</li><li><strong>Workflow runs but errors on authentication</strong>: The OAuth token can expire or be invalidated if you log out of Claude Code. Regenerate it with claude setup-token and update the secret.</li><li><strong>Claude’s commits don’t trigger CI</strong>: This is a GitHub default. Actions performed via GITHUB_TOKEN don’t trigger other workflows. If you need Claude’s pushes to trigger your test suite, you’ll need to set up a custom GitHub App and use its token instead. The <a href="https://code.claude.com/docs/en/github-actions#alternative-integration-methods">official docs</a> cover this in the advanced configuration section.</li><li><strong>Hitting the Pro plan’s usage limits faster than expected</strong>: If you’ve modified the workflow to add automation triggers like pull_request: [opened, synchronize], expect quota usage to climb fast.</li></ul><h3>When to use the API key path instead</h3><p>The OAuth route is great for personal projects and small teams where the work fits inside subscription limits. There are cases where an API key still makes more sense:</p><ul><li>You want predictable per-token costs rather than risking subscription throttling.</li><li>You’re running automation that processes far more volume than interactive use (nightly reviews of every PR across many repos, large-scale refactoring jobs).</li><li>You’re on a team account where multiple developers’ work shouldn’t all be billed against one person’s subscription token.</li><li>You need to use Bedrock or Vertex AI for compliance reasons.</li></ul><p>In those cases, set ANTHROPIC_API_KEY in your repo secrets and reference it as anthropic_api_key in the workflow file instead. Everything else stays the same.</p><h3>References</h3><ul><li>Claude Code Action repository: <a href="https://github.com/anthropics/claude-code-action">https://github.com/anthropics/claude-code-action</a></li><li>Setup guide (official): <a href="https://github.com/anthropics/claude-code-action/blob/main/docs/setup.md">https://github.com/anthropics/claude-code-action/blob/main/docs/setup.md</a></li><li>Claude Code GitHub Actions docs: <a href="https://code.claude.com/docs/en/github-actions">https://code.claude.com/docs/en/github-actions</a></li><li>Code Review (Team/Enterprise): <a href="https://code.claude.com/docs/en/code-review">https://code.claude.com/docs/en/code-review</a></li><li>Claude GitHub App: <a href="https://github.com/apps/claude">https://github.com/apps/claude</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8de7dc18c32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mind the data, don’t mine the data]]></title>
            <link>https://codersloth.medium.com/mind-the-data-dont-mine-the-data-a6a6157f11e3?source=rss-69186b461ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6a6157f11e3</guid>
            <category><![CDATA[expo]]></category>
            <category><![CDATA[react-native-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[data-privacy]]></category>
            <dc:creator><![CDATA[coderSloth]]></dc:creator>
            <pubDate>Thu, 30 Apr 2026 05:50:38 GMT</pubDate>
            <atom:updated>2026-06-02T19:20:41.776Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a budgeting app with no accounts, no servers, and no analytics</h3><p>Some years ago, I was talking to a coworker about budgeting apps. They wanted something simple: a way to track spending against a weekly budget without hooking it up to their actual bank accounts. They also wanted to log their own information without an app deciding what counted as “groceries” or pulling in transactions they didn’t want a third party to see. We looked around and couldn’t find anything that quite fit the bill.</p><p>That conversation became SimplyBudget, a small personal budgeting app I’m now rebuilding for Android (with iOS coming later). Its design is centered on letting users log expenses their way, where no data leaves the device without their say so. Storing data locally, rather than in the cloud, and being careful about what data is tracked, if any, greatly reduced the necessary security work for keeping user data safe.</p><p>This piece is about what that looks like in practice: what it actually protects and what it doesn’t. If you’re building something small and offline-leaning, and you’re staring down the cost of backend infrastructure you may not need, hopefully some of this is useful.</p><h3>What “your data, not mine” actually means</h3><p>The decision not to have user accounts was always central to the product idea. If the whole point is that you log your spending your way, on your terms, then storing that data on a server contradicts the premise. It doesn’t matter how careful I am with the data, because once it leaves your device, is that data really yours anymore, especially when some random app from some random developer is collecting it?</p><p>That decision has more benefits, especially for solo developers who want to provide free apps. There’s no auth flow or breach notifications to deal with, no cloud bill, and no worrying about helping users recover access after forgetting their passwords. That saves a lot of time, money, and compliance-related worry. I can’t protect users from physical threats to their devices, but I can guarantee that my cloud isn’t an attack vector by simply not having one.</p><p>Of course, there are tradeoffs, and those won’t be right for every app. There’s no cross-device sync: if a user loses their phone or wipes it without exporting first, their data is gone. There’s no shared budgeting between partners or family members. There’s no way for me to help a user recover anything, because there’s nothing on my end to recover from. For an app like this, that tradeoff is fine. The data fits comfortably on a device and the user is the only person who needs to see it. Recovery is the user’s responsibility, supported by an export feature they can run whenever they want.</p><h3>What “local storage” actually protects</h3><p>SimplyBudget relies on OS-level encryption and uses expo-sqlite with no application-layer encryption on top of it. The database file lives in the app&#39;s sandbox. The protection it gets comes from two layers underneath, rather than the app’s code:</p><ol><li><strong>App sandboxing:</strong> Other apps on the device can’t read SimplyBudget’s files. This is enforced by the OS.</li><li><strong>File-based encryption (FBE):</strong> On Android 10 and up, with a lock screen set, the user’s data is encrypted at rest using keys tied to their lock-screen credential. While the device is locked, those keys aren’t available, and the database file isn’t readable. Once the user unlocks the device, the keys come back and the app can read its data normally.</li></ol><p>That second point is why I’m planning to set the app’s minSdkVersion to 29. FBE became the default in Android 10, so older versions have weaker protection.</p><p>What this stack protects against:</p><ul><li>Other apps from poking around in SimplyBudget’s data. Sandboxing prevents this.</li><li>Someone picking up the locked phone and trying to read the database file offline. FBE handles this, assuming the user has a lock screen set.</li><li>A breach of my servers. There are no servers.</li></ul><p>What this stack does not protect against:</p><ul><li>A user who doesn’t use a lock screen at all. FBE’s protections evaporate without one. The app can’t fix that, and trying to (by demanding a passphrase) would defeat the no new credentials principle the whole design rests on.</li><li>A device that’s been unlocked and handed to someone else. Once the device is unlocked, the data is decrypted and accessible to the app.</li><li>A determined attacker with physical possession, time, and the right tools. Forensic extraction on a locked, modern Android device is hard but not impossible.</li><li>The user themselves exporting data and forgetting where they put it. Once data leaves the app via the share sheet, it’s entirely under the user’s control.</li></ul><p>I did consider using SQLCipher to add application-layer encryption but decided against it. For SQLCipher to actually add security on top of what the OS gives me, the encryption key has to live somewhere the OS layer doesn’t already protect. The options are: hardcode the key in the app (theater, since anyone who unpacks the APK has it), derive it from a user passphrase (which reintroduces the credential burden the app is built to avoid), or store it in the Android Keystore (which protects it using the same OS facilities I’m already relying on). The third option doesn’t add a meaningful layer for this threat model. The Keystore protects the key using the same lock-screen-bound encryption that’s already protecting the database file. An attacker who can defeat one can almost certainly defeat the other, so wrapping the database in a second layer that depends on the same root protections doesn’t improve security. It mostly adds complexity and more room for bugs.</p><p>There are apps where SQLCipher absolutely is the right call: a journalist’s notes app, a medical records app, anything where the threat model includes a sophisticated attacker with physical access and the user is willing to type a passphrase. But that’s not SimplyBudget.</p><h3>App lock as a UX layer, not a security layer</h3><p>SimplyBudget has an optional app lock setting that uses expo-local-authentication to gate access to the app behind the user&#39;s existing screen lock — fingerprint, face, PIN, whatever they already use to unlock their phone. It&#39;s off by default and lives in Settings. Turn it on, and opening the app prompts for the same biometric data or PIN the device uses before revealing the app.</p><p>This lock screen functions as a UI gate, and not an additional layer of encryption. The database is just as readable to the app whether the lock is on or off. It’s simply preventing the app from drawing its UI until the user re-authenticates with the device.</p><p>The lock serves a very specific purpose: what happens when the device is unlocked and someone other than the user is looking at the screen? A partner picking up the phone to check a recipe, a child playing a game, someone borrowing the phone to make a call. In all of these cases, the OS-level encryption is already off because the device is unlocked. Sandboxing still keeps other apps out, but it doesn’t keep the Nosy Nellies out.</p><h3>Collect less, leak less</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fsoekde4hY8OQt-esQBy3A.png" /><figcaption>The expense form lets users choose what data to disclose</figcaption></figure><p>The strongest privacy guarantee for a piece of data is that it was never recorded in the first place. SimplyBudget takes that principle seriously by requiring a minimal amount of data when inputting expenses.</p><p>An expense has three required fields: an amount, a date, and a category. A small set of categories ships with the app — Food, Transportation, Bills, that sort of thing — and the user can add their own custom categories on top of those, with full edit and delete control over the ones they create. There’s also an optional description field, which is a free-text input the user can use however they want. That’s it. No additional data, like locations or vendor names, are required. This gives users the freedom to determine how much data to disclose. For example, they could place all expenses under the “Other” category without any description if they were worried about others finding out what they were spending their money on specifically.</p><p>The data on the device is a smaller, vaguer record of someone’s spending than what most apps would have collected. Even in a worst-case scenario where the device protections fail and someone reads the file, what they get is a list of amounts, dates, and whatever labels the user picked, with no external context attached. That’s still personal information, but it’s a meaningfully smaller surface than “every transaction with merchant, location, and category inferred from a payments API.”</p><h3>The one third party in the room</h3><p>There’s exactly one place in SimplyBudget where data leaves the device: crash reporting. I need to know when the app crashes and on which devices, and roughly where in the code it failed. Without that, I’m relying on users to manually report problems, which they almost never do, and to describe them accurately, which they almost never can (not their fault by the way). Shipping an app with no crash reporting would mean shipping an app I can’t reliably fix, which is pretty unacceptable in my opinion.</p><p>So SimplyBudget uses Firebase Crashlytics for crash reporting in a somewhat constrained manner:</p><ul><li><strong>Opt-in:</strong> Crash reporting is off by default, so users aren’t secretly opted in; it has to be their choice.</li><li><strong>No analytics:</strong> I don’t use Google Analytics or any other usage tracking.</li><li><strong>No spending data ever leaves the device:</strong> Crash reports include device info, OS version, the stack trace, and breadcrumbs. They do not include any user-entered content, like amounts, categories, or descriptions.</li><li><strong>Breadcrumbs are constants:</strong> Breadcrumbs in SimplyBudget are predefined strings like &quot;tapped add expense&quot; or &quot;opened settings&quot;. This is enforced by compile-time type checking that ensures only one of the predefined strings is passed to the method that wraps the Crashlytics&#39; log method.</li></ul><p>If you’re going to involve a third party, the useful question isn’t whether you intend to send only safe data, but whether your code makes it possible to send anything else.</p><h3>When this approach stops working</h3><p>Everything in this article applies to a particular type of app: small, personal, single-device, with data that doesn’t need to be shared, synced, or recovered by anyone other than the user. This, of course, is not every app, nor should it be!</p><p>The moment you want any of the following, everything changes. This isn’t an exhaustive list, but it covers some common cases:</p><ul><li><strong>Cross-device sync:</strong> If a user expects their data to show up on their tablet or in a website, you need a server, and the server needs to know who the user is, which means accounts.</li><li><strong>Sharing:</strong> E.g., family budgets, shared expenses, partner access. The moment two or more users need to see the same data, you need identity, permissions, and a backend that can enforce them.</li><li><strong>Recovery:</strong> If users expect to be able to wipe and reinstall their phone without losing data, you need cloud storage and a way to authenticate them back in if relying on manually-stored backups is too risky.</li><li><strong>Anything social:</strong> E.g., leaderboards, comments, sharing publicly, anything where users interact with each other.</li></ul><p>For any of those, the right answer likely isn’t to roll your own auth and storage. Authentication is difficult to get right and easy to get wrong, and the consequences when it goes wrong are very large — leaked credentials, account takeovers, breach notifications, and more! Mature identity providers like Auth0, Clerk, or Supabase exist because this work is genuinely hard, and outsourcing it to people who specialize in it is almost always the right call for a small team. The goal is to use the right tool for the job after considering all of the tradeoffs.</p><h3>Wrapping up</h3><p>When my coworker and I were complaining about budgeting apps all those years ago, neither of us said “I want a privacy-first app with no server-side data collection.” (Doesn’t that just roll right off the tongue?) We just wanted something simple — something that didn’t connect to our financial accounts and let us log things our way. The privacy posture came later, almost as a side effect of taking the original frustration seriously.</p><p>I think a lot of these decisions actually work that way: you aim to design an app that does what the user wants without doing things the user didn’t ask for. Keeping the user top of mind at all times can lead to needing fewer (or no) servers, smaller schemas, and shorter privacy policies that are easier to defend. So before designing any app, ask yourself “what data needs to leave the device, and why, for this product to work?”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6a6157f11e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Remaking SimplyBudget with Claude Code Part 2]]></title>
            <link>https://codersloth.medium.com/wip-remaking-simplybudget-with-claude-code-part-2-d408420c65c7?source=rss-69186b461ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/d408420c65c7</guid>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[expo]]></category>
            <dc:creator><![CDATA[coderSloth]]></dc:creator>
            <pubDate>Wed, 15 Apr 2026 10:38:10 GMT</pubDate>
            <atom:updated>2026-04-20T05:55:38.687Z</atom:updated>
            <content:encoded><![CDATA[<h4>This article covers my process of converting the web MVP to a React Native app. In Part 1, I rebuilt my old budgeting web app MVP using React and Claude Code. Now it’s time for the mobile version.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1-oSTbe3NjtibQbjoRAkAg.png" /><figcaption>Screenshots from SimplyBudget — mockups made with MockUPhone</figcaption></figure><h3>Background</h3><p>Around six years ago I created an MVP for a budgeting web app called SimplyBudget. I had always planned on turning it into a mobile app, but life happened and I never got around to it. Recently, I decided to rebuild that MVP using React and Claude Code. You can read about that in <a href="https://codersloth.medium.com/remaking-simplybudget-with-claude-code-part-1-4696a6f5674d">Part 1</a> if you like, though it’s not necessary.</p><p>I’ve never built a mobile app using React Native before, but with Claude Code by my side, I feel a lot better about it. So here we go!</p><h3>Main Tools Used</h3><ul><li>Frontend: Expo / React Native / TypeScript</li><li>Data: expo-sqlite</li><li>Charts: react-native-gifted-charts</li><li>Authentication: expo-local-authentication</li><li>Testing: Jest / Expo Go / Android Studio Emulator / iOS Simulator from Xcode</li><li>Coding: Claude Code (Pro plan)</li><li>Design: Claude + Me</li><li>App Icon: Affinity Designer 2</li><li>Crash reporting: Firebase Crashlytics</li></ul><h3>Repos</h3><ul><li><a href="https://github.com/helloRupa/simplybudget-native">React Native SimplyBudget</a></li><li><a href="https://github.com/helloRupa/simplybudget">Web MVP SimplyBudget</a></li></ul><h3>Phase 0: Initial Planning and Setup</h3><p>Since I already have a <a href="https://hellorupa.github.io/simplybudget/">web MVP</a> built in React ready to go, I need to work with Claude to convert that to a React Native app using Expo. I haven’t done this type of project with Claude before, so my first stop is a conversation to figure out how best to work with Claude. Here’s my first prompt: “I have a React project for web which is already complete. I want to create a new version of this project in React Native for Android and iOS. How do I best work with Claude Code to do this?”</p><p>Claude’s guidance was clear and simple. This is a compacted version:</p><ol><li>Set up a CLAUDE.md file to be the project’s permanent brain. Include a project summary, target platforms, technologies to use, and state management details.</li><li>Plan before building. Ask for an implementation plan and tell Claude Code not to write any code yet. Review the plan and make any necessary changes.</li><li>Break the work into phases. Do not do it all at once.</li></ol><p>Claude provided more steps, but I’ll leave it here for now, since these represent the core flow. I’ll note that the steps are strikingly similar to how a person would go about doing the work manually.</p><p>Since I’m new to creating React Native apps, I also needed to figure out which dependencies to install. I chatted with Claude about options for charting, storing data, using a pin code to access the app, and more. Each time Claude made suggestions, I checked in with myself to ensure I was asking important questions. For example, I’m not familiar with how different types of data storage persist their data in mobile apps, so I asked Claude which actions would cause an app’s AsyncStorage to be cleared and how that compares to using expo-sqlite. Learning that AsyncStorage can be automatically cleared if the device is low on storage on iOS helped me decide that expo-sqlite was the way to go, not only for the expenses data but also for settings data, since some of its contents are crucial for performing calculations accurately. I also ensured that the dependencies chosen would not incur any costs, since this app will be free if released.</p><p><strong>Project Setup</strong></p><p>I decided to set up the project myself instead of asking Claude to do it. I wanted to familiarize myself with the basics of an Expo app before working with Claude Code, so I could be better at directing and evaluating its work (hopefully). Also, I could save some tokens.</p><p>I started by following Expo’s <a href="https://docs.expo.dev/tutorial/create-your-first-app/">Create Your First App tutorial</a>. This gave me a better understanding of how traditional React concepts map to React Native, and how HTML elements map to React Native Components. For example, rather than using an h1 tag or a p tag, React Native uses a Text component. I created tabbed navigation, some links, and some placeholder screens. Nothing amazing, but enough to get my feet wet.</p><p>Afterwards, I installed the following packages in my project:</p><ul><li><strong>expo-document-picker</strong>: access a user’s documents to support importing backup data</li><li><strong>expo-file-system</strong>: export data</li><li><strong>expo-sqlite</strong>: store all expense-related and settings data required for the app to run</li></ul><p><em>Note: more packages are installed later as needed.</em></p><p><strong>More Planning with Claude</strong></p><p>I then worked with Claude to create the initial <a href="https://github.com/helloRupa/simplybudget-native/blob/master/CLAUDE.md">CLAUDE.md</a> file and added it to the root of my project. It included information on where to find the original project, how to map HTML elements and browser APIs to React Native, coding rules, and more. The <a href="https://github.com/helloRupa/simplybudget-native/tree/master">repo</a> is public, so you can check out the commit history and see how it’s changed over time as the project evolved. Notably, it includes a section that Claude updates any time it gets corrected and needs to learn from its mistakes.</p><p>Next, I created an <a href="https://github.com/helloRupa/simplybudget-native/blob/master/.claude/commands/audit.md">audit command</a> to instruct Claude to analyze the original web project to produce a report detailing the project’s components, each component’s complexity, and web APIs that needed to be replaced with React Native equivalents. After running the audit, I checked the report for accuracy, and then added and ran a <a href="https://github.com/helloRupa/simplybudget-native/blob/master/.claude/commands/plan.md">plan command</a>. That command created an MD file detailing the implementation phases, tasks to complete, and the SQLite schema.</p><p>I used the Sonnet model for both the audit and the plan, since it didn’t seem like deep reasoning was needed. I switched to Opus when I noticed major issues with Sonnet’s work. For example, the SQLite schema in the migration plan was obviously wrong, so I used Opus to analyze specific files in the original project and reproduce the schema. Opus got most of it right, but there was still a little more editing required to ensure the columns had the correct constraints. Outside of the schema, I also noticed there were references to the About modal, but there was no information on where it would live. I worked with Sonnet to choose an appropriate location and Sonnet updated the migration plan.</p><p>At the end of all of this planning, we ended up with these implementation phases:</p><ol><li>Create the foundation and navigation shell</li><li>Establish the data layer with SQLite</li><li>Create the global budget state backed by SQLite</li><li>Port all stateless or almost stateless components</li><li>Port the expense screens (list, form, recurring expense manager)</li><li>Port the most complex screens: Dashboard and Settings with backup/restore</li><li>Polish and Cross-Platform QA: check styles and test behavior for consistency and accessibility</li></ol><p>And with that, we’re finally ready to build! There will probably be more planning along the way, but for now, it is BUILDING TIME!</p><p><em>A quick note: Unless otherwise noted, Sonnet is the model in use throughout this project.</em></p><h3>Phase 1: Create the Foundation and Navigation Shell</h3><p>This part was extremely straightforward and fast. I simply told Claude to execute phase 1 of the migration plan, and then (drum roll please), it did. At the end of its work, it produced a three-tab navigation layout with placeholder screens using the theme from the original web app. I checked that the tabbed navigation worked using Expo Go, and then reviewed the code. The review resulted in one more prompt: “separate the global colors into constants that can be reused throughout the app, and then update CLAUDE.md with this information to ensure colors are reused.” After that, I cleared the conversation since the next phase didn’t require any knowledge of Phase 1.</p><h3>Phases 2–3: Establish the Data Layer</h3><p>Once again, I started by telling Claude to execute the specific phase from the migration plan: Phase 2. This time I also requested tests and to mock as little as possible to avoid false passes or failures. Claude sprinted through setting up the local database, tables, and tests. It even added better-sqlite3 (a Node-compatible SQLite library) so it could test actual SQL queries without excessive mocking (expo-sqlite doesn’t run in Node.js, so this allows tests to run against a real database).</p><p>The code looked good upon review. So far, all of the upfront planning was paying off! At this point, I compacted the conversation, since knowledge of the SQLite schema and implementation were necessary for Phase 3: Create the global budget state.</p><p>Phase 3 went by quickly — it was only about 5 minutes until Claude declared it “baked”. For this phase, Claude installed any compatible and necessary packages from the web project and copied over several files that would work as is. Claude also ported over the original shared BudgetContext and rewrote it for use with SQLite.</p><p>The initial app run failed with:Render Error: Call to function ‘NativeDatabase.prepareSync’ has been rejected. Caused by: Error code : no such table : expenses</p><p>I gave Claude the error and reproduction steps. I also asked if it remembered to initialize the database when the app loads if one does not already exist. Claude responded that it had forgotten to do that and quickly fixed the issue.<br><br>At this point, I realized we hadn’t fleshed out how to handle category colors (categories are used to organize spending entries), and it looked like Claude had assumed that we were going to allow users to pick custom colors for user-created categories. This behavior was markedly different from the web app. I instructed Claude to add a custom palette of colors to choose from, and to then apply one at random any time a custom category was created. Claude then happily added the color palette, made all code changes, and updated tests until they passed.</p><p>Once again, I checked that the app could run successfully in Expo Go, and then cleared the conversation before moving on to the next phase.</p><h3>Phase 4: Port Stateless Components</h3><p>For SimplyBudget, simple components include the Toast, About Modal, and the AppName (used to display the app’s name in teal and white text). Claude finished this work within minutes. However, Claude had a couple of minor hiccups:</p><ul><li>The info icon was ported over from the web app and was being used to open the About modal on tap. According to the migration plan, the About modal should live in Settings.</li><li>Claude forgot to update the colors object and use tokens instead of bare color strings. CLAUDE.md explicitly states that colors should be stored in the colors constant and reused.</li></ul><p>I asked Claude what had happened when porting the About modal and asked if there was a mistake somewhere in our plans. Claude confirmed that the plans were good — it was a mistake made when porting the code from the web app, which contains that behavior. When asked about the missing color tokens, Claude stated that it didn’t know what to do when a color token didn’t already exist. In response, I asked Claude to update CLAUDE.md with a rule to add tokens when it encounters new colors.</p><blockquote>Lessons learned: Be extremely vigilant when porting features that may be visually or functionally different from the original implementation. When specifying rules, be very specific with all cases accurately described, e.g., what to do when encountering new colors.</blockquote><h3>Phase 5: Port Medium-Complexity Screens</h3><p>I cleared the conversation and we began Phase 5, which included porting over the expense forms and lists. This took about 20 to 30 minutes of “sautéing”. The first test run for adding an expense didn’t work out due to a missing package. Luckily, that was an easy fix: just import the package!</p><p>Claude didn’t realize negative expenses are allowed, even though that is a feature of the web app. I gave Claude specific instructions to allow negative expenses and also provided the exact file that required the fix as well as the “why” behind this decision (an item could be returned or a total could be adjusted). However, Claude got a little too excited and “fixed” the recurring expenses, which are always positive values, too. I prompted Claude to undo that change, and it did so without complaint.</p><blockquote>Lesson learned: It’s a good idea to provide the product requirements even when porting an existing project. I’m guessing this would help prevent it from happening again. Either that, or say “only fix what I’m mentioning”.</blockquote><p>At this point, I could navigate between the different screens via the navigation tabs, add expenses, and view my expenses list. Certainly good progress!</p><p>I decided to take a minor diversion and take care of some of the visual issues that were bothering me:</p><ul><li>There was a white flash when transitioning from one screen to another.</li><li>The Expense form’s header area was white.</li></ul><p>I provided Claude with screenshots and descriptions of the issues. It took a few tries for Claude to get it right. Claude first tried changing Stack.Screen’s background color, followed by adding an animation. When those solutions didn’t work, Claude updated the app.json file that sets the app’s background colors. And with that, the white flash was gone!</p><p>Since this phase was over and Claude didn’t need to know about it for the next phase, I cleared the conversation before moving on.</p><h3>Phase 6: Port the Most Complex Screens</h3><p>This phase involved creating the Dashboard and Settings screens, which also support importing and exporting data in different formats. Claude took a while to complete this work — a Claude while though, not a human while. The first app run failed due to a missing package. Once again, this was an easy fix for Claude. I then noticed that the formatting of the Dashboard was a little off, so I had Claude fix that too by describing the issues alongside a screenshot.</p><p>The most involved issues to fix during this phase included:</p><ul><li>Getting the bar chart tooltip, which shows the user’s spending vs. budget per week, to render in the correct location and layer.</li><li>Getting the math right for the total overspent or saved for all time.</li></ul><p>For the tooltip, I had to provide a very specific prompt defining exactly how I wanted it to work. This included information on where it renders on the screen relative to the chart’s bars and within the visual layers, or stack. I also had to define the close behavior. Each time the tooltip rendered in the wrong location, I provided a screenshot and guidance to help fix the issue.</p><p>In the web MVP, Claude struggled to correctly calculate the total overspent or saved for all time, and the same was true in the mobile app even though Claude was porting an existing project. The issue was the same as before: failing to use each week’s set budget to calculate the total allowed spend. To fix the issue, I gave Claude example budget data along with the correct calculations and explanations of those calculations. I also asked Claude to add three weeks’ worth of mock data that was accessible in DEV mode only. That information seemed to be enough for Claude to make the appropriate fix.</p><blockquote>Lesson learned: Don’t expect Claude to understand nuanced behavior even when porting an existing project. Spell it all out explicitly.</blockquote><p>There were some other issues, like setting the app’s first use date to the wrong date, but those were pretty quick and easy to solve. However, I did ask Claude some questions about the implementation before closing out the session to confirm everything was working as I expected. I find it’s a good practice to get Claude to answer questions about its work before moving along. For example, I asked Claude if the data import function expected data to be in the same shape as the actual exported data. I also asked if recurring expenses were no longer added to the expense list once their end dates had passed.</p><p>Since we’d spent quite a while on logic and data, I wanted to take another diversion to take care of some low-hanging fruit, like styling future expenses and expired recurring expenses. I also noticed that I wasn’t a fan of how the Monthly Spending section looked on the Dashboard. Using category cards worked fine on web, where there’s lots of horizontal space, but on a slim screen, it could cause the Dashboard’s scrollable height to increase significantly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*-Hnt90tEUdV1dztZqRIhOg.png" /><figcaption>Layout for monthly spending in the web MVP using category cards</figcaption></figure><p>I asked Claude for some options on how to present this data. Claude gave several, but they involved adding many rows of data or showing/hiding data on tap or scroll. I suggested a pie chart could work, and Claude came back with an even better option: a donut chart! After that, I requested a plan for making this change, which needed to include information on handling very small slices of data and adding a legend mapping colors to categories. Claude provided a solid plan, and then got to work on the implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Lm13oHrSut2QHReAq-5eg.png" /><figcaption>Donut chart from the Expo React Native app</figcaption></figure><p>At this point, I played with the app some more and noticed another issue: the text “(tabs)” was showing next to the back button on some screens. I gave Claude a screenshot of the issue and reproduction steps, but after a couple of tries the issue persisted. Claude then suggested creating a custom header area with a back button. To my human brain, this seemed like it was probably a bit much, so I decided to look into the issue myself, which only took a few minutes of wandering the web. Fortunately, it was an insanely simple fix: add an empty string as the title for the Stack.Screen called “(tabs)”. When the title is not provided explicitly, the route name is used by default.</p><h3>Phase 7: Polish and Cross-Platform QA</h3><p>This was a fairly uneventful phase, which in my opinion, is a very good thing. Claude checked for possible cross-platform issues regarding missing fallbacks and polyfills, potential areas where content could overlap, inconsistent styles, accessibility, and more! Each time Claude found an issue, it fixed it and updated tests without needing any input from me.</p><p>When Claude was done, I asked for a test coverage report and to identify the highest-priority areas for adding more tests. Claude found significant gaps for the recurring expenses, so it went ahead and updated those tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qi4F0DU4INIHDW78sEWk3Q.png" /><figcaption>SimplyBudget’s official icon, justice not required</figcaption></figure><p>I also decided to take care of the app’s iconography. Instead of using AI, I decided to draw the vector artwork myself using Affinity Designer. I wanted to create a frog, but due to my obsessive nature, what should have been a short task started to become a long task. This was not where I wanted to put my time, so I created a coin instead. There’s no way I’d care as much about a coin graphic when compared to a cute frog. Frogs are adorable and I’d have to do them justice; coins are not adorable.</p><h3>AI Code Review</h3><p>Instead of using my existing code review command, I decided to install a code review skill from <a href="https://www.aitmpl.com/component/skill/development/code-reviewer">AI Templates</a>. Before using the skill, I looked at all of its source code to ensure there was nothing malicious. I also had Claude review it before installation to double-check my findings. I asked Claude to look for security holes, like transmitting data across networks or making changes to my system. Claude determined the skill was safe, so I went ahead and installed it.</p><p>The review resulted in finding two bugs and a refactoring suggestion:</p><ul><li>Bug 1: In the Budget vs Spending chart, the budget data wasn’t being mapped to the bars correctly.</li><li>Bug 2: Existing budget data wasn’t being cleared when budget data was being imported.</li><li>Refactor: The recurring expenses file was far too long and would benefit from separating the form code from the list code.</li></ul><p>The bug fixes took a little extra prompting. For example, Claude initially updated the wrong method when fixing the Budget vs Spending chart data. I pointed Claude to the right place and then it fixed it without issue. For Bug 2, Claude initially cleared the existing data before the import transaction began. That meant if the import failed partway through due to malformed data, the user would lose their existing data with no rollback possible. I told Claude to clear the data in the same transaction as the import to ensure the database could roll back successfully. The fix was in! There were no notes on the refactor!</p><h3>Add More Features</h3><p>Since this is a mobile app, I decided we should add some new features to take advantage of the platform. These included:</p><ul><li>Optional screen lock: From the Settings screen, users should be able to enable or disable an app lock setting that utilizes the user’s default screen lock method to protect the user’s data. Expenses can be quite personal!</li><li>Optional notifications: From the Settings screen, users should be able to opt into or out of a daily notification reminding them to add expenses and a weekly notification reminding them to back up their data.</li><li>Optional crash reporting: We should send crash reports with generic breadcrumbs to understand when and how the app is failing. Users should opt in on the Settings screen. If opted in, Firebase Crashlytics will be enabled.</li></ul><p>These features are fairly nuanced, so they took longer to develop than other features. For example, knowing when to show/hide/disable the screen lock took some planning, and Claude needed a few tries to get Crashlytics set up correctly with logging. Also, React Native Firebase requires custom native code, which can’t be used with Expo Go, so I had to switch to Android Studio’s emulator. The installation took quite a while.</p><h3>Privacy Policy</h3><p>It’s my goal to release this app for free for both Android and iOS. Both the Play Store and App Store require up-to-date privacy policies for submission, so I turned to Gemini to craft a policy for SimplyBudget. After some back and forth, we landed on a pretty solid policy based on my understanding of the app. I fed this policy to Claude Code and asked it to review each item on a scale of 1 to 5, with 1 being “this item is completely false” and 5 being “this item is completely true”, along with a short explanation for the score.</p><p>Claude compared each item to the app’s implementation and gave me some suggestions for improvements. I implemented the ones I agreed with, like specifying the type of notifications the app uses and an improved description about policy updates, and then asked Claude to link to the policy on the Settings screen.</p><h3>Conclusion</h3><p>At this point, I’m fairly certain I have a solidly working app. However, I am a paranoid programmer and need to do further testing to be sure of that 😁. My next steps are testing the app some more, making preview builds for iOS and Android, and getting better acquainted with the rules and costs associated with submitting an app to each store. All of that and more can be yours in Part 3! (Well, probably not more — I don’t know what “more” would be.)</p><p>One final note: I’m still happy developing in phases, rather than attempting to make a whole app at once. I feel it’s easier to test and confirm results in this manner. Also, if something does go wrong, it’s easier to catch and debug since I’m more likely to know when it went wrong and have reasonable chunks of testable behavior, rather than one gigantic chunk. Lastly, it’s a lot easier to review code in phases than a whole lot of code all at once. For example, Claude and I were making some updates to the database code to enforce strict types, and Claude changed the code in a way that would have caused the tables to be dropped every time the app loaded. This behavior would have prevented data from persisting, which I likely would have caught during manual testing, but I’d rather not let such a bug get that far.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d408420c65c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Auto-Deploying Your Next.js App to GitHub Pages]]></title>
            <link>https://codersloth.medium.com/auto-deploying-your-next-js-app-to-github-pages-47ded703532b?source=rss-69186b461ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/47ded703532b</guid>
            <category><![CDATA[nextjs-deployment]]></category>
            <category><![CDATA[continuous-deployment]]></category>
            <category><![CDATA[github-tutorial]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[coderSloth]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 23:37:56 GMT</pubDate>
            <atom:updated>2026-04-06T23:37:56.684Z</atom:updated>
            <content:encoded><![CDATA[<h4>A friendly guide based on deploying SimplyBudget</h4><p>You’ve built a Next.js app and want to automatically deploy to GitHub Pages every time you push to your main or master branch (or some other branch). No manual builds or uploads, no fussing about. Here’s how to do it.</p><p>The whole setup comes down to three things: telling Next.js to export a static site, writing a GitHub Actions workflow that does the building and deploying for you, and flipping a switch in your repo settings. Let’s go!</p><h3>Step 1: Configure Next.js for Static Export</h3><p>GitHub Pages serves static files, so you need to tell Next.js to produce a folder of HTML, CSS, and JavaScript instead of a server-rendered app. Locate your nextConfig (mine was in next.config.mjs) and add the following:</p><pre>const nextConfig = {<br>  output: &#39;export&#39;,<br>  basePath: &#39;/your-repo-name&#39;,<br>  assetPrefix: &#39;/your-repo-name/&#39;,<br>  images: { unoptimized: true },<br>};<br>export default nextConfig;</pre><p>The basePath setting is the part people most commonly get wrong. GitHub Pages doesn’t serve your app from the root of a domain: it serves it from a path like /your-repo-name. Without basePath, your assets will 404. Make sure it matches your repository name exactly. My repo’s name is “simplybudget”, so the basePath and and assetPrefix in my project are both set to “/simplybudget”.</p><p>Since this is a frontend-only app and I didn’t use the Next.js Image component, I’ve set image optimization off: “images: { unoptimized: true }”.</p><h3>Step 2: Create the GitHub Actions Workflow</h3><p>Here comes the automation! Are you ready!?</p><p>Create a file at .github/workflows/deploy.yml in your project’s root. This file tells GitHub what to do every time you push to main/master (or whichever branch you wish to deploy from).</p><pre>name: Deploy to GitHub Pages<br><br>on:<br>  push:<br>    branches: main # update to match your target branch/es<br>  paths-ignore:<br>      - &quot;**/README.md&quot;<br><br>permissions:<br>  contents: read<br>  pages: write<br>  id-token: write<br><br>concurrency:<br>  group: pages<br>  cancel-in-progress: false<br><br>jobs:<br>  test:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v5 # check GitHub for latest version<br>      - uses: actions/setup-node@v4 # check GitHub for latest version<br>        with:<br>          node-version: &#39;25.x&#39; # match your project or choose the latest stable release<br>          cache: npm<br>      - run: npm ci<br>      - run: npm test -- --watchAll=false --passWithNoTests<br><br>  build-and-deploy:<br>    needs: test<br>    runs-on: ubuntu-latest<br>    environment:<br>      name: github-pages<br>      url: ${{ steps.deployment.outputs.page_url }}<br>    steps:<br>      - uses: actions/checkout@v5 # check GitHub for latest version<br>      - uses: actions/setup-node@v4 # check GitHub for latest version<br>        with:<br>          node-version: &#39;25.x&#39; # match your project or choose the latest stable release<br>          cache: npm<br>      - run: npm ci<br>      - run: npm run build<br>      - uses: actions/upload-pages-artifact@v3 # check GitHub for latest version<br>        with:<br>          path: ./out<br>      - id: deployment<br>        uses: actions/deploy-pages@v4 # check GitHub for latest version</pre><p><strong>What’s happening here?</strong><br>The workflow has two jobs that run in sequence:</p><ul><li>test: runs your Jest suite first. If any tests fail, the project will not deploy. This prevents you from shipping broken code.</li><li>build-and-deploy: installs dependencies, runs next build (which produces the out/ folder thanks to “output: ‘export’”), uploads that folder, and deploys it to GitHub Pages.</li></ul><p>The “needs: test” line under “build-and-deploy” is what connects the two jobs. It ensures the deploy job only runs if the test job succeeds.</p><p>There’s no need to test and rebuild the app if README.md is updated, so “paths-ignore” is added to prevent that from happening. If you want to prevent deployment when any .md file is updated, modify the entry from “**/README.md” to “**.md”. You can add as many items as you need. Conversely, you can also trigger a deployment when certain files are updated using the “paths” entry.</p><p>You can find more information on the Workflow syntax in <a href="https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax">GitHub Docs</a>.</p><h3>Step 3: Enable GitHub Pages in Your Repo</h3><p>Head to your repository on GitHub, then go to Settings → Pages. Under Source, select GitHub Actions (not the “Deploy from a branch” option). Save it, and you’re done with the settings side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*LapeRD9kTu1kSWC23BxCxQ.png" /></figure><h3>Step 4: Push and Watch It Go!</h3><p>Commit your new workflow file and config changes, then push your branch!</p><p>Go to the Actions tab in your repo and you’ll see the workflow running. Once it finishes, your project will be live at: <a href="https://your-username.github.io/your-repo-name/">https://your-username.github.io/your-repo-name/</a></p><p>From this point on, every push to your deployment branch triggers the whole process automatically: tests first, then build, then deploy. No more thinking or manual deployment!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47ded703532b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Remaking SimplyBudget with Claude Code, Part 1]]></title>
            <link>https://codersloth.medium.com/remaking-simplybudget-with-claude-code-part-1-4696a6f5674d?source=rss-69186b461ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/4696a6f5674d</guid>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[ai-assisted-coding]]></category>
            <dc:creator><![CDATA[coderSloth]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 04:08:26 GMT</pubDate>
            <atom:updated>2026-04-15T10:41:17.063Z</atom:updated>
            <content:encoded><![CDATA[<h4>This article covers my process of taking an old frontend app I’d built many years ago and turning it into a new version using Claude Code. Skip the Background section if you want to dive right in.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FnyYOo2ZM7Y1NJptIiEIaw.png" /><figcaption>MVP UI for SimplyBudget remade with Claude Code</figcaption></figure><h3>Background</h3><p>Around six years ago, I was talking to a co-worker and we were lamenting that we couldn’t find a simple budgeting app for tracking expenses against a weekly budget without connecting to our financial accounts. As a result, I decided to create SimplyBudget, a frontend-only app using React with no connections to anything but itself. I worked on the app after work and on weekends after working long hours. In all honesty, that process was a bit of a slog due to tiredness, but I got an MVP done and working. However, I never made it to the next step due to life changes and shifting priorities: converting it to a mobile app using React Native.</p><p>Now, all this time later I have time, but I also want to focus on studying, and I have a bunch of other apps I want to build. Enter Claude Code: my new best friend who can perform much of the work for me and free me up to study as I please…for the most part, and make it so that I never have to look at that old repo ever again 😁.</p><h3>Main Tools Used</h3><ul><li>Frontend: React / Next, TypeScript, Tailwind CSS</li><li>Charts: recharts</li><li>Testing: Jest</li><li>Coding: Claude Code (Pro plan)</li><li>Design: Claude + Me + Variant</li></ul><h3>Repos</h3><ul><li><a href="https://github.com/helloRupa/simply-budget">Old SimplyBudget</a></li><li><a href="https://github.com/helloRupa/simplybudget">New SimplyBudget</a></li></ul><h3>The New Beginning (Inspiration)</h3><p>I was already using Claude Code and had taken some of the Anthropic courses online, but I felt that I didn’t know what I didn’t know. The biggest hole in my understanding was how others were using it, so I decided to take a Coursera course from Vanderbilt University: <a href="https://www.coursera.org/learn/claude-code">Claude Code Software Engineering with Generative AI Agents</a>. The instructor, Dr. Jules White, opened the course by making an expense tracker from a single prompt and recommended following along. I immediately noticed that the expense tracker was similar to SimplyBudget, minus a few features, so I decided to take his prompt and modify it to create the new and improved version.</p><p>Here’s the prompt (using Opus) that started it all:</p><pre>I want you to create a modern NextJS personal budgeting application. Here&#39;s my vision:<br><br>APPLICATION OVERVIEW:<br>Build a complete budgeting web app that helps users manage their personal expenditures. The app should feel modern and intuitive. <br><br>CORE FEATURES:<br>- Users set a weekly budget to track expenses against<br>- Add expenses with date, amount, category, and description, with description being optional<br>- View expenses in a clean, organized list<br>- Filter expenses by date range and category<br>- Dashboard with spending summaries and basic analytics, including but not limited to the total amount saved for the week and the total amount saved since using the app (Note that this number could be positive if the user has spent less than their budget, or negative if they have spent more)<br>- Starter Categories: Food, Transportation, Entertainment, Shopping, Bills, Other<br>- Users should be able to add new categories if they want<br>- Data persistence using localStorage for this demo<br><br>TECHNICAL REQUIREMENTS:<br>- NextJS 14 with App Router<br>- TypeScript for type safety<br>- Tailwind CSS for styling with a modern, clean design<br>- Responsive design that works on desktop and mobile<br>- Use React hooks for state management<br>- Form validation for expense inputs<br>- Date picker for expense dates<br>- Currency formatting for amounts<br>- Support for localization: all translatable strings should be localized<br><br>DESIGN REQUIREMENTS:<br>- Clean, modern interface with a friendly color scheme<br>- Medium to dark purple background<br>- Intuitive navigation and user experience<br>- Visual feedback for user actions<br>- Loading states and error handling<br>- Mobile-responsive design<br><br>SPECIFIC FUNCTIONALITY:<br>- Expense form with validation<br>- Expense list with search and filter capabilities<br>- Summary cards showing total spending, monthly spending, top categories<br>- Basic charts or visual representations of spending patterns<br>- Export functionality (at least CSV)<br>- Delete and edit existing expenses<br><br>Please create this as a complete, production-ready application. Set up the project structure, implement all features, and make sure everything works together seamlessly. Focus on creating something that looks friendly and that I could actually use to track my expenses.<br><br>When you&#39;re done, provide instructions on how to run the application and test all features.</pre><p><em>Note: This isn’t how I normally go about creating an app. I normally start with a CLAUDE.md file and then build feature by feature, which makes testing easier.</em></p><p>The prompt is broken into clearly labeled sections to help Claude focus on one concern at a time: features, technical constraints, and design separately. Its structure reduces ambiguity and tends to produce more accurate results than a single wall of text.</p><p>This prompt also gives Claude a lot of room to make decisions regarding styling, architecture, and how features work. However, since this is a fairly simple app, it actually produces a really good almost-working version in a matter of minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bksYk6gWm3mJesAv8xlgzw.png" /><figcaption>MVP from first prompt</figcaption></figure><p>The app was very purple, so very purple. I did ask for purple, so I guess that’s on me.</p><p>I decided not to add tests just yet, because I wanted to figure out the exact functionality first and then test for that. I didn’t want to spend tokens writing tests and then rewriting them a million times as I honed in what I actually wanted.</p><h3>Testing the App</h3><p>I ran through testing the app in my browser like a real user. I checked for appropriate empty states, input validations, adding and editing expenses, and dashboard calculations. I also checked that my expenses persisted upon refresh, and after quitting and reopening the browser.</p><p>Luckily, the app mostly worked and everything seemed like it would be pretty easy to fix via additional prompts. I’ll list the notable bugs and improvements here:</p><ul><li><strong>Calculations</strong>: <strong>1)</strong> SimplyBudget allows users to insert future expenses, but these should not count against your current spending since they’ve not yet occurred. <strong>2)</strong> A user can change their weekly budget amount at any time, so we need to ensure that any lifetime savings or overspending are tracked using the corresponding week’s budget. On the first pass, the total saved or overspent was multiplying the number of budgeting weeks against the current budget amount.</li><li><strong>Translations</strong>: <strong>1)</strong> Some text was not translated. <strong>2)</strong> There was no support for currencies outside of USD. <strong>3)</strong> Dates were not localized.</li><li><strong>CSV Export</strong>: <strong>1)</strong> Formatting of dates was causing a mismatch between columns and headers. <strong>2)</strong> Categories weren’t translated — only English was being exported.</li></ul><p>I would say that most of these bugs are somewhat nuanced. For example, I wouldn’t expect Claude to “just know” how to handle future expenses or correctly calculate the total saved or overspent for all time. These items require the developer to appropriately describe what they want, since more knowledge of the final user experience is needed.</p><p>I batched similar fixes/improvements into their own prompts and had Claude get to work fixing and improving the app. For example, I handled similar calculations in a single prompt and the CSV fixes in a separate prompt. This allows Claude to reuse the context it already has and handle similar work while consuming fewer tokens. Each time you start a new prompt, Claude needs to re-read the conversation history; grouping related tasks means less repeated context. I also cleared its context when switching to different tasks. For instance, the CSV fixes did not require knowledge of translation or dashboard calculation changes.</p><p>Claude fixed everything with ease. There were one or two instances where it thought an issue was fixed, but it wasn’t quite there yet. Those instances were easily resolved with additional prompts. In most cases, only one more prompt was needed.</p><p>At this point, I had a working MVP, but I still had some tokens left for the session, so I figured I’d burn through them. I asked Claude to do a total redesign of the app: something creative and fun, which doesn’t look like AI made it. I intentionally gave it a vague instruction because I wanted to see what would happen. It certainly gave me something I didn’t expect. I wish I had taken a screenshot or saved it to a branch because it was pretty out there. Needless to say, I didn’t like it and abandoned that design. It was really late (or early depending on how you think of time 😂), I was out of tokens, and it was time for bed.</p><h3>Refining the App’s Functionality</h3><p>I refined the MVP by adding and updating features and styles over several days. I switched between Opus and Sonnet depending on how difficult I thought a task would be: Opus for complex reasoning or architecture decisions, Sonnet for quicker iterative tasks. If I wasn’t sure, I’d ask Claude to make a suggestion on which model to use. When in doubt about how to use Claude, just ask Claude. I also added the CLAUDE.md file, detailing the stack used, key decisions, features, and some coding style preferences. This gives Claude persistent context about the app, so it doesn’t forget key decisions between sessions. I continued updating this file with important decisions to ensure Claude didn’t forget.</p><p>Here are some of the features we (me + Claude = we) added:</p><ul><li>Support for recurring expenses with weekly, monthly, or annual intervals</li><li>Export and import backup data</li><li>About modal</li><li>Allow negative expenses so users can account for returns without having to find and modify old expenses</li></ul><p>If I knew what I wanted, I prompted Claude to build exactly what I wanted while providing some context around the motivation. For example: “Users might have recurring expenses, like needing to pay their Internet bill each month. Let’s support recurring expenses for weekly, monthly, and annual intervals. These expenses should be automatically added to the expenses list. Ensure we don’t add duplicates. Tell me your plan first.” In other cases, I wasn’t entirely sure of what I wanted so I asked Claude to give me some options: “I want to add an About section to the app. Can you give me some options on where we might put this and what information we might include?” I also asked Claude to create a data retention strategy document in case we ever needed to archive old data — something that might become necessary after years of use.</p><p>Each time we added something new, I entered into the same loop of testing and prompting as needed.</p><p>Once I was reasonably certain I had an MVP built to the spec that existed in my head, I instructed Claude to write integration tests for each view. It did so really quickly and I was happy with the test coverage!</p><h3>Refining the User Experience</h3><p>Claude is not a person, so there was an interaction in the app that was difficult to follow and there were some inconsistent styles.</p><p>I’ll keep this brief and list a couple of the improvements we made:</p><ul><li>When editing an existing expense in the expense list, the focus wouldn’t shift up to the expense form. If you were way down on the page, you’d likely be confused because the form wouldn’t be in view. We added a scroll-to-top animation along with a pulse to draw attention to the form when a user clicks “Edit”.</li><li>Some of the form validation errors weren’t styled in the same manner as others. They were using the browser’s default input validations. This was an easy fix: add noValidate to the forms.</li></ul><h3>Refining the App’s Design</h3><p>I didn’t really know what I wanted the app to look like, and it was so very purple (completely my fault), so I worked with Claude and Variant to come up with some improvements.</p><p>The first thing I did was take a screenshot of the old MVP I built many years ago. I told Claude that I wanted it to take inspiration from the colors and to pay particular attention to how colors mapped to meaning within the UI. Claude quickly understood how amounts were colored based on current spending and figured out that I like colors…lots of colors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*PpSifZJDZFbdP66k3O2NMg.jpeg" /><figcaption>SimplyBudget MVP from the days of yore</figcaption></figure><p>I still wasn’t happy with the app’s appearance, so I turned to <a href="https://variant.com/">Variant</a>. For Variant’s prompt, I pasted a screenshot of the app’s current Dashboard, and added a small description about it. I added additional information on what I was looking for in the final design: something clean, modern, and colorful!</p><p>Variant gave me many designs to choose from, and as I scrolled down the page, it gave me more until I ran out of tokens. I took screenshots of the designs I liked and gave them to Claude one by one, each time telling Claude exactly what I liked about those designs.</p><p>Most of the inspiration came from this design variant:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lXQMyvzYmoig5OrTqugINA.png" /><figcaption>Color inspiration from variant</figcaption></figure><p>I actually hand-coded/pasted the gradients in the final MVP because I wasn’t sure of what I wanted. I used <a href="https://shuffle.dev/">Shuffle</a>’s (a Tailwind component tool)<em> </em>AI feature to quickly test gradients and output the correct Tailwind CSS classes. I then copy/pasted those into the relevant files, ordering the colors as I pleased.</p><p>After that, I updated some of the iconography in the app. At this point, Claude had generated all of the icons itself. Most of those were fine as is, but some were too US-centric or I couldn’t understand what they were. I wanted icons that would be applicable for users in any country.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pQcq1ZKPUJGza1H8W_-png.jpeg" /><figcaption>Note the “$” sign in the far left icon and on the far right, an icon that still confuses me</figcaption></figure><p>I asked Claude for some options for the cards at the top of the Dashboard. We chose a wallet for the weekly budget icon, and a piggy bank for the total overspent/saved icon on the far right. The wallet turned out really well, but the piggy bank was an oval with some lines for legs, which was not great. We decided to make a regular bank building instead. To be fair, Claude’s documentation does state that it’s best for simple icons, but I was curious.</p><p>I also asked Claude to make a money frog icon for the main app icon based on an image I provided. It did make an icon that looked like a frog, but I wasn’t happy with it. Clearly, I didn’t learn my lesson from earlier regarding simple icons.</p><p>I gave that same money frog image to ChatGPT instead, and asked it to make some changes: fewer coins and black linework only. After that, I asked it to show me some options in color that would be appropriate for use as an app icon. I took the linework-only image and put it into Affinity so it could be traced. I then edited and colored that tracing to create the final SVG, and created the favicon.ico file using <a href="https://www.freeconvert.com/svg-to-ico">FreeConvert.com</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*0o3qN0ZRMsZGIQFMk2KkMQ.png" /><figcaption>Money frog icon for MVP</figcaption></figure><p>I’d say this image is too close to the one I found online, so I wouldn’t use it in a production release, but it works for an MVP.</p><h3>Review and Refactor</h3><p>No app, MVP or not, is done until it has been reviewed and refactored. Since we’d already written tests, it was the perfect time to do this work.</p><p>I used custom Claude commands for this work. Custom commands are reusable prompts you can save in Claude Code and trigger with a slash command (e.g. /refactor). You set them up by creating markdown files in a .claude/commands folder at the root of your project, where the filename is the command name.</p><p>The first snippet is for the refactor command, and the second snippet is for the review command:</p><pre>Refactor: $ARGUMENTS<br><br>Requirements:<br>- Analyze the file or files for opportunities for code reuse<br>- Check for React best practices<br>- Look for unused or dead code, e.g. unused variable/import/function, to clean up<br>- Check for missing types<br>- Ensure code is easy to understand for humans<br>- Ensure all user-facing text is translated<br>- Provide a short bullet-list report of proposed changes, including reasoning, if any<br>- Make changes if given permission to do so, and then run the test suite: `npm test 2&gt;&amp;1`</pre><pre>Review the code in: $ARGUMENTS<br><br>Requirements:<br>- Review like you&#39;re a senior developer who loves clean and maintainable code<br>- Look for code that doesn&#39;t meet best practices for the tech stack<br>- For TypeScript, inference is OK<br>- Look for opportunities for code reuse<br>- Point out code that is hard to understand <br>- Check for code that might lead to subtle bugs<br>- Provide a report as a bulleted list and provide the top 3 to 5 changes to prioritize<br>  - List should detail priority of change: High, medium, or low<br>  - Include reasoning, but keep it short</pre><p>For the refactor, I wanted Claude to give me its plan first so I could ensure it was worthwhile. After receiving its plan, I’d instruct it on which refactors to perform, and Claude would then run tests to ensure nothing broke along the way.</p><p>We followed the same strategy for the review. Although the commands look almost identical, the review actually caught some more areas where code could be reused and some missing dependencies in dependency arrays for React hooks.</p><p>After all of that was done, I took a look at the code and found one tiny area where code could be reused: the two-color app title which is used in two places. Claude happily did that work for me.</p><h3>Conclusion</h3><p>I had a great time working with Claude to remake SimplyBudget. I was actually surprised by how much it could do by itself without specific instructions. For example, it automatically generated Spanish and French translations for me as part of the initial MVP prompt and many icons!</p><p>I don’t know how long it would have taken me to build this by myself. It certainly would have taken more than the several days I spent with Claude. Keep in mind, we didn’t work whole days, just a few hours here and there. And I didn’t use subagents doing work in parallel either, since I’d rather run out of tokens with a single feature cooking as opposed to several. It also increased my chances of having something to play with before the tokens ran out.</p><p>Now that the web MVP is complete, I need to create the React Native version for iOS and Android. I’ll detail that process in <a href="https://medium.com/p/d408420c65c7">part 2 of this series</a>. I can already tell you how it’s going to begin: “Claude, how best can I work with you to convert this React web app to a React Native app?”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4696a6f5674d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Test Web Apps and Sites on Mobile Without Deploying (Access Localhost)]]></title>
            <link>https://codersloth.medium.com/how-to-test-web-apps-and-sites-on-mobile-without-deploying-access-localhost-90f304d5c2a1?source=rss-69186b461ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/90f304d5c2a1</guid>
            <category><![CDATA[mobile-testing]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[coderSloth]]></dc:creator>
            <pubDate>Tue, 29 Dec 2020 07:42:56 GMT</pubDate>
            <atom:updated>2026-08-27T05:02:47.620Z</atom:updated>
            <content:encoded><![CDATA[<h4>It doesn’t always make sense to deploy our web apps and sites to test them on our mobile devices. Luckily, we can access our computers’ IP addresses by following some simple steps.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3Asof4k20Coj27ks" /><figcaption>Photo by <a href="https://unsplash.com/@danny144?utm_source=medium&amp;utm_medium=referral">Dan Nelson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a> We don’t need VPN, but this picture is freee!</figcaption></figure><h3>The Problems</h3><p>I’m creating a static website and I want to test it on my mobile devices without deploying it anywhere (for some random reason, I don’t want to use GitHub Pages to test 🤷‍♀). Or I want to test my React app on my phone, or I’m testing a native app that depends on communicating with a back end that’s stored on my computer…and I don’t want to deploy it yet. Maybe my Internet connection is too slow or I don’t ever plan on deploying what I’m working on, so I don’t want to go through the hassle. Who knows? I’ve got reasons!</p><h3>The Solution</h3><p>Luckily, the solution is really simple. Other than a working computer and mobile device, you’ll need:</p><ul><li>To connect your devices to the same WiFi</li><li>A command line server, like <a href="https://www.npmjs.com/package/httpserver">httpserver,</a> if serving a static site</li></ul><p>First, you’ll need to serve up your app. If you’re serving a static website (HTML, CSS, JS), you’ll need to serve it up using a command line server. If you’re serving up a web app, like a React or Rails app, just start it. And now, for the glorious steps (which I can confirm do work on macOS):</p><ol><li>In the command line run ifconfig on a Mac or ipconfig on Windows.</li><li>On a Mac, locate an entry that has a status of active. Next to “inet”, you’ll see an address that looks something like this: 192.168.x.xx. You can test that this address works by navigating to it in a browser along with the port your app is running on, e.g. 192.168.1.11:3000. If it’s incorrect, try another address. For Windows, try the IPv4 address.</li><li>In some cases, you might need to change the configuration of your app in order to access it this way. In Rails, for example, we need to bind the host and port when starting the server (rails s -b 192.168.1.11 -p 3000) or set environment variables.</li><li>Once you find the working address, you can update any apps you wish to test on your devices. For example, if you’re running a front end that relies on a locally-hosted back end, you could set an environment variable to point to the local IP address when the app is being run in the development environment. If you need to test the same local app across different browsers and devices, <a href="https://www.browserstack.com/automate">BrowserStack Automate</a> can also be used to test localhost and other private web applications on real devices, without deploying them publicly.</li></ol><p>And that’s it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90f304d5c2a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Database Constraints, But Why?]]></title>
            <link>https://codersloth.medium.com/database-constraints-but-why-c283761ec7c6?source=rss-69186b461ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/c283761ec7c6</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[data-integrity]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[coderSloth]]></dc:creator>
            <pubDate>Tue, 22 Dec 2020 06:05:37 GMT</pubDate>
            <atom:updated>2020-12-22T06:05:37.440Z</atom:updated>
            <content:encoded><![CDATA[<h4>Many people know why we should use model validations, but why also use database constraints? All this and more (not really more actually) can be yours if you read on! OK fine, short story: to protect the integrity of our data!</h4><figure><img alt="Protect your data like this duck protects its young!" src="https://cdn-images-1.medium.com/max/1024/0*QznFurdbskREGbgD" /><figcaption>Photo by <a href="https://unsplash.com/@kris_ricepees?utm_source=medium&amp;utm_medium=referral">Gary Bendig</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a> (Protect your data like this duck protects its young!)</figcaption></figure><h3>The Problem(s)</h3><p>Our backend currently relies on model validations to ensure the correct format of any data that reaches the database. This has worked great so far, but we’re at a point where we need to start using SQL to add and update data in the database in order to speed up performance. Or we need to interact with the database directly to perform bulk operations that are otherwise difficult to perform. Any modifications made in this manner will not pass through validations :(</p><h3>The Solution: Database Constraints!</h3><p>Database constraints are the perfect answer to the problem stated above. They also help protect our data in the event that we switch out part of our stack, specifically the backend application that interacts with the database (So many things can go wrong when we make big changes!).</p><p>Like model validations, database constraints allow us to declare what the data in a column should look like: does it follow a pattern? Should it be a certain length? Can it be empty? Is there a range of values it should fall within? What about uniqueness? And on and on. In the event that someone bypasses the model validations to add or modify data, that new data won’t be added unless it conforms to the database constraints, thus protecting the integrity of our data.</p><p>As a general rule, I like to ensure that my database constraints mirror my model validations, or vice versa. At times, this means I need to break out my old SQL friend when I’m writing migrations, since the out-of-the-box constraints (aka helpers) are limited regardless of what we’re using for the backend application.</p><h3>A Rails Example</h3><p>Here’s a quick example of a migration that includes database constraints to ensure that certain columns always contain data, are unique, and/or require a minimum character length:</p><pre>create_table :bands do |t|<br>  t.string :name, null: false, unique: true<br>  t.integer :members, null: false</pre><pre>  t.timestamps<br>end</pre><pre>execute &lt;&lt;-SQL <br>  ALTER TABLE bands<br>  ADD CONSTRAINT check_minimum_length <br>  CHECK (LENGTH(name) &gt; 2)<br>SQL</pre><p>And this also has the added benefit of automatically indexing the name column, which allows for faster lookups! This would not be true with a model validation alone. Ooooh, benefits…</p><p><em>Quick note: please don’t index every column in every table: this is a bad idea. Please look into why if you don’t believe me.</em></p><h3>Conclusion / PSA</h3><p>If there’s even the slightest chance that you or someone else will directly modify data in the database, please, please, whip out those constraints! I know there are people out there who don’t, so you do you. Personally, I always use database constraints, we’re tight like that.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c283761ec7c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails: How to Batch Insert Records]]></title>
            <link>https://codersloth.medium.com/rails-how-to-batch-insert-records-20ea769dcbc4?source=rss-69186b461ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/20ea769dcbc4</guid>
            <category><![CDATA[fetch]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[rails-6]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[batch-insert]]></category>
            <dc:creator><![CDATA[coderSloth]]></dc:creator>
            <pubDate>Mon, 24 Aug 2020 08:36:05 GMT</pubDate>
            <atom:updated>2020-08-24T08:36:05.766Z</atom:updated>
            <content:encoded><![CDATA[<p>We can easily insert records one by one by supplying an array of objects to .create in Ruby on Rails, but each insertion results in a separate request to the database. This may not be an issue for apps that receive low traffic or where batches are small, but what if your app receives high traffic or the batches are large? In the past, we had to use SQL directly to batch insert all at once, but as of Rails 6 we now have .insert_all!</p><h3>The Problem(s)</h3><p>My web app allows users to create multiple records at once. The frontend sends an HTTP request containing an array of objects to the backend, which then calls .create on the appropriate model using the parameters from that request. However, this is slowing down our response times since each record results in a separate request to the database. For example, if we try to .create 12 records, we’ll see 12 separate INSERTs in the logs.</p><p>We haven’t been using SQL because we want the records to pass through the relevant model validations. We also use Active Record callbacks to add data to these objects before they are saved. But we’re now at a point where this isn’t feasible.</p><h3>Need to Know</h3><p>When we call .create on a model, objects pass through model validations and Active Model callbacks are run (e.g. after_validation, before_save…). When we insert records using SQL or .insert_all, callbacks and model validations are bypassed. As of right now, the only way to batch insert or upsert records in a database with a single request is through SQL and Rails 6 methods, such as .insert_all. Database constraints will still apply, as always.</p><p>According to this <a href="https://www.red-gate.com/simple-talk/sql/performance/comparing-multiple-rows-insert-vs-single-row-insert-with-three-data-load-methods/">Redgate article</a>, inserting five rows in a single statement reduced execution time by 40% when compared to five separate inserts. And then there’s this lovely quote from the <a href="https://dev.mysql.com/doc/refman/8.0/en/insert-optimization.html">MySQL documentation</a>: “If you are inserting many rows from the same client at the same time, use <a href="https://dev.mysql.com/doc/refman/8.0/en/insert.html">INSERT</a> statements with multiple VALUES lists to insert several rows at a time. This is considerably faster (many times faster in some cases) than using separate single-row <a href="https://dev.mysql.com/doc/refman/8.0/en/insert.html">INSERT</a> statements.”</p><h3>What We’ll Be Doing</h3><p>Here is the code we’ll be working with:</p><pre>class CreateBands &lt; ActiveRecord::Migration[6.0]<br>  def change<br>    create_table :bands do |t|<br>      t.string :name, null: false<br>      t.integer :members, null: false</pre><pre>      t.timestamps<br>    end</pre><pre>    add_index :bands, :name, unique: true<br>  end<br>end</pre><pre>class Band &lt; ApplicationRecord<br>  validates :name, presence: true, length: { minimum: 3 },  <br>    uniqueness: true<br>  validates :members, presence: true, <br>    numericality: { greater_than: 0 }<br>end</pre><pre>class BandsController &lt; ApplicationController<br>  def index<br>    render json: Band.all<br>  end</pre><pre>  def create<br>    begin<br>      Band.transaction do<br>        @bands = Band.create!(bands_params)<br>      end<br>    rescue ActiveRecord::RecordInvalid =&gt; exception<br>      @bands = {<br>        error: {<br>          status: 422,<br>          message: exception<br>        }<br>      }<br>    end</pre><pre>    render json: @bands<br>  end</pre><pre>  private</pre><pre>  def bands_params<br>    params.permit(bands: [:name, :members]).require(:bands)<br>  end<br>end </pre><p>We’ll modify this to work with .insert_all, and then we’ll tackle the problems as they come up. Our end goal is to have an all-or-nothing insertion that respects all of our necessary validations.</p><p>Notice how the model validations don’t currently match the database constraints, which are a little looser. We’ll tackle this issue as well, since batch insertions rely on database constraints.</p><p>Lastly, we’ll explore how we can insert records that require additional modifications before insertion, like adding more information or running validations that can’t easily be applied as database constraints.</p><h3>Quick Log Check: .create vs .insert_all</h3><p>Let’s take a look at the log for creating three records via .create on our Band model. Notice that there are three total transactions here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*Ph1azHD8KxQE9H_9SYek7g.png" /><figcaption>Log when inserting an array of records via .create</figcaption></figure><p>Also notice that we didn’t have to add the timestamps for updated_at and created_at. Those were added for us.</p><p>Now let’s take a look at using .insert_all:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*EXmo-c9Dp2teXm7OJS7uag.png" /><figcaption>Log when inserting an array of records via .insert_all</figcaption></figure><p>There’s a single bulk insert, but since our Band records require timestamps, we had to add those in for our records to pass the database constraints. Otherwise, any records missing that information would not be inserted.</p><h3>Step 1: Make it Work!</h3><p>Right now, we can send an array of bands and they’ll be inserted into our database one by one. Let’s see if we can get our bands to bulk insert instead without worrying about the fine details of what’s valid or not valid. In short, just make it work, even if it’s not great.</p><p>Let’s start by making our create action as dumb as possible:</p><pre>def create<br>  bands = Band.insert_all(bands_params)<br>  render json: bands<br>end</pre><p>Now let’s make a request containing several bands and see what error we get:</p><pre>ActiveRecord::NotNullViolation (SQLite3::ConstraintException: NOT NULL constraint failed: bands.created_at)</pre><p>In the migration, we added timestamps using the timestamps method. This automatically adds a not null constraint for both the created_at and updated_at columns. When we add records by instantiating objects from the model, Active Record automatically adds timestamps for us. Since we’re now bypassing that step to insert multiple rows with a single statement, we now need to add this data ourselves. Let’s add some class methods to the Band model to get this working:</p><pre>def self.insert_all(records)<br>  normalized = normalize(records)<br>  super(normalized)<br>end</pre><pre>def self.normalize(records)<br>  records.each do |rec|<br>    add_timestamp(rec)<br>  end<br>end</pre><pre>def self.add_timestamp(record)<br>  time = Time.now.utc</pre><pre>  record[&#39;created_at&#39;] = time<br>  record[&#39;updated_at&#39;] = time<br>end</pre><p>Now, when I send a fetch request in my browser, the records are created, but my response is an array of object, and each object has an id:</p><pre>[{ id: 1 }, { id: 2 }]</pre><p><em>Note: This behavior is specific to PostgreSQL. SQLite3, for example, will return an empty array by default.</em></p><p>That’s not a very useful response, so let’s fix that up by using the returning option to specify which data we want to have returned to us:</p><pre># BandsController<br>def create<br>  bands = Band.insert_all(bands_params, <br>    returning: [:id, :name, :members])</pre><pre>  render json: bands<br>end</pre><pre># Band<br>def self.insert_all(records, options)<br>  normalized = normalize(records)<br>  super(normalized, options)<br>end</pre><p><em>Note: The returning option is not valid when using SQLite3. It will produce an error!</em></p><p>Now we receive a more useful response containing the data we want:</p><pre>[<br>  { id: 3, name: “Radiohead”, members: 5 },<br>  { id: 4, name: “Refused”, members: 4 }<br>]</pre><p>What happens if we try to make these same records again? Our database constraints state that the band names must be unique, so the records aren’t created. Our response consists of an empty array.</p><p>What if we try to create some bands with 0 members? There’s no database constraint for that, but there is a model validation. Since .insert_all bypasses model validations, those records are inserted, so we now have bands in the database that have 0 members. Let’s clear this up in the next step.</p><h3>Step 2: Better Database Constraints</h3><p>Right now, our database constraints ensure that any new band rows contain a name and some number of members. They also ensure that each band has a unique name. However, the Band model has additional validations: it checks that the band name is three characters or more and that the number of members is greater than 0.</p><p>For .insert_all to honor these rules, we’ll need to add a change migration and we’re going to have to bust out our old friend SQL!</p><pre>class AddCheckConstraintToBandsForNameLength &lt; ActiveRecord::Migration[6.0]<br>  def change<br>    execute &lt;&lt;-SQL<br>      ALTER TABLE bands<br>      ADD CONSTRAINT check_minimum_length<br>      CHECK (LENGTH(name) &gt; 2)<br>    SQL<br>  end<br>end</pre><p>This new constraint doesn’t show up in schema.rb, but we can easily test it in the console. We shouldn’t be able to insert any bands with names of less than three characters.</p><pre>bands = Band.insert_all([{ name: ‘bb’, members: 5 }], returning: [:id, :name])<br># =&gt; ActiveRecord::StatementInvalid (PG::CheckViolation: ERROR:  new row for relation &quot;bands&quot; violates check constraint &quot;check_minimum_length&quot;)</pre><pre>bands = Band.insert_all([{ name: ‘bbb’, members: 5 }], returning: [:id, :name])<br>bands.first<br># =&gt; { “id”=&gt; 12, “name” =&gt; “bbb” }</pre><p>So it looks like our minimum length constraint is working. Let’s also add our minimum band member constraint, since bands should have more than zero members:</p><pre>class AddCheckConstraintToBandsForMinimumMembers &lt; ActiveRecord::Migration[6.0]<br>  def change<br>    execute &lt;&lt;-SQL<br>      ALTER TABLE bands<br>      ADD CONSTRAINT check_minimum_number_of_band_members<br>      CHECK (members &gt; 0)<br>    SQL<br>  end<br>end</pre><p>This has also worked. You’re just going to have to trust me on that.</p><p>After testing this out, I can now only batch insert valid records, and my database constraints perfectly match my model validations from earlier.</p><p>But what if we needed to add some additional data during some part of the object life cycle? How could we do that?</p><h3>Step 3: Adding Additional Data Before Insert</h3><p>I ran a change migration and added a ‘gibberish’ column to our bands table. I then made the following change to the model:</p><pre>after_validation :add_gibberish</pre><pre>def add_gibberish<br>  self.gibberish = &quot;#{self.name} likes gibberish&quot;<br>end</pre><p>I wish I had come up with something more creative to show here, but it just wasn’t happening today.</p><p>Since .insert_all doesn’t care about the object life cycle, we can’t add this nonsense after validation. Instead, we’ll need to update our Band model like so:</p><pre>def add_gibberish<br>  self.class.make_gibberish(self)<br>end</pre><pre>def self.make_gibberish(record)<br>  record[:gibberish] = &quot;#{record[:name]} likes gibberish&quot;<br>end</pre><pre>def self.normalize(records)<br>  records.each do |rec|<br>    add_timestamp(rec)<br>    make_gibberish(rec)<br>  end<br>end</pre><p>If we were running many methods, we could instead instantiate a new object from the Band class, check if the object is valid, and then use the attributes from that object as our record:</p><pre>def self.object_to_record(record)<br>  band = Band.new(record)<br>  band.valid?<br>  band.attributes<br>end</pre><p>By doing this, we can run any life cycle methods that occur before or right after validation. But this will do nothing to help us if we’re running methods around save.</p><h3>Step 4: Refactor</h3><p>Our Band model is looking pretty messy, and I’m pretty sure the .insert_all override/monkey patch is general enough to put it elsewhere. Actually, let’s not be monkeys and instead use a new method name. And we’ll factor this code out into a concern, which I’ll call Insertable:</p><pre># app/models/concerns/insertable.rb</pre><pre>module Insertable<br>  extend ActiveSupport::Concern</pre><pre>  class_methods do<br>    def add_timestamp(record)<br>      time = Time.now.utc</pre><pre>      record[&#39;created_at&#39;] = time<br>      record[&#39;updated_at&#39;] = time<br>    end</pre><pre>    def insert_all_normalized(records, options = {returning: [:id]})<br>      normalized = normalize(records)<br>      result = nil</pre><pre>      begin<br>        result = insert_all(normalized, options)<br>      rescue ActiveRecord::StatementInvalid =&gt; e<br>        result = e<br>      end</pre><pre>      result<br>    end<br>  end<br>end</pre><p>I also moved add_timestamp into the concern because it’s not specific to the Band model. Notice that .insert_all_normalized is still relying on .normalize. That method will always be specific to a model, so anytime we mix Insertable into a model class, we’ll need to declare .normalize in that model. I also decided to handle any exceptions here, so that the controller can be as “dumb” as possible, and if this method is called in multiple controllers, it’ll reduce the amount of code we need to write.</p><p>Our Band model now looks like this:</p><pre>class Band &lt; ApplicationRecord<br>  include Insertable</pre><pre>  validates :name, presence: true, length: { minimum: 3 },<br>    uniqueness: true</pre><pre>  validates :members, presence: true, <br>    numericality: { greater_than: 0 }</pre><pre>  after_validation :add_gibberish</pre><pre>  def add_gibberish<br>    self.class.make_gibberish(self)<br>  end</pre><pre>  def self.make_gibberish(record)<br>    record[:gibberish] = &quot;#{record[:name]} likes gibberish&quot;<br>  end</pre><pre>  def self.normalize(records)<br>    records.each do |rec|<br>      add_timestamp(rec)<br>      make_gibberish(rec)<br>    end<br>  end<br>end</pre><p>And here’s our controller:</p><pre>class BandsController &lt; ApplicationController<br>  def index<br>    render json: Band.all<br>  end</pre><pre>  def create<br>    bands = Band.insert_all_normalized(bands_params, <br>      returning: [:id, :name, :members])</pre><pre>    if bands.kind_of?(ActiveRecord::Result)<br>      render json: bands<br>    else<br>      render json: {<br>        status: 422,<br>        error: bands<br>      }, status: 422<br>    end<br>  end</pre><pre>  private</pre><pre>  def bands_params<br>    params.permit(bands: [:name, :members]).require(:bands)<br>  end<br>end</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20ea769dcbc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails: Creating Multiple Records From a Single Request]]></title>
            <link>https://codersloth.medium.com/rails-creating-multiple-records-from-a-single-request-a45261085164?source=rss-69186b461ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/a45261085164</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[fetch]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[model]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[coderSloth]]></dc:creator>
            <pubDate>Mon, 03 Aug 2020 01:48:44 GMT</pubDate>
            <atom:updated>2020-08-03T01:48:44.002Z</atom:updated>
            <content:encoded><![CDATA[<p>Creating multiple entries in a database from a single HTTP request using Rails is easier than it seems. We can even ensure that if one fails, our database gets rolled back to its previous state! Ooh la la.</p><p>Note that this article talks about creating many records in a single table, not many tables. Also, this isn’t a batch SQL insert: if you’re interested in that look into insert_all. If you read the whole thing, expect to learn quite a bit about create(!) and parameters. If you just want to see the code that changed, scroll down to the <em>Summary</em> at the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RGrh89JhQ4u4LHWo" /><figcaption>Photo by <a href="https://unsplash.com/@hal9001?utm_source=medium&amp;utm_medium=referral">HAL9001</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>What Do We Want to Do?</strong></p><p>Let’s say we have a table storing Band data, and we want the ability to add several new Bands to this table from the frontend (JavaScript) using a fetch request. Our initial idea might be to loop through all of the new Band data on the frontend and send one fetch request per Band. However, this results in making more requests than necessary. Instead, we can actually add all of the new Bands using a single fetch request, which reduces the number of requests our server must handle.</p><p>The fetch request we’re aiming for might look something like this:</p><pre>const options = {<br>  method: ‘POST’,<br>  headers: { ‘Content-Type’: ‘application/json’ },<br>  body: JSON.stringify({ bands }) // bands is an array of Objects<br>}</pre><pre>// fetch here</pre><p><strong>Hello My Old Friend, ActiveRecord create(!)</strong></p><p>To do this easily, we first need to take a look at our old class method friends create and create!. Commonly, we use these methods to create a single entry in a database by passing a Hash as an argument:</p><pre>Band.create(name: “Nite Fields”, year: 2012)<br>Band.create!(name: “Nite Fields”, year: 2012)</pre><p>However, we can also pass an Array of Hashes to create several records at once:</p><pre>Band.create([{ name: “Nite Fields”, year: 2012 }, { name: “Refused”, year: 1991 }])</pre><pre>Band.create!([{ name: “Nite Fields”, year: 2012 }, { name: “Refused”, year: 1991 }])</pre><p>But the question is: what happens if some of the records in the Array are valid and others are not? Will the valid records be created anyway? Luckily, this is easy to test. We can attempt to create several valid records, and then attempt to create a mix of invalid and valid records all at once:</p><pre># VALID RECORDS ONLY<br>Band.create([{ name: “Nite Fields”, year: 2012 }, { name: “Refused”, year: 1991 }])</pre><pre># ONE INVALID RECORD<br>Band.create([{ name: “Radiohead”, year: 1985 }, { name: “The Blah Blahs” }, { name: “Testing”, year: 2222 }])</pre><p>When each Hash contains valid data (passes validations and any database-level checks), the records are created as expected: they are inserted one-at-a-time into the database. When creating a mix of valid and invalid records, we actually get mixed results depending on where the invalid data is located in the Array.</p><p><strong>Database-level validations using column modifiers only</strong></p><p>When we use column modifiers in our migrations, such as null: false, but we don’t add validations to our models, create will abort as soon as an invalid Hash of attributes is encountered in the Array. All records preceding the invalid one will be inserted into the database. For example, if the first Hash in the Array contains invalid data, no records will be inserted. If the middle Hash contains invalid data, every record preceding it will be inserted:</p><pre># NO RECORDS WILL BE INSERTED, FIRST HASH IS INVALID<br>Band.create([{ name: “The Blah Blahs” }, { name: “Radiohead”, year: 1985 }])</pre><pre># ONLY RADIOHEAD WILL BE INSERTED<br>Band.create([{ name: “Radiohead”, year: 1985 }, { name: “The Blah Blahs” }, { name: “Testing”, year: 2222 }])</pre><p>But what if we use create! instead. Is the behavior any different? Let’s find out:</p><pre># NO RECORDS WILL BE INSERTED, FIRST HASH IS INVALID<br>Band.create!([{ name: “The Blah Blahs” }, { name: “Radiohead”, year: 1985 }])</pre><pre># ONLY RADIOHEAD WILL BE INSERTED<br>Band.create!([{ name: “Radiohead”, year: 1985 }, { name: “The Blah Blahs” }, { name: “Testing”, year: 2222 }])</pre><p>It’s the same behavior! Well, that makes things a little easier on our brains.</p><p><strong>Model validations</strong></p><p>Adding model validations for the name and year columns changes the behavior of create. First let’s put the invalid record at the start of the Array:</p><pre># RADIOHEAD IS INSERTED<br>Band.create([{ name: “The Blah Blahs” }, { name: “Radiohead”, year: 1985 }])</pre><pre># RADIOHEAD AND TESTING ARE INSERTED<br>Band.create([{ name: “Radiohead”, year: 1985 }, { name: “The Blah Blahs” }, { name: “Testing”, year: 2222 }])</pre><p>Unlike before, this actually resulted in all valid records being inserted into the database regardless of their location in the Array.</p><p>But what about create!? Is there a difference?</p><pre># NOTHING IS INSERTED, ABORTED ON FIRST INVALID RECORD<br>Band.create!([{ name: “The Blah Blahs” }, { name: “Radiohead”, year: 1985 }])</pre><pre># RADIOHEAD IS INSERTED, ABORTED ON FIRST INVALID RECORD<br>Band.create!([{ name: “Radiohead”, year: 1985 }, { name: “The Blah Blahs” }, { name: “Testing”, year: 2222 }])</pre><p>This is actually similar to before. As soon as an invalid record was encountered, the process was aborted. The Blah Blahs, sadly, are still floating in space waiting for their time to shine.</p><p><strong>Return values and exceptions</strong></p><p>When only column modifiers are present, both create and create! raise exceptions when any invalid records are present in the Array, and return an Array of records when all records are valid. As a result, if an invalid record is present, attempting to store the result in a variable will cause the variable to equal nil or its previous value, if it had one:</p><pre>a = Band.create([{ name: ‘Bandy McBandFace’, year: 3000 }, { name: ‘not happening’ }])<br># a =&gt; nil</pre><pre>a = ‘dance magic dance’<br>a = Band.create([{ name: ‘Bandy McBandFace’, year: 3000 }, { name: ‘not happening’ }])<br># a =&gt; ‘dance magic dance’</pre><p>When model validations are present and only valid records exist in the Array, create will return an Array of valid objects representing the entries that were just created, including their IDs. When creating a combination of valid and invalid records create returns all of those records, but the invalid records will have an ID of nil. If all of the records are invalid, create will still return an Array of those objects with IDs set to nil.</p><p>create! operates differently. If all of the records are valid, it will return them in an Array with their IDs set. If one record is invalid, regardless of where it’s located in the Array, it will raise an exception. If we try to set a variable to the return value of create! when it raises an exception, the value stored in that variable will either be nil or the variable’s previous value. create!, in other words, behaves just as it does when only column modifiers are present.</p><p><strong>Summary: create vs create!</strong></p><ul><li>Both take a Hash or Array of Hashes as an argument.</li><li>Both return an Array of objects when all records being created are valid.</li><li>When only column modifiers are present, both raise exceptions upon encountering an invalid record and stop inserting any further records. No records are returned.</li><li>When model validations are present, create inserts all valid records and returns an Array of objects. Objects representing invalid records will have IDs set to nil in the returned Array.</li><li>When model validations are present, create! behaves just as it does when no model validations are present.</li></ul><p>&gt; <em>Note: the specific exception that’s raised differs when handling failed database-level validations vs failed model validations!</em></p><p><strong>Accepting Arrays from HTTP Requests</strong></p><p>Now that we know the differences between the two creates (it’s important, I promise!), we can move on to our BandController. We’re probably pretty used to creating a single record where our parameters are expecting a simple Hash of data:</p><pre>def create<br>  band = Band.new(band_params)</pre><pre>  if band.save<br>    render json: band<br>  else<br>    render json: { errors: band.errors.full_messages }<br>  end<br>end</pre><pre>private</pre><pre>def band_params<br>  params.require(:band).permit(:name, :year)<br>end</pre><p>The code above is pretty straightforward: band_params parses the parameters from the request and returns a Hash-like object, which Band.new uses to create a new Band object. That data can either be saved to the database or not depending on its validity. So how do we change this to accept an Array of Bands instead of a single Band.</p><p><strong>Updating the strong params</strong></p><p>First, our strong parameters need to be updated to accept an Array of data. Instead of going straight to updating the controller, let’s play with Parameters in the Rails console. We’ll create a new Parameters object using the same data format we expect to receive from the frontend:</p><pre>bands = { bands: [{ name: &quot;Radiohead&quot;, year: 1985 }, { name: &quot;Refused&quot;, year: 1991 }] }</pre><pre>params = ActionController::Parameters.new(bands)<br># =&gt; &lt;ActionController::Parameters {&quot;bands&quot;=&gt;[{&quot;name&quot;=&gt;&quot;Radiohead&quot;, &quot;year&quot;=&gt;1985}, {&quot;name&quot;=&gt;&quot;Refused&quot;, &quot;year&quot;=&gt;1991}]} permitted: false&gt;</pre><p>Now let’s try running these parameters through our regular strong parameters method that expects to receive a Hash…just for fun (because there’s no chance it’s going to work! Look at me knowing what fun is):</p><pre>params.require(:band).permit(:name, :year)<br># =&gt; ActionController::ParameterMissing (param is missing or the value is empty: band)</pre><pre>params.require(:bands).permit(:name, :year)<br># =&gt; NoMethodError (undefined method `permit’ for #&lt;Array:0x00007fc530ea8880&gt;)</pre><p>In both cases, exceptions were raised. First, it was because the required parameter/key band was missing. In the second case, we updated the requirement to bands, but we received an error stating that permit can’t be called on an Array. This means that calling require returned an Array, and permit just wasn’t into any of that business.</p><p>This is actually important to keep in mind. When require is called on the parameters in this example, it returns the value associated with the bands key, which happens to be an Array. In other words, require returns values, and not key-value pairs.</p><p>So how can we fix this? Well, what if we just get rid of require and tell permit to accept an Array of data:</p><pre>params.permit(bands: [:name, :year])<br># =&gt; &lt;ActionController::Parameters {&quot;bands&quot;=&gt;[&lt;ActionController::Parameters {&quot;name&quot;=&gt;&quot;Radiohead&quot;, &quot;year&quot;=&gt;1985} permitted: true&gt;, &lt;ActionController::Parameters {&quot;name&quot;=&gt;&quot;Refused&quot;, &quot;year&quot;=&gt;1991} permitted: true&gt;]} permitted: true&gt;</pre><p>We didn’t get an error, but this still isn’t quite what we want. We now have a Parameters object that has our Band data attributed with a bands key in a Hash. Both create(!)s are expecting an Array. Let’s give it a whirl to check our hypothesis:</p><pre>Band.create(params.permit(bands: [:name, :year]))<br># =&gt; ActiveModel::UnknownAttributeError (unknown attribute &#39;bands&#39; for Band.)</pre><p>Our good ol’ friend the exception is telling us that our hypothesis was right. The create method received a Hash-like object with an unknown attribute, and not an Array. So what can we do to fix this? require will return the value associated with the bands key, so let’s chain that on and see what happens:</p><pre>params.permit(bands: [:name, :year]).require(:bands)<br># =&gt; [&lt;ActionController::Parameters {&quot;name&quot;=&gt;&quot;Radiohead&quot;, &quot;year&quot;=&gt;1985} permitted: true&gt;, &lt;ActionController::Parameters {&quot;name&quot;=&gt;&quot;Refused&quot;, &quot;year&quot;=&gt;1991} permitted: true&gt;]</pre><pre>Band.create(params.permit(bands: [:name, :year]).require(:bands))<br># =&gt; Created the records and returned them in an Array</pre><p>Wow! That worked!! We called permit first, so that we could accept an Array of data. That returned a Parameters object containing more Parameters structured as a Hash. To get the Array associated with the bands attribute from there, we just had to call require. Not too shabby.</p><p>We can now update our strong parameters method like so:</p><pre># changed the method&#39;s name, FYI<br>def bands_params<br>  params.permit(bands: [:name, :year]).require(:bands)<br>end</pre><p>&gt; <em>Note: For this example, I’m assuming all requests will pass an Array of Bands. If we wanted to accept both Arrays and Hashes, we could set up a separate route or use additional logic in the </em><em>create action to handle both types of data.</em></p><p><strong>Updating the create action</strong></p><p>Our create action is currently expecting to add a single record to the database. We’ll need to change this so that it creates multiple records. Here is our code so far with the updated strong params method:</p><pre>def create<br>  band = Band.new(band_params)</pre><pre>  if band.save<br>    render json: band<br>  else<br>    render json: { errors: band.errors.full_messages }<br>  end<br>end</pre><pre>private</pre><pre>def bands_params<br>  params.permit(bands: [:name, :year]).require(:bands)<br>end</pre><p>This most certainly is not going to work…at all.</p><p>At the moment, our Rails project has database-level validations (column modifiers) and model validations. This means that any invalid requests will fail on the model validations, since they directly mirror the column modifiers. We need to keep this in mind as we move forward, since it affects how we handle requests.</p><p>First, let’s try making the simplest change we can think of to our create action:</p><pre>def create<br>  bands = Band.create(bands_params)<br>  render json: bands<br>end</pre><p>First we’ll see what happens when we send only valid data:</p><pre>options = {<br>  method: &#39;POST&#39;,<br>  headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>  body: JSON.stringify({<br>    bands: [<br>      { name: &#39;oh yeah&#39;, year: 3000 },<br>      { name: &#39;wee bitz&#39;, year: 1980 }<br>    ]<br>  })<br>}</pre><pre>fetch(&#39;http://localhost:3000/bands&#39;, options)<br>.then(res =&gt; res.json())<br>.then(console.log)<br>.catch(console.log)<br>// =&gt; Array of Objects representing Band objects with IDs set</pre><p>Sending only valid data, resulted in all of our records being created and an Array of data being sent back in response. But what will happen if we send a mix of valid and invalid data?:</p><pre>options = {<br>  method: &#39;POST&#39;,<br>  headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>  body: JSON.stringify({<br>    bands: [<br>      { name: &#39;i am first&#39;, year: 1 },<br>      { name: &#39;i feel so alone&#39; }<br>    ]<br>  })<br>}</pre><pre>fetch(&#39;http://localhost:3000/bands&#39;, options)<br>.then(res =&gt; res.json())<br>.then(console.log)<br>.catch(console.log)<br>// =&gt; Array of Objects representing Band objects with one ID set and one set to null</pre><p>Both records were returned regardless, but only one was created in the database. On the frontend, we could choose to pinpoint the bad records, fix them, and then resend our request, but I’d prefer to go a different route: let’s handle our requests in an all-or-nothing manner. All records must be valid for any insertions to persist.</p><p><strong>Creating Records via Transactions</strong></p><p>We’re about to make a new friend: a class method called transaction. Transactions are protective blocks that help maintain the integrity of a database. Any SQL statements executed inside a transaction will persist only if all of the SQL statements were executed successfully. A single failure will cause the database to roll back to its previous state. In other words, it’s all or nothing!</p><p>For the transaction to do its job, we have to raise an exception when an insertion fails (The API documentation is really beautiful when it comes to transactions). This means we have to say goodbye to our friend create and make create! our new bestie. Let’s modify our controller code to utilize transactions:</p><pre>def create<br>  Band.transaction do<br>  # using an instance variable to make it available to render<br>  # otherwise we&#39;d have to declare bands in the outer scope as nil<br>    @bands = Band.create!(bands_params)<br>  end</pre><pre>  render json: @bands<br>end</pre><p>After sending a fetch request with only valid data, we receive the response we expect: an Array of Hashes containing valid Band records. But what happens if there’s invalid data in the request? First of all, no new records are created, the database is restored to its pre-HTTP-request state, so yay. In the web page’s console, we get an error message (the angry red one) stating “422 (Unprocessable Entity)”, and from the second then() we log an Object that looks like this:</p><pre>{status: 422, error: &quot;Unprocessable Entity&quot;, exception: &quot;#&lt;ActiveRecord::RecordInvalid: Validation failed: Year can&#39;t be blank&gt;&quot;, traces: {…}}</pre><p>It doesn’t have to be this way. We could handle the exception that’s raised in the controller if we prefer to send a different response.</p><p><strong>Handling the exception</strong></p><p>To handle the exception, we’ll make yet another friend, the begin-end block, because that’s what it does! Luckily, this requires only a small change to the create action:</p><pre>def create<br>  begin<br>    Band.transaction do<br>      @bands = Band.create!(bands_params)<br>    end<br>  rescue ActiveRecord::RecordInvalid =&gt; exception<br>    # omitting the exception type rescues all StandardErrors<br>    @bands = {<br>      error: {<br>        status: 422,<br>        message: exception<br>      }<br>    }<br>  end</pre><pre>  render json: @bands<br>end</pre><p>Now if a record is invalid, our custom response will be sent instead of the one generated by Rails:</p><pre>{<br>  error: {<br>    message: &quot;Validation failed: Year can&#39;t be blank&quot;,<br>    status: 422<br>  }<br>}</pre><p>We can now post multiple Bands at once to the database and send custom error messages when things go wrong!</p><p><strong>Summary</strong></p><p>Here’s a quick rundown of how to post multiple records embedded in an HTTP request with a single request:</p><ol><li>Update the strong params (or declare a new method) in the controller to accept an Array of data</li><li>Update the controller action (or declare a new one) to create records using create or create!</li><li>If you want an all-or-nothing outcome, use a transaction and create!</li><li>If you also want to respond with a custom error message, handle the exception created by the transaction</li></ol><p>And here’s the BandsController at the end of all this wordy madness:</p><pre>class BandsController &lt; ApplicationController<br>  def create<br>    begin<br>      Band.transaction do<br>        @bands = Band.create!(bands_params)<br>      end<br>    rescue ActiveRecord::RecordInvalid =&gt; exception<br>      @bands = {<br>        error: {<br>          status: 422,<br>          message: exception<br>        }<br>      }<br>    end</pre><pre>    render json: @bands<br>  end</pre><pre>  private</pre><pre>  def bands_params<br>    params.permit(bands: [:name, :year]).require(:bands)<br>  end<br>end</pre><p><a href="https://github.com/helloRupa/mass_create_example">GitHub Repo</a></p><p>Why so many words for so little code? I’m a deep sea diver who operates on land. Sometimes I can’t help myself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a45261085164" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Auth with JWT: But Why?]]></title>
            <link>https://codersloth.medium.com/auth-with-jwt-but-why-36a2e72afe04?source=rss-69186b461ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/36a2e72afe04</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[cookies]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[sessions]]></category>
            <dc:creator><![CDATA[coderSloth]]></dc:creator>
            <pubDate>Wed, 05 Feb 2020 05:53:27 GMT</pubDate>
            <atom:updated>2020-02-07T20:03:28.792Z</atom:updated>
            <content:encoded><![CDATA[<h3>A wise man once asked me why a developer would choose JWT (JSON Web Tokens) over a traditional session cookie, and I thought, what if I do a bunch of research and write a really long article about that! So here it goes, let’s do some brain chewing!</h3><p><em>Note: this article mostly focuses on browser-based sessions. There are little bits here and there about native app sessions, but not much, as the rabbit holes are many and incredibly deep.</em></p><p><strong>Who should read this?<br></strong>Anyone who is new to JWT or authentication and authorization, or doesn’t know when to choose JWT over traditional session cookies.</p><p><strong>Prerequisite Knowledge<br></strong>State and the Web, basic understanding of HTTP request-response cycle</p><p><strong>What’s in this article?<br></strong>Auth with session cookies, auth with JWT, backend control of sessions, web storage vs cookie jar, CORS requests, a brief note on native apps, use cases, conclusion</p><p><strong>But I just want a tutorial!<br></strong>That’s not what this is. Move along buddy…or stay and enjoy some good ol’-fashioned thinking.</p><p><strong>I noticed a mistake in the article</strong></p><figure><img alt="You ought to know" src="https://cdn-images-1.medium.com/max/474/1*PeBMKQbRfIfL3NAPar_P2A.jpeg" /><figcaption>Image from <a href="https://cheezburger.com/4226774016">cheezburger.com</a></figcaption></figure><p>Tell me about it. Seriously. Very seriously.</p><p><strong>Can I have the short version?<br></strong>JWT is a good option (but not the only one) to consider when you need to:</p><ul><li>Authorize access across multiple domains / services</li><li>Reduce database requests to speed up a site (if session authorization requests are causing the issue)</li><li>Create an API that works with browser-based and native apps</li><li>Scale an app horizontally (i.e. add more servers)</li></ul><p><em>Note that I’m not saying the above can’t be done with traditional sessions or other technologies.</em></p><p>You might want to skip JWT if the app or API:</p><ul><li>Already works well with old-fashioned session cookies</li><li>Is served only in a browser</li><li>Doesn’t receive Reddit-level traffic :(</li><li>Will never be “publicly” available (i.e. the API serves your site but no others)</li><li>Transmits specific user information with every auth request (i.e. each request MUST result in a query of the users database where the session data is also stored — ignore this bullet if sessions are stored in a separate database)</li><li>Requires fine-grained tracking and control of a user’s sessions from the backend</li></ul><p>This is just a starting point for thinking about using server-side sessions vs. JWT. With time, experience, and research, I’m sure you’ll come up with many more.</p><p>Also, asking “JWT or session cookie?” is probably the wrong question — a better question is to ask whether the application needs stateful sessions or stateless sessions, and then from there, decide on the proper implementation. This will make more sense if you read the rest of the article.</p><h3>A short(ish) analogy to keep in mind as you learn more</h3><figure><img alt="Gandalf the Gray Bouncer" src="https://cdn-images-1.medium.com/max/500/1*mtcqkeTh7DqU5l5kwB1Y4g.jpeg" /><figcaption>Image from <a href="https://funnyjunk.com/funny_pictures/3582681/Gandalf+the+bouncer/">funnyjunk.com</a></figcaption></figure><p>Think of JWT like a state or national ID card. First, you have to go to a government office, show some form of identification to prove you are who you say you are, and then you’re issued with a shiny new ID card. Now, when you go to the club and the bouncer asks you to prove you’re over 18 years old, you just show your ID. The bouncer looks for specific markers on the ID, and if it looks genuine, they let you in, and you dance the night away to the smooth sounds of <a href="https://www.youtube.com/watch?v=XXvuUp-KY5g">Daybreak</a>.</p><p>Traditional cookie-based sessions are a little different. The bouncer doesn’t just look at your ID card, they also call the issuing government office to verify the details on your ID card. Once the government gives the thumbs up, the bouncer lets you enter the club and enjoy those saxy sounds.</p><p>Now let’s say you do something that really riles the government’s feathers, causing ‘The Man’ to invalidate your ID. However, you still have your ID card in your possession. In the JWT scenario, the bouncer looks at your ID card, sees that it’s not expired, and lets you in — you get a night filled with smooth jazz. In the cookie-based scenario, the bouncer calls a government office and finds out your ID card isn’t worthy — no jazz for you! (Note: there are ways to immediately take away your access with JWT — the JWT bouncer would have to act more like the session cookie bouncer, more on that later).</p><h3>Auth with session cookies</h3><p>Before we dive into JWT, let’s make sure we understand the basic auth pattern with our good old-fashioned session cookies (just because they’re old, doesn’t mean they’re obsolete!). Keep in mind this is one way of handling it — there are others!</p><ol><li>Jambaby visits catdanceparty.com and is presented with a login page.</li><li>Jambaby enters their credentials, in this case a username and password, correctly.</li><li>Jambaby’s credentials are securely transmitted to catdanceparty.com via a POST request.</li><li>The site’s server receives the request, and looks up Jambaby’s credentials in the appropriate database. There’s a match, so the server generates a unique session identifier (randomized url-safe string) and stores it in the database. (If there isn’t a match, a session identifier will not be generated and Jambaby will not receive a precious, tasty cookie. Poor, sad Jambaby.)</li><li>The server sends a cookie containing the unique session identifier to Jambaby’s browser (aka the client). The client is then redirected to the appropriate page.</li><li>Jambaby lands on a protected page. The browser sends the session cookie (from the previous step) to the server as part of the GET request.</li><li>The server parses out the unique session identifier from the cookie, looks up the identifier in the database, and finds a match. The protected page loads successfully. (If a valid identifier were not found, the protected page would not load.)</li></ol><p>In summary, any time a user (the Jambaby of the story) wants to access a protected route on the site, their unique session identifier must be looked up in the appropriate database. In other words, more requests for access means more database queries.</p><figure><img alt="Request-response cycle with session cookie" src="https://cdn-images-1.medium.com/max/691/1*xm5CxSS41CABGUkjY-sMjA.png" /><figcaption><em>The above illustration is only concerned with illustrating requests for authentication and authorization. For an SPA, the server would respond with JSON, and the frontend would control the routing.</em></figcaption></figure><h3>Auth with JWT</h3><p>One of the benefits of using JWT, or other tokens, for authentication is that we don’t have to store and access session data in a database. Instead, the server receiving the authorization request merely checks if the JWT is valid, similar to how the bouncer at the club looks at an ID card instead of calling a government office (aka the database).</p><p><strong>So what exactly is this JWT business?<br></strong>JWT refers to a specific data format — it does not refer to how or where that data should be stored (e.g. cookies or web storage) or accessed. So what does a JWT look like? <a href="https://jwt.io/#debugger-io?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmbGF0aXJvbiIsIm5hbWUiOiJ0b2tlbnRpbWUiLCJpYXQiOjE1Nzk4MDkwMjIsImN1c3RvbSI6ImknbSBnbGFkIHlvdSBtYWRlIGl0IHRoaXMgZmFyIGluIHRoZSByZWFkaW5nLCBwYXQgeW91cnNlbGYgb24gdGhlIGJhY2sifQ.hHJa6miIHQ7ldf_effL4YrM0_EzpOYe9SggSqnPXiRk">eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmbGF0aXJvbiIsIm5hbWUiOiJ0b2tlbnRpbWUiLCJpYXQiOjE1Nzk4MDkwMjIsImN1c3RvbSI6ImknbSBnbGFkIHlvdSBtYWRlIGl0IHRoaXMgZmFyIGluIHRoZSByZWFkaW5nLCBwYXQgeW91cnNlbGYgb24gdGhlIGJhY2sifQ.hHJa6miIHQ7ldf_effL4YrM0_EzpOYe9SggSqnPXiRk</a></p><p>If you look carefully at that beautiful string above, you’ll see that it’s dot separated. Each dot denotes the beginning of a new part of the token. Every JWT has the following parts in the same order: Header.Payload.Signature</p><p><strong>Parts of a JWT</strong></p><pre>{<br>  &quot;alg&quot;: &quot;HS256&quot;,<br>  &quot;typ&quot;: &quot;JWT&quot;<br>}</pre><p>The header typically consists of two parts — the signing algorithm and the type of token, which is ‘JWT’. The signing algorithm must be specified in order to validate the signature (this will make more sense soon, promise).</p><pre>{<br>  &quot;sub&quot;: &quot;1234567890&quot;,<br>  &quot;name&quot;: &quot;Blarney McDougalPants&quot;,<br>  &quot;iat&quot;: 1516239022,<br>  &quot;custom&quot;: &quot;I am so special&quot;<br>}</pre><p>The payload contains information, called claims, that is specific to an application’s needs. For example, an application might need an expiration date for the token and the name of the issuer as well as other non-sensitive data. Since the payload can easily be <a href="https://www.google.com/search?q=decode+base64&amp;oq=decode+&amp;aqs=chrome.2.69i57j0l6j69i60.3031j1j7&amp;sourceid=chrome&amp;ie=UTF-8">decoded</a>, it’s important to not store sensitive data, such as any information that can be used to identify a person, in a JWT.</p><pre>BgnTL5iqjdvsC-LSCD9YNlmpcn6ppU7_OZWYj3uHoPs</pre><p>The signature is used to confirm that the token wasn’t tampered with before or during transmission. Once a server receives a JWT, it can confirm that the JWT is valid by running the encoded header and payload along with the secret through the hashing algorithm specified in the header to generate its signature. If the generated signature matches the received JWT’s signature, the JWT is valid. This will make more sense in a moment.</p><p><strong>But why does it look like nonsense?<br></strong>We write the header and payload as ordinary JSON, and then those parts are encoded using the base64url encoding scheme, which basically spits out strings that look like gibberish. After that, the signature needs to be created.</p><p>To make the signature, the encoded header and payload are hashed with a secret (another nonsensical-looking string) using a hashing algorithm, which is specified in the header. The hashed string is then encoded in the same manner as the header and payload. The secret, provided it remains a secret, makes it difficult for malicious users to forge or tamper with a JWT, since they need the secret to generate a valid signature. If you’re familiar with password salting, you can think of the secret as being similar to the salt.</p><figure><img alt="Diagram of how the signature is created" src="https://cdn-images-1.medium.com/max/555/1*TOhy4kymr3-zlr0OBtN05g.png" /><figcaption>hs256(encoded_header + ‘.’ + encoded_payload, secret)</figcaption></figure><p><strong>Basic Auth Flow with Stateless JWT<br></strong>This is <em>one possible way</em> JWT can be used for authenticating and authorizing a user:</p><ol><li>Jambaby visits catdanceparty.com and is presented with a login page.</li><li>Jambaby enters their credentials, in this case a username and password, correctly.</li><li>Jambaby’s credentials are securely transmitted to catdanceparty.com via a POST request.</li><li>The site’s server receives the request, and looks up Jambaby’s credentials in the appropriate database. There’s a match, so the server generates a JWT with an expiration date inside of it.</li><li>The server sends the JWT to Jambaby’s browser (aka the client). The client stores the token and is then redirected to the appropriate page.</li><li>Jambaby lands on a protected page. The browser sends the JWT (from the previous step) to the server as part of the GET request.</li><li>The server checks if the JWT is valid by generating the signature for the given JWT and checking if it matches the signature on the JWT sent by the client. If there’s a match and the JWT has not yet expired, the protected page loads successfully. (If the signatures didn’t match or the JWT were expired, the protected page wouldn’t load).</li></ol><figure><img alt="JWT session flow" src="https://cdn-images-1.medium.com/max/691/1*6zCIYr0Agoyy6UQoBUNTrQ.png" /><figcaption><em>The example above assumes there’s a database dedicated to storing only credentials. It does not illustrate the usage of any other databases that may be required to complete requests. For an SPA, the server would respond with JSON, and the frontend would control the routing.</em></figcaption></figure><p>In summary, any time a user (the Jambaby of the story) wants to access a protected route on the site, the server simply checks if the JWT is valid. In other words, more requests for access does not necessarily mean more database queries.</p><h3>Backend control of traditional sessions vs. JWT sessions</h3><figure><img alt="Hacker Man Meme" src="https://cdn-images-1.medium.com/max/680/1*jXtn95gSG5AO2hJc9OIGmA.png" /><figcaption>Image from <a href="https://i.kym-cdn.com/entries/icons/original/000/021/807/ig9OoyenpxqdCQyABmOQBZDI0duHk2QZZmWg2Hxd4ro.jpg">knowyourmeme.com</a></figcaption></figure><p>Depending on the application, we might need fine-grained control over every users’ sessions from the backend. Any web app that stores sensitive data will likely need backend control over individual sessions, e.g. automatically or manually logging a user out. Another way to think of this is to ask yourself, “How much damage can a hacker do to a user if the hacker hijacks a user’s session?” There are other reasons for needing backend tracking and control, but we’ll stick with Hackerman as our main reason.</p><p><strong>Cookie-based sessions vs. stateless JWT sessions<br></strong>One of the benefits of using stateless JWT sessions is that it has the potential to result in fewer database queries. With cookie-based sessions, every attempt to access a protected route results in a database query to check if the session is valid. JWT, on the other hand, only requires the server to validate the token’s signature — no lookups are necessary. However, there are some downsides to using stateless JWT sessions.</p><p>With a cookie-based session, it’s common to associate a user’s session with a unique session ID in a sessions database (or some other storage mechanism). On the backend, this means we can easily log out a single user by nullifying or changing their session ID so that it no longer matches the ID stored in the client’s session cookie. If we have reason to believe a specific user’s account has been compromised, or if the user’s permissions or password have changed (or maybe they forgot my birthday), we can simply update the session’s ID on the backend, and they’re logged out. It’s also possible to keep track of which sessions are active on different user devices.</p><p>Since stateless JWT means we aren’t storing session data server-side, we can’t easily nullify users’ sessions. If a user changes their password, we can’t log them out on any devices other than the one used to change the password. If we suspect a specific account has been hacked, we can’t nullify the session on the backend, because we aren’t storing any session data. Lastly, if we’re storing any data about a user’s permissions in a JWT and we then change those permissions on the backend, that user will have the old-level of access until their JWT expires. For the last example, we could check the user’s permissions in the database for any permission-protected requests, but that might negate the benefits of using stateless JWT for authorization, since it would result in additional database queries.</p><p>It’s equally easy to log out all users at once with either approach. For cookies, we can nullify all of the session data, or if we’re using encrypted cookies, we can update the secret used to decrypt the cookies. For JWT, just change the secret used to validate the tokens’ signatures.</p><p><strong>Cookie-based sessions vs. stateful JWT sessions<br></strong>But wait, I thought JWT was stateless?! Well, in a way, JWT can be anything we want it to be (except our best friend, because that would be weird), including stateful. There are a number of ways to make JWT stateful — two common methods include whitelisting and blacklisting tokens. Both of those methods require storing and accessing data server-side in order to validate tokens.</p><p>A JWT whitelist will include identifiers for all tokens that should be honored. A blacklist will include identifiers for all tokens that should be rejected. In either case, we’ll need to automate tasks that keep these lists up to date. For example, there’s no reason to keep a token on either list once it officially expires. Using a whitelist or blacklist gives us control over user accounts in the same way traditional sessions do, since we now have the power to revoke access on the backend by either adding a token to the blacklist or removing it from the whitelist. However, we now have to look up whether or not a token is valid, just like we have to look up session IDs, in addition to validating the signature.</p><p><strong>Summary<br></strong>Ultimately, the amount of control we need over a user’s sessions depends on the application and the type of user data we’re storing. If we don’t need to quickly and easily revoke access, we can consider using stateless JWT sessions. If we need fine-grained control, we’ll need stateful sessions.</p><h3>Web storage vs cookie jar</h3><figure><img alt="Cookie Monster thinking" src="https://cdn-images-1.medium.com/max/580/1*TrcL10K1WF2rYVHYu3R51Q.jpeg" /><figcaption>Image from <a href="https://www.themarysue.com/sesame-street-what-does-the-fox-say/">themarysue.com</a></figcaption></figure><p>While traditional sessions are always stored in cookies, tokens can be stored in cookies or web storage. There are a lot of opinions on whether JWTs should be stored in cookies or web storage, but ultimately, it depends on the specifics of the web app. Let’s find out what differentiates cookies from web storage, and what that means for us.</p><p><strong>What is a cookie?<br></strong>A cookie is a small file containing data stored in key-value pairs. It can be set on the client by the web server, when sent in the response, or by client-side JavaScript. Cookies can store up to ~4 kilobytes of data, and they are automatically sent by the browser with every request to the domain where the cookie originated. Since they are automatically sent by the browser and increase the size of each request, they may reduce performance for users who do not have high-speed internet access.</p><p>A cookie can be persistent, i.e. remain in storage after the browser is closed (until they reach the expiration date or are deleted by the user), or session-based, i.e. deleted when the browser is closed. Browsers automatically store cookies in their own “cookie jar,” preventing one domain from accessing another domain’s cookies (i.e. catdanceparty.com only has access to its own cookies).</p><p>Depending on the flags used when a cookie is set, it can be accessed by JavaScript and HTTP requests or only by HTTP requests. We can prevent JavaScript from having access to cookies by setting them using the “HttpOnly” flag, which defends our cookies against <a href="https://owasp.org/www-community/attacks/xss/">cross-site scripting (XSS) attacks</a>. We can further protect cookies by setting the “secure” flag, which limits them to being sent in requests over HTTPS only. On the server-side, we’ll need to ensure all responses are sent over HTTPS, preventing the efficacy of <a href="https://us.norton.com/internetsecurity-wifi-what-is-a-man-in-the-middle-attack.html">man-in-the-middle attacks</a>. HttpOnly cookies, however, are vulnerable to <a href="https://portswigger.net/web-security/csrf">CSRF attacks</a>, which we defend against using <a href="https://portswigger.net/web-security/csrf/tokens">CSRF tokens</a>.</p><p><strong>What is web storage?<br></strong>Web storage allows sites to store data in key-value pairs to a client’s browser, similar to cookies. However, the storage limit is much higher (up to 5MB, but depends on the browser). Data stored in web storage is not automatically sent with each request, and it is stored and accessed using client-side JavaScript.</p><p>Data can be stored in web storage via local storage or session storage, both of which can be cleared with JavaScript. Data stored in local storage persists and has no expiration date. It is cleared when a user clears the browser’s cache. Anything stored in session storage is automatically deleted when the user closes their browser or the tab displaying the website. Similar to cookies, when a site stores information in web storage, only that site has access to that data.</p><p>Information stored in web storage is vulnerable to XSS attacks, since it can be accessed by JavaScript. Extra care must be taken when using third-party JavaScript to ensure it does not contain any malicious code. Unlike cookies, there is no built-in method or flag to ensure data stored in web storage is sent over HTTPS only when including it in requests. However, there is middleware that can do this for us or we can write our own scripts.</p><p><strong>Summary<br></strong>We can’t really say it’s better or safer to use web storage or cookies, since it all comes down to the specifics of the web app, but cookies do appear to have a slight edge in browser-based applications. HttpOnly cookies aren’t vulnerable to XSS attacks, which is important since it’s common practice to use many third-party scripts in a single web app. It’s also easier to ensure that cookies are sent with requests only over a secure connection (HTTPS) by using the “secure” flag. However, cookies are vulnerable to CSRF attacks, while data in web storage is not.</p><p>When creating browser-based apps, cookies have the added convenience of automatically being sent with each request. The same is not true for data stored in web storage. However, manually sending data typically does not require much additional code to be written on the client-side, and it may reduce the overall size of all combined requests coming from a single client, since the additional data is only included with the requests as needed (provided the app is coded that way). Conversely, <a href="https://dzone.com/articles/cookies-vs-tokens-the-definitive-guide">JWTs are typically larger than cookies</a>, since they typically store more data than session cookies, and this might actually increase the overall size of all combined requests. ¯_(ツ)_/¯</p><p>Lastly, some organizations advise against storing session identifiers and sensitive information in web storage at all due to the threat of XSS attacks, which they estimate is a larger threat than CSRF attacks.</p><h3>Cross-Origin Resource Sharing (CORS)</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F122ieBYC3AcECI%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2F122ieBYC3AcECI&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F122ieBYC3AcECI%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/b792447076a74092026dbe852fa997e9/href">https://medium.com/media/b792447076a74092026dbe852fa997e9/href</a></iframe><p>Web apps commonly request resources from other domains, e.g. catdanceparty.com might request images from catpartyimages.com. Or the frontend and backend might be hosted on two different servers. In either case, you’re going to end up with a good ol’ CORS request! You probably know them well, they’re those requests that fill your developer console with all kinds of fun errors, like this famous ditty:</p><pre>Cross-Origin Request Blocked: <br>The Same Origin Policy disallows <br>reading the remote resource at <br>https://dancemagicdance.com/</pre><p>Pure poetry!</p><p>Those CORS request errors occur when a request to one domain comes from a completely different domain. The server that receives the request has control over which other domains, if any, can access its resources. When we set up a new project using a framework like Rails, CORS requests are disallowed on the server-side by default (It’s actually the browser that enforces the policy, but the server sets the rules). We’re not going to go into detail about server-side settings — just know that we can allow a single domain, all domains, or whitelisted domains to make requests, and that certain requests require cookies or tokens to be sent along with them in order for the client to receive a successful response. Any server that is expected to receive CORS requests must be configured to allow them.</p><p><strong>CORS requests with httpOnly cookies<br></strong>Let’s say our server is configured to accept third-party requests, but data stored in a cookie is required for the request to receive a successful response. We are on catdanceparty.com, and from that page, a request is made to secretcatdances.co.uk (CORS request) to retrieve some super secret cat dance gifs. Since we are making a request to a different domain, none of catdanceparty.com’s cookies are sent by the browser, so the request is unsuccessful. An error appears in our browser. To remedy this, there are a couple of things we must do.</p><p>On the server-side, when it sets the cookie on the client, the cookie’s domain/path properties will have to be set in order to tell the browser where that cookie is allowed to be sent.</p><p>On the client-side, we must tell the browser that we want to send credentials with the request. When making a fetch request, we set ‘credentials’ to ‘include’ (in an XMLHTTPRequest, we would set ‘withCredentials’ to ‘true’). As long as the server is configured to receive CORS requests, and the cookie and request have been set properly, the request should result in a successful response.</p><p><strong>CORS requests with tokens in web storage<br></strong>Once again, our server is configured to accept CORS requests, but this time we’ve stored our authorization data in a JWT in web storage, instead of an httpOnly cookie. Since the token is accessible by JavaScript, we use JavaScript to access the token and add it to the Authorization header with our request to secretcatdances.co.uk. The CORS request completes with a successful response from secretcatdances.co.uk.</p><p><strong>Summary<br></strong>I’m not going to say which sounds easier than the other, but I think you know which one I’m thinking of.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*dQo88N-YQHE268FnpecZUQ.png" /><figcaption>Sorry, I couldn’t help myself. Image from <a href="https://imgflip.com/memetemplate/Oprah-You-Get-A">imgflip.com</a></figcaption></figure><h3>Native app auth</h3><p>If we’re designing native apps or an API that will communicate with them, tokens seem like the way to go. There are a lot of debates regarding whether or not cookies should or can be used for authentication and authorization in native mobile apps. The short story is this: some say it’s easy to implement auth with cookies and others say it’s difficult, and a few say it’s impossible! It is possible to implement auth either way, but there does appear to be more support — including tutorials, out-of-the-box solutions, and opinions — for using tokens in native apps. As of writing, <a href="https://facebook.github.io/react-native/docs/network#known-issues-with-fetch-and-cookie-based-authentication">React Native has issues with implementing fetch and cookie-based authentication</a>. However, both iOS and Android native apps support the use of cookies.</p><p>Whether the API uses cookies or tokens, the native app will have to explicitly send that data with each request and handle it, as needed, with every response.</p><h3>Use Cases</h3><p>Here are some (and I mean some in a very small sense) examples illustrating when and why you might choose JWTs or cookie-based sessions, state or no state.</p><p>Jarlo is working on a browser-based web app where users create cat dance parties using different gifs, music, and background images. Users save their dance parties to their accounts, so they can view, edit, and delete them later. When users sign up, they specify their own unique username and password. The site never asks for or stores any personal information that could be used to identify a specific user. Since the data stored on the website doesn’t have much value and can’t harm users in any meaningful way, Jarlo decides to implement sessions using stateless JWT. Even if a malicious user hijacks another user’s session, the worst they can do is view, edit, or delete that user’s dance parties, or prevent a user from accessing their largely worthless account (worthless from a data perspective).</p><p>Sumya is creating a browser-based web app where users track their fitness goals and overall health. The app collects personal data, such as a user’s email, weight, height, and more. She doesn’t expect the app to grow beyond a small user base and doesn’t plan on expanding to native mobile apps. Since the data stored in the backend includes personal user data, Sumya decides to implement stateful sessions with secure http-only cookies. A malicious user could do a lot of damage, so Sumya needs full control over access on the backend.</p><p>Charlie is expanding the number and types of web services the users of his company’s site have access to. This involves adding more servers to host the different services. There is currently no infrastructure in place for handling authorization across servers, since they’ve been running off of a single server until now. In the near future, they are planning to integrate their services with native mobile apps. Charlie decides to use stateless JWT to ensure only authorized users get access to the various services. He ensures that each token expires within a very short timeframe to limit any possible damage a malicious user can do.</p><p>Bernice’s company runs a social networking site available via browsers and a native app. The site is already successfully using cookie-based sessions and sticky sessions to ensure users remain logged in when accessing different resources. The social network’s user base is growing, and they need to scale horizontally. Since they are already using sticky sessions successfully, they decide to stick with those — the time and expense of switching the auth infrastructure isn’t worth it at this time.</p><p>Emilia is creating a publicly available API. She needs to ensure only authorized applications can access the API and wants to support as many devices as possible. Emilia decides to use stateful JWT to control access to the API. When the client sends a token with their request to the API, the client’s token is validated and looked up server-side. The client’s requests are tracked for billing purposes and rate limiting.</p><h3>Conclusion</h3><p>Any time we want to implement authentication and authorization, we have to ask ourselves several questions:</p><ol><li>Who is the client?</li><li>How valuable is the data we’re protecting? To our users and to us?</li><li>What could a malicious user do if they gained access to another user’s account?</li><li>How much, if any, information do we need about what our users are doing?</li><li>How much control do we need over individual user sessions?</li><li>Will different servers need to communicate with one another to complete requests?</li></ol><p>If the data stored is of low value and cannot be used to harm someone, stateless sessions with little-to-no backend control may be acceptable, and we can store the session data in a cookie or web storage. However, if fine-grained control over sessions is required, which will likely be the case if the data being accessed by clients is of high value, we must use stateful sessions.</p><p>How we choose to implement those sessions is up to us: we can make a case for storing session data in cookies or JWTs in browser storage. HttpOnly cookies will provide protection against XSS attacks, but require a little more work to configure for CORS requests, while JWTs in browser storage are easier to work with for CORS requests, but may be less secure than httpOnly cookies due to the threat of XSS attacks. That’s a lot to think about, and we’ve only scratched the surface!</p><p>Now treat yourself to the smooth sounds of <a href="https://www.youtube.com/watch?v=XXvuUp-KY5g">Daybreak</a>.</p><h3>Googleables</h3><p>SameSite cookies, encrypted cookies, JWT refresh token, JSON Web encryption, cross-domain SSO flow, XSS attack, CSRF attack, Redis sessions, microservice architecture, horizontal vs vertical app scaling, sticky session, load balancer, cookie headers, dancing peanut fail (just for fun)</p><h3>Resources</h3><p>Introduction to JSON Web Tokens <a href="https://jwt.io/introduction/">https://jwt.io/introduction/</a></p><p>The Complete Guide to JSON Web Tokens <a href="https://blog.angular-university.io/angular-jwt/">https://blog.angular-university.io/angular-jwt/</a></p><p>Sticky Session <a href="https://www.imperva.com/learn/availability/sticky-session-persistence-and-cookies/">https://www.imperva.com/learn/availability/sticky-session-persistence-and-cookies/</a></p><p>Stop Using JWT for Sessions <a href="http://cryto.net/~joepie91/blog/2016/06/13/stop-using-jwt-for-sessions/">http://cryto.net/~joepie91/blog/2016/06/13/stop-using-jwt-for-sessions/</a></p><p>MDN Web Docs: HTTP Cookies <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies">https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies</a></p><p>Cross-Origin Resource Sharing (CORS) <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS</a></p><p>Understanding Cross-Origin Resource Sharing (CORS) <a href="https://dev.to/miguelmota/understanding-cross-origin-resource-sharing-cors-2i3e">https://dev.to/miguelmota/understanding-cross-origin-resource-sharing-cors-2i3e</a></p><p>Where to Store Your JWTs: Cookies vs. HTML5 Web Storage <a href="https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage">https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage</a></p><p>Cookies vs. Tokens: The Definitive Guide <a href="https://dzone.com/articles/cookies-vs-tokens-the-definitive-guide">https://dzone.com/articles/cookies-vs-tokens-the-definitive-guide</a></p><p>Cookies in Mobile: Do they exist? <a href="https://www.socialmediatoday.com/content/cookies-mobile-do-they-exist">https://www.socialmediatoday.com/content/cookies-mobile-do-they-exist</a></p><p>Horizontal vs. Vertical Scaling: Which is Right for Your App? <a href="https://www.missioncloud.com/blog/horizontal-vs-vertical-scaling-which-is-right-for-your-app">https://www.missioncloud.com/blog/horizontal-vs-vertical-scaling-which-is-right-for-your-app</a></p><p>React Native Documentation: Networking <a href="https://facebook.github.io/react-native/docs/network">https://facebook.github.io/react-native/docs/network</a></p><p>Secure Yet Simple Authentication System for Mobile Applications <a href="https://readybytes.in/blog/secure-yet-simple-authentication-system-for-mobile-applications">https://readybytes.in/blog/secure-yet-simple-authentication-system-for-mobile-applications</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36a2e72afe04" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>