<?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 UKPAI Chukwuemeka on Medium]]></title>
        <description><![CDATA[Stories by UKPAI Chukwuemeka on Medium]]></description>
        <link>https://medium.com/@ukpai?source=rss-8aebf678c904------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vH-x6xZPJ9XFTvxBviE7dQ.jpeg</url>
            <title>Stories by UKPAI Chukwuemeka on Medium</title>
            <link>https://medium.com/@ukpai?source=rss-8aebf678c904------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 20:44:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ukpai/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[Create your first NPM Package — 2025 Edition]]></title>
            <link>https://medium.com/@ukpai/create-your-first-npm-package-2025-edition-217b44a87671?source=rss-8aebf678c904------2</link>
            <guid isPermaLink="false">https://medium.com/p/217b44a87671</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[UKPAI Chukwuemeka]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 11:50:39 GMT</pubDate>
            <atom:updated>2025-08-25T11:50:39.713Z</atom:updated>
            <content:encoded><![CDATA[<h3>Create your first NPM Package — 2025 Edition</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dPySBLaPRENoVlz7cyPZ3g.png" /><figcaption>Photo by Ukpai Chukwuemeka</figcaption></figure><blockquote>Five years ago, I published my first npm package together with a couple of friends from <strong>Andela Teen Code Africa</strong>.</blockquote><p>It was our contribution to <strong>Hacktoberfest</strong>, the annual open-source event that happens every October.</p><p>The package was simple — It helped developers initialize a .gitignore file based on the environment they were working in.</p><p>Whether it was Java, React, or Node.js, the <strong>dotgitignore</strong> package as we called it would generate the right .gitignore for you.</p><p>Fast forward to 2025, I’ve got a couple of new ideas I’m working on, some of them centered around npm packages.</p><p>So, I started looking for resources to guide me through the process.</p><p>While there are plenty of tutorials out there, one particular approach stood out as the easiest way to get started.</p><p>In this article, I’ll walk you through the <strong>step-by-step process</strong> so you can create and publish your first npm package.</p><h3>Types of NPM Packages</h3><p>Broadly, npm packages fall into <strong>two categories</strong>:</p><h4><strong>Library packages</strong></h4><p>The kind you import and use in your code</p><pre>import axios from &#39;axios&#39; </pre><h4><strong>CLI packages</strong></h4><p>The kind you run from the terminal</p><pre>npx create-react-app my-app </pre><p>Understanding this difference will help you structure and publish your package effectively.</p><h3>Prerequisites</h3><ul><li>Node.js ≥ 20</li><li>An <strong>npm account</strong> (<a href="https://www.npmjs.com/signup">signup here</a>)</li><li>A <strong>GitHub account</strong> to host your code (<a href="http://github.com/">signup here</a>)</li><li>Basic familiarity with JavaScript/TypeScript</li></ul><h3>How to Create NPM Library Package</h3><p>As I mentioned earlier a <strong>library package</strong> is something other developers can import into their projects.</p><p>To keep things simple, let’s build a <strong>string utilities library</strong> with two functions:</p><ul><li>capitalize(str) → capitalizes the first letter of a string</li><li>reverse(str) → reverses a string</li></ul><h3>Step 1. Set up NPM Library Package project</h3><p>We are going to do three things in this step:</p><ol><li>Create a new directory for our package, your package name must be unique</li><li>Change into that directory so we’re working inside it</li><li>Create Package.json and Initialize git</li></ol><blockquote>⚠️ Important: Every npm package name must be unique across the entire registry.</blockquote><blockquote>If you pick a name that’s already taken (for example, string-utils), npm won’t let you publish it.</blockquote><p>To check if your package name is available, run:</p><pre>npm search string-utils</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KVnPdDYKyJU9NduUlE5p8Q.png" /><figcaption>npm search result screenshot by ukpai chukwuemeka</figcaption></figure><p>Since the package<strong> </strong><strong>string-utils</strong> is not available, You can attach a prefix to your package name <strong>bwu-string-utils</strong>.</p><p>Run the following commands:</p><pre>mkdir bwu-string-utils      # create a new folder<br>cd bwu-string-utils         # move into the folder<br>npm init -y                 # initialize a new npm project<br>git init                    # initialize git for version control</pre><p>This will generate a <strong>package.json</strong> file for you and initialize git.</p><p>Update your version manually in <strong>package.json</strong> to 0.0.1.</p><pre>{<br>  &quot;name&quot;: &quot;bwu-string-utils&quot;,<br>  &quot;version&quot;: &quot;0.0.1&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;<br>  },<br>  &quot;keywords&quot;: [],<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;description&quot;: &quot;&quot;<br>}</pre><h3>Step 2. Setup Typescript</h3><p>Install typescript as a dev dependency, once it’s completed you can initialize typescript.</p><pre>npm i --save-dev typescript<br>npx tsc --init</pre><p><strong>Update tsconfig</strong></p><pre><br>{<br>  // Visit https://aka.ms/tsconfig to read more about this file<br>  &quot;compilerOptions&quot;: {<br>    /* Base Options: */<br>    &quot;esModuleInterop&quot;: true,<br>    &quot;skipLibCheck&quot;: true,<br>    &quot;target&quot;: &quot;es2022&quot;,<br>    &quot;verbatimModuleSyntax&quot;: true,<br>    &quot;allowJs&quot;: true,<br>    &quot;resolveJsonModule&quot;: true,<br>    &quot;moduleDetection&quot;: &quot;force&quot;,<br>    /* Strictness */<br>    &quot;strict&quot;: true,<br>    &quot;noUncheckedIndexedAccess&quot;: true,<br>    /* If NOT transpiling with TypeScript: */<br>    &quot;moduleResolution&quot;: &quot;Bundler&quot;,<br>    &quot;module&quot;: &quot;ESNext&quot;,<br>    &quot;noEmit&quot;: true,<br>    /* If your code runs in the DOM: */<br>    &quot;lib&quot;: [<br>      &quot;es2022&quot;,<br>      &quot;dom&quot;,<br>      &quot;dom.iterable&quot;<br>    ],<br>  }<br>}</pre><h3>Step 3. Write Your Code</h3><p>Create <strong>.gitignore</strong> file</p><pre>touch .gitignore</pre><p>Add the following to your <strong>.gitignore</strong> file</p><pre>node_modules<br>dist</pre><p>Then add and commit your changes</p><pre>git add .<br>git commit -m&quot;chore: add and initialize typescript&quot;</pre><p>Next create an <strong>index.ts</strong> file with the following:</p><pre>// index.ts<br><br>export function capitalize(str) {<br>  return str.charAt(0).toUpperCase() + str.slice(1);<br>}<br><br>export function reverse(str) {<br>  return str.split(&quot;&quot;).reverse().join(&quot;&quot;);<br>}</pre><h3>Bundle with tsup</h3><p>Install <a href="https://github.com/egoist/tsup"><strong>tsup</strong></a> to compile and bundle:</p><pre>npm i --save-dev tsup</pre><p>Update <strong>package.json</strong>:</p><pre>{<br>  &quot;name&quot;: &quot;buw-string-utils&quot;,<br>  &quot;version&quot;: &quot;0.0.1&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;build&quot;: &quot;tsup index.ts --format cjs,esm --dts&quot;,<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;<br>  },<br>  &quot;keywords&quot;: [],<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;devDependencies&quot;: {<br>    &quot;tsup&quot;: &quot;^8.5.0&quot;,<br>    &quot;typescript&quot;: &quot;^5.9.2&quot;<br>  }<br>}</pre><p>Run the build script</p><pre>npm run build</pre><p>This generates a <strong>dist/</strong> folder with compiled outputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0O4SYEFl6z5K3vBwRbXmQA.png" /><figcaption>npm package dist folder screenshot by ukpai chukwuemeka</figcaption></figure><p>Update your package.json again to include entry path for our package and also add your lint script.</p><pre>{<br>  &quot;name&quot;: &quot;buw-string-utils&quot;,<br>  &quot;version&quot;: &quot;0.0.1&quot;,<br>  &quot;main&quot;: &quot;dist/index.js&quot;,<br>  &quot;module&quot;: &quot;dist/index.mjs&quot;,<br>  &quot;types&quot;: &quot;dist/index.d.ts&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;build&quot;: &quot;tsup index.ts --format cjs,esm --dts&quot;,<br>    &quot;lint&quot;: &quot;tsc&quot;,<br>     ...<br>  },<br> ....<br>}</pre><p>Add and commit your changes</p><pre>git add .<br>git commit -m&quot;chore: add build script and entry points&quot;</pre><h3>Step 4. Versioning with @changesets/cli</h3><p>To handle versioning we can use a cli package called @changesets/cli.</p><pre>npm i --save-dev @changesets/cli<br><br>npx changeset init</pre><p>This adds a <strong>.changeset</strong> folder with a config and markdown file containing more information on changeset.</p><p>Now, whenever you want to bump the version of your package, you can create a changeset:</p><pre>npx changeset</pre><p>You are to choose the type (patch, minor, major) and a markdown file will be created in .changeset/ containing more information of the changes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ugFutDhl-sUZrSBqQ-NjCA.png" /><figcaption>npx changeset screenshot by ukpai chukwuemeka</figcaption></figure><blockquote>In this article, we won’t go deep into versioning versioning but here is a diagram explaining the parts of a version number &lt;x.y.z&gt;</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y1w6Add6rsBCme2n1N6GOw.png" /><figcaption>photo credit google</figcaption></figure><h3>Step 5. Testing with Jest</h3><pre>npm i --save-dev jest ts-jest @jest/globals<br>npx ts-jest config:init</pre><p>Update your package.json:</p><pre>&quot;scripts&quot;: {<br>  &quot;test&quot;: &quot;NODE_OPTIONS=--experimental-vm-modules jest&quot;<br>}</pre><p>Create index.test.ts:</p><pre># index.test.ts<br><br>import { capitalize, reverse } from &quot;./index&quot;;<br>import { describe, it, expect } from &quot;@jest/globals&quot;;<br><br>describe(&quot;capitalize&quot;, () =&gt; {<br>  it(&quot;capitalizes the first letter of a string&quot;, () =&gt; {<br>    expect(capitalize(&quot;hello&quot;)).toBe(&quot;Hello&quot;);<br>    expect(capitalize(&quot;world&quot;)).toBe(&quot;World&quot;);<br>    expect(capitalize(&quot;javaScript&quot;)).toBe(&quot;JavaScript&quot;);<br>  });<br>});<br><br>describe(&quot;reverse&quot;, () =&gt; {<br>  it(&quot;reverses a string&quot;, () =&gt; {<br>    expect(reverse(&quot;hello&quot;)).toBe(&quot;olleh&quot;);<br>    expect(reverse(&quot;world&quot;)).toBe(&quot;dlrow&quot;);<br>  });<br>}); <br></pre><p>Run tests:</p><pre>npm run test</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t5aiM-rFI8sbkJLyK__v-A.png" /><figcaption>npm run test screenshoot by ukpai chukwuemeka</figcaption></figure><h3>Step 6. Automate Publishing with GitHub Actions</h3><p>You want to create GitHub workflows , so you would not have to manually bump your package version.</p><pre>mkdir -p .github/workflows<br>touch .github/workflows/ci.yml<br>touch .github/workflows/publish.yml</pre><p><strong>main.yml</strong></p><pre>name: CI<br>on:<br>  push:<br>    branches:<br>      - &quot;**&quot;<br><br>jobs:<br>  build:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v3<br>      <br>      - uses: actions/setup-node@v3<br>        with:<br>          node-version: 20.x   # updated from 16.x<br>          cache: &quot;npm&quot;<br><br>      - run: npm install<br>      - run: npm run lint<br>      - run: npm test<br>      - run: npm run build</pre><p><strong>publish.yml</strong></p><pre>name: Publish<br>on:<br>  workflow_run:<br>    workflows: [CI]<br>    branches: [main]<br>    types: [completed]<br><br>concurrency: ${{ github.workflow }}-${{ github.ref }}<br><br>permissions:<br>  contents: write<br>  pull-requests: write<br><br>jobs:<br>  publish:<br>    if: ${{ github.event.workflow_run.conclusion == &#39;success&#39; }}<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Checkout repository<br>        uses: actions/checkout@v4<br>        with:<br>          fetch-depth: 0<br><br>      - uses: actions/setup-node@v3<br>        with:<br>          node-version: 20.x   # upgraded from 16.x<br>          cache: &quot;npm&quot;<br><br>      - run: npm install<br><br>      # Run version bump + changelog directly instead of PR<br>      - name: Version and Changelog<br>        id: version<br>        run: |<br>          npx changeset version<br>          VERSION=$(node -p &quot;require(&#39;./package.json&#39;).version&quot;)<br>          echo &quot;version=$VERSION&quot; &gt;&gt; $GITHUB_OUTPUT<br>          git config user.name &quot;github-actions[bot]&quot;<br>          git config user.email &quot;github-actions[bot]@users.noreply.github.com&quot;<br>          git add .<br>          git commit -m &quot;chore(release): v$VERSION&quot; || echo &quot;No changes to commit&quot;<br>          git push origin main<br><br>      - name: Configure npm auth<br>        run: echo &quot;//registry.npmjs.org/:_authToken=${NPM_TOKEN}&quot; &gt; ~/.npmrc<br>        env:<br>          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}<br><br>      - name: Publish to npm<br>        run: npm run release<br>        env:<br>          GITHUB_TOKEN: ${{ secrets.GIT_TOKEN }}<br>          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}<br><br>      - name: Create GitHub Release<br>        uses: ncipollo/release-action@v1<br>        with:<br>          tag: v${{ steps.version.outputs.version }}<br>          name: v${{ steps.version.outputs.version }}<br>          bodyFile: CHANGELOG.md<br>        env:<br>          GITHUB_TOKEN: ${{ secrets.GIT_TOKEN }}</pre><h4>In package.json, add:</h4><pre>&quot;scripts&quot;: {<br>  &quot;release&quot;: &quot;npm run build &amp;&amp; changeset publish&quot;<br>}</pre><p>From now on, GitHub Actions will handle building, versioning, and publishing automatically whenever you merge to <strong>main</strong>.</p><p>Congratulations you just created your first npm package.</p><h3>Testing Your Package Locally</h3><p>To test your package locally we are going to use this command npm link.</p><p>This is one of those handy commands that make developing and testing your package locally much smoother before publishing.</p><p>Inside your package folder <strong>bwu-string-utils/</strong>:</p><pre><br>npm run build<br>npm link</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7NZ5LeaepdNzCIq2Ejksxw.png" /><figcaption>npm link screenshot by ukpai chukwuemeka</figcaption></figure><p>Now create a new folder to test it:</p><pre>mkdir test-bwu-string-utils<br>cd test-bwu-string-utils<br>npm init -y<br>touch index.js<br>npm link bwu-string-utils</pre><p>Then edit <strong>index.js</strong>:</p><pre>const {capitalize,reverse} = require(&#39;buw-string-utils&#39;)<br><br><br>console.log(capitalize(&#39;hello world&#39;))  // Output: &#39;Hello world&#39;<br>console.log(reverse(&#39;hello world&#39;))     // Output: &#39;dlrow olleh&#39;</pre><h3>Publishing to GitHub and npm</h3><p>To push your package, you need to:</p><ul><li>Create a <strong>GitHub repository.</strong></li><li>Generate a <strong>GitHub token</strong>.</li><li>Generate an <strong>npm token</strong>.</li></ul><p>Once you’ve created these tokens, add them as <strong>GitHub secrets</strong> in your repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OToTl2J6gtnCPp4s-cVGUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*snjhBAnDVfBPn6cckE7seQ.png" /><figcaption>Github environment secret screenshot by ukpai chukwuemeka</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iXpD1tWvb_HGFquVjPEDHw.png" /><figcaption>actions secrets screenshot by ukpai chukwuemeka</figcaption></figure><p>With the tokens in place, every merge or pull request into <strong>main</strong> will automatically publish your package to npm.</p><p>⚡ Remember always run <strong>npx changeset</strong> to bump your version and update the changelog before pushing to main.</p><p>Cheers !</p><p>Happy package building 🚀</p><p><a href="https://docs.npmjs.com/creating-and-viewing-access-tokens">Creating and viewing access tokens | npm Docs</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F0C-B6bFuQYU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D0C-B6bFuQYU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F0C-B6bFuQYU%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/627f9fdc3e9faf74223040786149cc10/href">https://medium.com/media/627f9fdc3e9faf74223040786149cc10/href</a></iframe><p><a href="https://www.npmjs.com/package/buw-string-utils">buw-string-utils</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=217b44a87671" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing React Native Applications: Best practices and Frameworks]]></title>
            <link>https://medium.com/pen-with-paper/testing-react-native-applications-best-practices-and-frameworks-d0c44dca78e7?source=rss-8aebf678c904------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0c44dca78e7</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[UKPAI Chukwuemeka]]></dc:creator>
            <pubDate>Sat, 23 Aug 2025 16:07:22 GMT</pubDate>
            <atom:updated>2025-08-26T06:56:52.667Z</atom:updated>
            <content:encoded><![CDATA[<h4>Bet developers at Facebook don’t write test ?</h4><p><strong><em>Not a member ? </em></strong><a href="https://dev.to/aimes/testing-react-native-applications-best-practices-and-frameworks-5hca"><strong><em>Read for free</em></strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*GXBivCxUkJXbSTQ0Er14_Q.jpeg" /><figcaption>Photo by Simonkr | Credit: Getty Images</figcaption></figure><p>Testing is a habit — one that not every developer possesses.</p><p>Imagine driving through a busy intersection with no traffic lights.</p><p>Chaos, right ?</p><p>That’s exactly what software without testing feels like.</p><p>Testing is an integral part of software development.</p><p>For React Native applications, it ensures your features work as expected — and continue to do so as your app grows. <br> <br>Yet many developers skip tests because <em>“it works on my machine”</em> or due to tight deadlines.</p><p>Just like you go to the gym to stay fit, testing keeps your codebase healthy.</p><p>I’ll admit, I have written my fair share of tests and then stopped.</p><p>Until I realized that many of the bugs I kept missing were the direct result of extending functionality and refactoring without proper test coverage.</p><p>Those hidden bugs eventually slipped into production.</p><p>In this article, we’ll explore <strong>testing strategies, best practices, coverage, and frameworks</strong> you can use to catch bugs before they ever reach production.</p><h3>Why Testing Matters</h3><p>Every app has moving parts — logic, APIs, components, and user flows. Without automated tests, changes can unintentionally break those parts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tGkebH27npbyTmCV9BwwNw.png" /><figcaption>Photo by Ukpai Chukwuemeka</figcaption></figure><p>A good test suite helps you:</p><ul><li><strong>Prevent regressions.</strong></li><li><strong>Document expected behavior.</strong></li><li><strong>Increase confidence when refactoring.</strong></li><li><strong>Ship features faster and safer.</strong></li></ul><h3>Testing Frameworks for React Native</h3><p>There are several testing tools commonly used in react native applications, including:</p><p><strong>Jest</strong></p><ul><li>The default testing framework in React Native.</li><li>Fast, supports mocking, and integrates with libraries like react-test-renderer and @testing-library/react-native.</li><li>Great for unit and integration tests.</li></ul><h4><strong>React Native Testing Library (RNTL)</strong></h4><ul><li>A library built on top of @testing-library.</li><li>Encourages testing components the way users interact with them (via text, roles, and accessibility labels).</li><li>Example: getByText(&quot;Submit&quot;) instead of checking internal props.</li></ul><h4><strong>Detox</strong></h4><ul><li>A powerful E2E testing framework for React Native.</li><li>Automates user flows on real devices or emulators.</li><li>Ensures your app behaves correctly in real-world scenarios.</li></ul><h4><strong>Cypress (for Web/Expo Web)</strong></h4><ul><li>If your React Native project also targets web via Expo, Cypress is a great choice for browser-based E2E testing.</li></ul><h3>Test Coverage</h3><p>Coverage helps track which parts of your code are tested. Common metrics include:</p><ul><li><strong>Statements</strong> — how many statements in the code are executed.</li><li><strong>Branches</strong> — whether conditional paths (if, switch, ternary) are tested.</li><li><strong>Functions</strong> — coverage of function calls.</li><li><strong>Lines</strong> — percentage of lines run during tests.</li></ul><h3>Best Practices for Testing React Native</h3><p>Whether it’s <strong>unit tests</strong>, <strong>integration tests</strong>, or <strong>E2E tests</strong>, almost every testing framework follows this <strong>Arrange → Act → Assert (AAA)</strong> pattern.</p><p>You should also make more obvious what the SUT (subject under test) is.</p><h4>Example: AAA in Action</h4><pre>import React from &quot;react&quot;;<br>import { render, fireEvent } from &quot;@testing-library/react-native&quot;;<br>import { Button, Text } from &quot;react-native&quot;;<br><br>function GreetingButton() {<br>  const [message, setMessage] = React.useState(&quot;&quot;);<br>  return (<br>    &lt;&gt;<br>      &lt;Button title=&quot;Say Hello&quot; onPress={() =&gt; setMessage(&quot;Hello, World!&quot;)} /&gt;<br>      &lt;Text&gt;{message}&lt;/Text&gt;<br>    &lt;/&gt;<br>  );<br>}<br><br>test(&quot;it shows greeting after button press&quot;, () =&gt; {<br>  // Arrange<br>  const { getByText } = render(&lt;GreetingButton /&gt;);<br><br>  // Act<br>  fireEvent.press(getByText(&quot;Say Hello&quot;));<br><br>  // Assert<br>  expect(getByText(&quot;Hello, World!&quot;)).toBeTruthy();<br>});</pre><h3>Best Practices</h3><ul><li><strong>Test behavior, not implementation</strong><br>Focus on <strong>what the user sees and does</strong>, rather than the internal details of your component. This makes tests more robust and less prone to breaking when you refactor code.</li><li><strong>Keep tests fast</strong><br>Unit tests should execute quickly to encourage frequent running. Slow tests discourage developers from running them regularly.</li><li><strong>Mock external dependencies</strong><br>APIs, AsyncStorage, native modules, and other side-effect-prone dependencies should be mocked. This prevents flaky tests and ensures your tests run reliably.</li><li><strong>Use CI/CD pipelines</strong><br>Automate your tests using tools like <strong>GitHub Actions, Bitrise, or CircleCI</strong>. This ensures regressions are caught before code is merged.</li><li><strong>Don’t chase 100% coverage blindly</strong><br>Focus on <strong>critical paths and meaningful coverage</strong> rather than trying to hit 100% line coverage. High coverage doesn’t always mean high-quality tests.</li><li><strong>Use snapshots wisely</strong><br>Snapshots are useful for catching unintended changes in UI, but avoid overusing them for implementation details. Also update snapshots intentionally when UI changes are expected.</li><li><strong>Use Husky (optional)</strong><br>Husky can enforce <strong>pre-commit hooks</strong> to run tests or linting before commits. This is helpful, but optional — only adopt it if your team finds it useful.</li></ul><p><a href="https://medium.com/@ukpai/pre-deployment-checklist-setting-up-husky-1f38310e9598">Pre-deployment Checklist: Setting up Husky 🐶</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sNT7ws_hdcaszuwsFSmgyw.png" /></figure><h3>React Native Test Setup</h3><p>If you would like to start testing a new or an existing react native app.</p><p>It’s very easy</p><p>Plus any of the popular frameworks (like Jest for unit testing or Detox for end-to-end testing) can be integrated seamlessly.</p><h4>How To Create a New React Native Project</h4><p>To create a new project, you can use the official React Native Community CLI:</p><pre>npx @react-native-community/cli init rntesting </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wS-d4_rJ1QykqyRtM_NLSQ.png" /><figcaption>How to create a new react native project by Ukpai Chukwemeka</figcaption></figure><p>Once the setup is complete, open the newly created folder in your favorite IDE (such as VS Code) and you’re ready to start adding tests.</p><p>By default, projects created with the Community CLI come with <strong>Jest preinstalled and configured</strong>, so you can immediately run tests with:</p><pre>npm run test<br>yarn run test</pre><p>Let’s update a few things to help us write and run our test.</p><pre>    &quot;test:nowatch&quot;: &quot;jest --watchAll=false&quot;,<br>    &quot;test:coverage&quot;: &quot;jest --coverage --watchAll=false&quot;,<br>    &quot;test:update:snapshot&quot;: &quot;npm test -- -u&quot;</pre><p>We would update our <em>jest.config.js</em></p><pre>module.exports = {<br>  preset: &#39;react-native&#39;, // use the react-native preset<br>  transformIgnorePatterns: [<br>    &#39;node_modules/(?!(@react-native|react-native|react-native-reanimated|react-native-image-picker)/)&#39;, // add any other packages that need to be transformed<br>  ],<br>  setupFiles: [<br>    &#39;./jestSetup.js&#39;, // your custom setup file<br>  ],<br>  moduleNameMapper: {<br>    &#39;\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$&#39;:<br>      &#39;jest-transform-stub&#39;, // mock static assets<br>  },<br>  fakeTimers: {<br>    enableGlobally: true, // use fake timers for all tests<br>  },<br>  collectCoverageFrom: [<br>    &#39;src/**/*.{js,jsx,ts,tsx}&#39;, // your source files<br>    &#39;!src/assets/**&#39;, // exclude assets<br>    &#39;!src/**/*.d.ts&#39;, // exclude types<br>    &#39;!src/**/index.{js,ts,tsx}&#39;, // exclude barrel index files<br>  ],<br>  testMatch: [<br>    &#39;**/__tests__/**/*.{js,jsx,ts,tsx}&#39;, // look for tests in __tests__<br>    &#39;**/?(*.)+(spec|test).{js,jsx,ts,tsx}&#39;, // or files ending in .test/.spec<br>  ],<br>  collectCoverage: true, // enable coverage collection<br>  coverageThreshold: {<br>    // set coverage thresholds<br>    global: {<br>      branches: 100, // set to 100% or your desired threshold<br>      functions: 100, // set to 100% or your desired threshold<br>      lines: 100, // set to 100% or your desired threshold<br>      statements: 100, // set to 100% or your desired threshold<br>    },<br>  },<br>};</pre><p>Now the next time you run coverage you should be able to see your code coverage and a coverage folder would be generated.</p><pre>npm run test:coverage</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*uZb4Yf8lk_KjCQq_NHBoqA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1gUIZ79IZmrWbtDaX4RkAw.png" /></figure><p>To view the report in your browser open up the <strong>index.html</strong> file under <strong>rntesting/coverage/lcov-report/index.html .</strong></p><p><strong>Github Link:</strong></p><p><a href="https://github.com/Mr-emeka/rntesting/tree/AAA-with-testing-library/react-native-react-test-renderer">GitHub - Mr-emeka/rntesting at AAA-with-testing-library/react-native-react-test-renderer</a></p><h3>Conclusion</h3><p>We all dream of the fancy job with good pay but the harsh reality you are not ready to write test :).</p><p>Likewise teams that invest in tests build software that lasts.</p><p><strong>Do you want to practice?</strong></p><p>You can <a href="https://github.com/Mr-emeka/rntesting"><strong>fork the repo, experiment, and add your own test cases</strong></a>. Let’s help each other write better, more reliable apps !</p><p><strong>Cheers and happy testing!</strong></p><ul><li><a href="https://medium.com/pen-with-paper/windows-android-development-setup-2025-e6ba0b94eddf">Windows Android Development Setup — 2025</a></li><li><a href="https://reactnative.dev/docs/getting-started-without-a-framework">Get Started Without a Framework · React Native</a></li><li><a href="https://testing-library.com/docs/react-native-testing-library/intro">Introduction | Testing Library</a></li></ul><p><em>This story published on “</em><a href="https://medium.com/pen-with-paper"><strong><em>Pen With Paper</em></strong></a><strong><em>”</em></strong><em> — a fresh space where writers bring their thoughts, stories, and ideas to life. </em><strong><em>Want to share your voice? </em></strong><em>Join our community, and together, “</em><strong><em>We Elevate Your Stories”</em></strong></p><p><a href="https://medium.com/pen-with-paper/welcome-to-pen-with-paper-a-publication-f2d3782240f9">Welcome to ‘Pen With Paper’ — A Publication</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0c44dca78e7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pen-with-paper/testing-react-native-applications-best-practices-and-frameworks-d0c44dca78e7">Testing React Native Applications: Best practices and Frameworks</a> was originally published in <a href="https://medium.com/pen-with-paper">Pen With Paper</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Windows Android Development Setup — 2025]]></title>
            <link>https://medium.com/pen-with-paper/windows-android-development-setup-2025-e6ba0b94eddf?source=rss-8aebf678c904------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6ba0b94eddf</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[UKPAI Chukwuemeka]]></dc:creator>
            <pubDate>Tue, 24 Jun 2025 15:55:47 GMT</pubDate>
            <atom:updated>2025-06-24T15:55:47.901Z</atom:updated>
            <content:encoded><![CDATA[<h3>Windows Android Development Setup — 2025</h3><h4>Quite recently, I experienced one of the worst nightmares anyone who depends on their tools can go through — losing them.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5EdWYpQLk0-aonwn" /><figcaption>Photo by <a href="https://unsplash.com/@redaquamedia?utm_source=medium&amp;utm_medium=referral">Denny Müller</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>For a doctor, it might be a stethoscope.</p><p>For a farmer, a tractor.</p><p>For me — it was my MacBook.</p><p>It all started a few months back.</p><p>While working, water meant for drinking accidentally got into my MacBook.</p><p>At first, it seemed fine — no issues right away.</p><p>But deep down, I knew it was only a matter of time</p><p>I had already made plans to replace it.</p><p>But the new machine was still weeks away from arriving</p><p>In the meantime, I needed a temporary setup — I couldn’t afford to lose my job.</p><p>So, in search of a quick solution, I reached out to a few friends, asking if anyone had a spare laptop I could borrow.</p><p>I wasn’t just looking for convenience — I was trying to stay afloat.</p><p>Deadlines didn’t care that my machine was fried.</p><p>Fortunately, a friend lent me a <strong>Windows laptop</strong>.</p><p>But this introduced a new challenge:</p><p><em>I had to configure a Windows environment for mobile development (specifically Android).</em></p><p>Here’s a breakdown of how I did it and the issues I encountered along the way.</p><h3>Step-by-Step Windows Setup for Android Development</h3><h4>1. Install Development Essentials</h4><p>I started by downloading and installing the following tools:</p><ul><li><a href="http://coreybutler/nvm-windows"><strong>NVM for Windows</strong></a>: To manage Node.js versions easily</li><li><a href="https://www.cursor.com/"><strong>Cursor</strong> </a>(AI-powered code editor): As an alternative to VS Code</li><li><a href="https://git-scm.com/downloads"><strong>Git</strong>:</a> For version control and cloning repositories</li><li><a href="https://developer.android.com/studio"><strong>Android Studio</strong></a>: The official IDE for Android development</li><li><a href="https://www.oracle.com/java/technologies/downloads/#java8"><strong>JDK</strong> </a>(Java Development Kit): Required by Android Studio and Gradle</li></ul><h3>2. Android Studio Setup</h3><p>Once Android Studio was installed I went ahead to install android sdks and platform tools</p><ul><li>CMAKE</li><li>NDK (side by side)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*em_PKJ3Xrz2gyhO1Wn0I9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bZr_Z755ipr7d4KNdkg5xg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y8yoyaFxsegHI-_eSjkqBQ.png" /></figure><h3>3. Environment Variables</h3><p>To make sure commands run correctly in any terminal, I added the necessary environment variables. You can find this by pressing [Win], searching <em>Env</em>, and editing them under System Properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0E9_F4O-Io8H-Kl-26yWqg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*afNvZr95NSuGRmEMcxxzEA.png" /></figure><p><strong>JAVA_HOME</strong></p><p><strong>Setting JAVA_HOME Windows</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*e48Oo9OoHFe8ZPimJ2aHnA.png" /></figure><p>Added these paths to Path:</p><ul><li>%ANDROID_HOME%\platform-tools</li><li>%ANDROID_HOME%\tools</li><li>%JAVA_HOME%\bin</li></ul><h3>Common Issue: ADB Not Recognized</h3><p>At one point, I encountered this error:</p><p><em>&#39;adb&#39; is not recognized as an internal or external command</em></p><h3>Solution:</h3><ul><li>I double-checked if platform-tools was correctly installed via the <strong>SDK Manager</strong> in Android Studio.</li><li>I then <strong>added the full path to </strong><strong>platform-tools</strong> to the Path environment variable:</li></ul><p>C:\Users\&lt;YourUsername&gt;\AppData\Local\Android\Sdk\platform-tools</p><p>Then restarted the terminal.</p><p>Now running adb devices worked successfully!</p><h3>Conclusion</h3><p>Switching from macOS to Windows for Android development wasn’t easy, especially in the middle of active work.</p><p>But with some determination and the right setup, I was able to get back on track.</p><p>This experience taught me not just technical configuration — but also resilience in the face of unexpected setbacks. If you’re facing a similar situation, I hope this guide helps you as much as the process helped me.</p><p><em>This story published on “</em><a href="https://medium.com/pen-with-paper"><strong><em>Pen With Paper</em></strong></a><strong><em>”</em></strong><em> — a fresh space where writers bring their thoughts, stories, and ideas to life. </em><strong><em>Want to share your voice? </em></strong><em>Join our community, and together, “</em><strong><em>We Elevate Your Stories”</em></strong></p><p><a href="https://medium.com/pen-with-paper/welcome-to-pen-with-paper-a-publication-f2d3782240f9">Welcome to ‘Pen With Paper’ — A Publication</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6ba0b94eddf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pen-with-paper/windows-android-development-setup-2025-e6ba0b94eddf">Windows Android Development Setup — 2025</a> was originally published in <a href="https://medium.com/pen-with-paper">Pen With Paper</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build Self-Confidence — In a Real, Practical Way, Without Hurting Anyone]]></title>
            <link>https://medium.com/pen-with-paper/how-to-build-self-confidence-in-a-real-practical-way-without-hurting-anyone-7525d51b4aa5?source=rss-8aebf678c904------2</link>
            <guid isPermaLink="false">https://medium.com/p/7525d51b4aa5</guid>
            <category><![CDATA[life]]></category>
            <category><![CDATA[writing]]></category>
            <category><![CDATA[pen-with-paper]]></category>
            <category><![CDATA[confidence]]></category>
            <category><![CDATA[self-improvement]]></category>
            <dc:creator><![CDATA[UKPAI Chukwuemeka]]></dc:creator>
            <pubDate>Fri, 30 May 2025 17:41:03 GMT</pubDate>
            <atom:updated>2025-05-30T17:41:03.986Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Build Self-Confidence — In a Real, Practical Way, Without Hurting Anyone</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*bf4wnMdlORoNJ0G3QAAazA.jpeg" /><figcaption><a href="https://polygrafi.wordpress.com/wp-content/uploads/2013/10/freedom1.jpg">https://polygrafi.wordpress.com/wp-content/uploads/2013/10/freedom1.jpg</a></figcaption></figure><p>Self-confidence isn’t something you’re born with — it’s a skill.</p><p>And like any skill, it can be developed over time.</p><p>Even if you can’t imagine being confident right now, I want you to pause and tell yourself: it’s possible.</p><p>But here’s something most people don’t talk about enough—sometimes, in trying to become confident, we end up stepping on others.</p><p>We silence friends, neglect family, or put people down just to feel stronger.</p><p>And that kind of confidence? It doesn’t last. It’s a mask, not a mindset.</p><p>I know this because I’ve been there.</p><p>I know what it’s like to have no confidence at all.</p><p>To feel invisible. To walk into a room and question whether you even deserve to be there.</p><p>I used to second-guess everything—what I said, how I looked, what I did. Nothing ever felt right.</p><p>Got to a point where I tied my sense of worth to whether someone wanted me.</p><p>I got into relationships not because I was in love, but because I wanted to feel wanted.</p><p>With the believe that being chosen meant I mattered. But all it ever did was leave me emptier.</p><p>I’d end things or they’d fall apart, and I’d be right back where I started—still unsure of who I was.</p><p>I didn’t realize it at the time, but I was trying to fill a void inside me with things from the outside. Attention, validation, compliments—they gave me short bursts of energy, but never anything lasting.</p><p>In chasing those feelings, I ended up hurting people.</p><p>People who genuinely cared about me. I mistook their kindness for approval and ignored the deeper connection in favor of surface-level validation.</p><p>It wasn’t intentional, but the damage was real.</p><p>College didn’t make things easier. In my first year, I was broke. I could barely afford accommodation, food, or school supplies.</p><p>I rotated the same clothes to class—not because I didn’t care about how I looked, but because I had no choice. At the time, I wasn’t even counting. I was just trying to survive.</p><p>Then one day, My coursemates did the whole anonymous message.</p><p>It made fun of the fact that I wore the same outfit over and over again.</p><p>They didn’t know what I was going through. They didn’t ask. They just mocked me from a distance.</p><p>And still, I was lucky compared to some people because they had it worse.</p><p>They were labeled, ridiculed, reduced to jokes.</p><p>I didn’t escape the embarrassment entirely, but I learned something important:</p><p><strong><em>Confidence isn’t about what you wear or how much you have. It’s about continuing to show up even when you feel like you have nothing. It’s standing in your truth, even when that truth isn’t glamorous.</em></strong></p><p>Eventually, I started making some money. It wasn’t a lot, but it was enough to buy clothes, eat better, and even support my family a bit.</p><p>I thought I’d finally made it. For a while, I believed money had solved my confidence issues. I felt more secure, more respected, more seen.</p><p>But after the initial thrill wore off, I realized something else—money didn’t change how I felt about myself.</p><p>Sure, it gave me temporary comfort, but the moment it slowed down or things got tight again, all my insecurities came rushing back.</p><p>That’s when it really hit me: confidence built on external things—money, appearance, status—will always be shaky. It doesn’t take much for it to fall apart.</p><p>The truth is, my confidence was so low that I apologized for simply existing.</p><p>I’d say sorry when someone else tripped. I’d say sorry when it rained. I was constantly shrinking myself, trying not to inconvenience anyone, trying not to be too much.</p><p>I’ll never forget the day a friend stopped me mid-apology and said, “Why are you saying sorry? I didn’t fall.”</p><p>It sounds small, but in that moment, I realized how automatic it had become for me to ignore myself just to keep others comfortable.</p><p>He wasn’t just calling me out — He was holding up a mirror, showing me that I didn’t have to shrink to be accepted.</p><p>One of the hardest lessons came with my first real opportunity in tech.</p><p>A friend’s dad ran a consulting firm and needed a website.</p><p>I was excited — it felt like the break I’d been waiting for.</p><p>But because of my lack of confidence, I didn’t ask questions. I didn’t negotiate. I didn’t set expectations. I just said yes and hoped for the best.</p><p>I worked hard, met deadlines, gave it my all. And in the end?</p><p>I got crumbs. Not just financially, but in how I was treated. It wasn’t about the money — it was about what I believed I was worth. And at the time, that wasn’t much.</p><p>Unfortunately, that wasn’t the only time I found myself in that position.</p><p>I’ve had moments where I was struggling — truly struggling — but couldn’t ask for help.</p><p>Not because help wasn’t available, but because I didn’t feel worthy of it. I was dying in silence because I didn’t have the courage to speak up.</p><p>So how do you build real, sustainable confidence — the kind that doesn’t need to hurt anyone, the kind that doesn’t crumble when life gets hard?</p><p>For me, it started with acknowledging the fears I tried to avoid.</p><p>I had to admit what scared me: rejection, failure, not being enough.</p><p>And then, I had to take small steps in the direction of those fears.</p><p>Speaking up even when I felt shaky. Saying no even when I feared it would upset someone. Setting boundaries even when it felt unnatural.</p><p>I learned to celebrate small wins — each time I honored myself, I became a little stronger.</p><p>I stopped comparing myself to others. I reminded myself that other people succeeding didn’t mean I was failing.</p><p>And most of all, I learned not to step on others to feel taller.</p><p>That kind of confidence is built on insecurity. Real strength is quiet. It doesn’t need to scream or belittle or dominate. It simply is.</p><p>I’m still learning. I still have days when I feel small.</p><p>But I’ve stopped trying to fix that by pretending to be big. Instead, I remind myself that being grounded, kind, and honest is enough.</p><p>Confidence isn’t about walking into a room and thinking you’re better than everyone.</p><p>It’s walking in and knowing you’re enough — just as you are. And when you believe that, you don’t need to hurt anyone to feel good about yourself.</p><p>You just show up. Fully. Authentically. And that’s more than enough.</p><p><em>This story published on “</em><a href="https://medium.com/pen-with-paper"><strong><em>Pen With Paper</em></strong></a><strong><em>”</em></strong><em> — a fresh space where writers bring their thoughts, stories, and ideas to life. </em><strong><em>Want to share your voice? </em></strong><em>Join our community, and together, “</em><strong><em>We Elevate Your Stories”</em></strong></p><p><a href="https://medium.com/pen-with-paper/welcome-to-pen-with-paper-a-publication-f2d3782240f9">Welcome to ‘Pen With Paper’ — A Publication</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7525d51b4aa5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pen-with-paper/how-to-build-self-confidence-in-a-real-practical-way-without-hurting-anyone-7525d51b4aa5">How to Build Self-Confidence — In a Real, Practical Way, Without Hurting Anyone</a> was originally published in <a href="https://medium.com/pen-with-paper">Pen With Paper</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Rate Limiting]]></title>
            <link>https://medium.com/@ukpai/api-rate-limiting-96357c2a7b3b?source=rss-8aebf678c904------2</link>
            <guid isPermaLink="false">https://medium.com/p/96357c2a7b3b</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[UKPAI Chukwuemeka]]></dc:creator>
            <pubDate>Thu, 27 Mar 2025 14:26:01 GMT</pubDate>
            <atom:updated>2025-03-27T14:26:01.595Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BO7KJeXVDzgVmTahqN3q0A.png" /></figure><blockquote>API rate limiting is a technique used to control the rate at which requests are made to a network, server, or other resource.</blockquote><h3>Why Should I Rate Limit an API ?</h3><p>Imagine a scenario where a malicious actor or an unintentional client overloads your API by sending thousands of requests per second. If your server can’t handle the load, it may crash, resulting in downtime and a poor user experience.</p><p>This type of attack is known as a <strong>Denial-of-Service (DoS) attack</strong>.</p><p>Rate limiting helps mitigate such risks by preventing excessive or abusive use of a resource, ensuring that the resource is available to all users.</p><p>In this guide, I’ll show you how to implement rate limiting in a <strong>NestJS</strong> application.</p><h3>Rate Limiting in NestJS</h3><p>NestJS provides built-in support for rate limiting through the @nestjs/throttler package.</p><h4>Using ThrottlerModule in NestJS</h4><p>ThrottlerModule is the official rate-limiting solution for NestJS and works well with both HTTP-based APIs and WebSockets.</p><h4>Installation</h4><p>To use the throttler package, install it with:</p><pre>npm install @nestjs/throttler</pre><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { ThrottlerModule } from &#39;@nestjs/throttler&#39;;<br><br>@Module({<br>  imports: [<br>    ThrottlerModule.forRoot({<br>      ttl: 60, // Time to live (in seconds)<br>      limit: 10, // Maximum 10 requests per minute<br>    }),<br>  ],<br>})<br>export class AppModule {}</pre><h4>Applying Rate Limiting to Specific Routes</h4><p>You can use the @Throttle() decorator on specific controllers or routes.</p><pre>import { Controller, Get } from &#39;@nestjs/common&#39;;<br>import { Throttle } from &#39;@nestjs/throttler&#39;;<br><br>@Controller(&#39;users&#39;)<br>export class UsersController {<br>  @Get()<br>  @Throttle(5, 30) // Max 5 requests per 30 seconds<br>  getUsers() {<br>    return { message: &#39;This route is rate-limited&#39; };<br>  }<br>}</pre><h3>Using express-rate-limit in a NestJS Application</h3><p>If you’re using NestJS with Express (instead of Fastify), you can use express-rate-limit.</p><h4>Installation</h4><pre>npm install express-rate-limit</pre><h4>Applying Rate Limiting in main.ts</h4><pre>import * as rateLimit from &#39;express-rate-limit&#39;;<br>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br><br>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br><br>  app.use(<br>    rateLimit({<br>      windowMs: 60 * 1000, // 1 minute<br>      max: 100, // Limit each IP to 100 requests per minute<br>      message: &#39;Too many requests, please try again later.&#39;,<br>    })<br>  );<br><br>  await app.listen(3000);<br>}<br>bootstrap();</pre><h4><strong>Importance of Rate Limiting</strong></h4><ul><li>Rate limiting is an essential security mechanism for protecting your APIs from abuse and preventing server overload.</li><li>Implementing rate limiting ensures fair usage and improves API reliability.</li></ul><blockquote>You can read more on Rate Limiting <a href="https://medium.com/@bijit211987/everything-you-need-to-know-about-rate-limiting-for-apis-f236d2adcfff">https://medium.com/@bijit211987/everything-you-need-to-know-about-rate-limiting-for-apis-f236d2adcfff</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96357c2a7b3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building and Signing Apps Made Easy: React Native and EAS]]></title>
            <link>https://medium.com/@ukpai/building-and-signing-apps-made-easy-react-native-and-eas-0ac620aa648c?source=rss-8aebf678c904------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ac620aa648c</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[expo]]></category>
            <category><![CDATA[ea]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[UKPAI Chukwuemeka]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 09:02:05 GMT</pubDate>
            <atom:updated>2025-02-03T09:02:05.449Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sXnmH8kl6GsY7ebIK4yFmA.png" /></figure><p>Building and signing apps directly on your hardware can be problematic and a frustrating experience.</p><p>For many developers, it’s either limited hardware specs or the lack of an Apple MacBook can make building iOS apps feel like an impossible task.</p><p>I have firsthand seen aspiring mobile developers give up on their dreams for these very reasons — and honestly, it’s heartbreaking. But here’s the good news: it doesn’t have to be that way.</p><p>In this article, I’ll share the cloud service I rely on for both work and personal projects as a senior mobile engineer. It has simplified my workflow, eliminated the need for high-end hardware, and made building and deploying apps easy.</p><p>Whether you’re an aspiring developer or an experienced professional, there’s something here for everyone to learn.</p><p>The service? <strong>Expo Application Services (EAS)</strong>.</p><h4>Does EAS work with React Native?</h4><p>If you were asked this question in an interview and this question happens to be your gate way to getting the job what would be your response ?</p><p>If your response was No, I am sorry to inform you the job is no longer available :).</p><h4>The correct answer is</h4><p><strong>Yes, Expo Application Services (EAS) works with React Native.</strong> In fact, you can also say it was specifically built for React Native.</p><p>EAS is designed for developers who want to streamline app development, updates, and collaboration workflows with a cloud service tailored for React Native and Expo.</p><p>You can set up your app for distribution in minutes, including support for <strong>internal distribution</strong>. This feature allows you to share test builds with colleagues and friends without going through an app store by using <a href="https://expo.canny.io/feature-requests/p/iosbuild-with-adhoc-provision-profile">ad hoc provisioning</a> on iOS and standard APK side-loading on Android.</p><h3>Key Features That Make EAS Perfect for React Native:</h3><ol><li><strong>EAS Build:</strong> Allows you to build apps for iOS and Android in the cloud, removing the need for high-end hardware or an Apple MacBook.</li><li><strong>EAS Submit:</strong> Simplifies the app submission process to the Apple App Store or Google Play Store.</li><li><strong>EAS Update:</strong> Enables over-the-air updates, letting you deliver changes to your app without waiting for store approvals.</li><li><strong>EAS Hosting: </strong>A service currently in preview, designed to simplify the deployment of web projects built using Expo Router and React Native for web. This service allows developers to quickly deploy web applications, including API routes and server functions, directly through EAS hosting.</li><li><strong>Seamless Integration:</strong> Works with both managed and bare React Native workflows, making it flexible for different project setups.</li></ol><h3>Getting Started with EAS</h3><p>To follow along, you’ll need:</p><ul><li>A basic understanding of<a href="https://reactnative.dev/docs/environment-setup"> React Native</a>.</li><li><a href="https://nodejs.org/en/download/current">Node.js</a> and npm (or <a href="https://classic.yarnpkg.com/lang/en/docs/install/#mac-stable">yarn</a>) installed</li><li>A free <a href="https://expo.dev/signup/">EAS</a> account</li><li>A working React Native development environment (<a href="https://reactnative.dev/docs/set-up-your-environment">setup here</a>)</li></ul><h3>Initializing new React Native project</h3><pre>npx @react-native-community/cli@latest init RNEAS --pm yarn</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5krllt7433oGrxd0WER-gw.png" /></figure><p>You deserve a cold beer at this point, Next we are going to install the EAS CLI.</p><h3>Installing the EAS CLI</h3><p>Installing the EAS CLI is quick and simple:</p><pre># Install the CLI globally using yarn<br>yarn dlx eas-cli<br><br># Verify installation<br>eas whoami</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Kc8NQ14aOZbgBMFo85pjQ.png" /></figure><h3>Configuring EAS Build</h3><p>Let’s configure EAS to handle build in our newly initialized React Native Project.</p><p><strong>Set Up Your App for Building</strong></p><pre>eas build:configure</pre><p>Because you are not logged in yet, You should get a prompt to login.</p><p>Once you are logged in, you should get a new prompt to create a project go ahead and create one, Next we get another prompt asking what platforms you would like to configure EAS build for.</p><p>We want EAS to build for <strong>All</strong> platforms — both iOS and android, so go ahead and select all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8nYhpGsJN6_DK6HB5-Wn_Q.png" /><figcaption>EAS build configuring a react native project.</figcaption></figure><p>This command creates a <strong>eas.json</strong> file that holds configuration EAS service would need to build our app for different environments.</p><p>Update your <strong>eas.json</strong> file to match the config below. we are just setting up our different profiles, buildType and distribution.</p><pre>{<br>  &quot;cli&quot;: {<br>    &quot;version&quot;: &quot;&gt;= 14.2.0&quot;,<br>    &quot;appVersionSource&quot;: &quot;remote&quot;<br>  },<br>  &quot;build&quot;: {<br>    &quot;development&quot;: {<br>      &quot;developmentClient&quot;: true,<br>      &quot;distribution&quot;: &quot;internal&quot;,<br>      &quot;android&quot;: {<br>        &quot;buildType&quot;: &quot;apk&quot;<br>      }<br>    },<br>    &quot;preview&quot;: {<br>      &quot;android&quot;: {<br>        &quot;buildType&quot;: &quot;apk&quot;<br>      },<br>      &quot;distribution&quot;: &quot;internal&quot;<br>    },<br>    &quot;production&quot;: {<br>      &quot;autoIncrement&quot;: true,<br>      &quot;android&quot;: {<br>        &quot;distribution&quot;: &quot;store&quot;,<br>        &quot;image&quot;: &quot;latest&quot;,<br>        &quot;buildType&quot;: &quot;app-bundle&quot;<br>      },<br>      &quot;ios&quot;: {<br>        &quot;distribution&quot;: &quot;store&quot;<br>      }<br>    }<br>  },<br>  &quot;submit&quot;: {<br>    &quot;production&quot;: {<br>      &quot;ios&quot;: {<br>        &quot;ascAppId&quot;: &quot;ascAppID&quot;,<br>        &quot;appleTeamId&quot;: &quot;appleTeamId&quot;,<br>        &quot;appleId&quot;: &quot;appleId&quot;<br>      }<br>    }<br>  }<br>}</pre><p><strong>How to Log In and Logout Your EAS Account</strong></p><pre># login <br>eas login<br><br># logout<br>eas logout</pre><p><strong>Trigger a Build and Signing App</strong></p><p>we can go ahead and trigger a build using the command below.</p><pre>eas build --profile development --platform android</pre><p>Replace development and android with your desired profile and platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*buvMidHvU6h-BcYkOkR8lg.png" /><figcaption>EAS build command terminal process.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0tvwg5NA2MInTbaJRodCdQ.png" /><figcaption>EAS Dashboard showing the android preview build for internal distribution</figcaption></figure><h3>Submitting Your App with EAS</h3><p>Once your build is complete, submitting to app stores is easy:</p><pre>eas submit --platform [ios/android]</pre><p>It’s important to note that you can only submit production builds to the store.</p><h3>Updating Your App with EAS</h3><p>Need to push updates to your app without waiting for store approval? Use <strong>EAS Update</strong>:</p><pre>eas update</pre><h3>You can also manage environment variables securely with EAS:</h3><pre># Push development environment variables<br>eas env:push --environment=development --path=.env.development</pre><h3>Wrap-Up</h3><p>Configuring EAS is that easy! With just a few commands, you can build, test, and update your React Native apps faster than ever. Whether you’re just starting out or looking to improve your workflow, EAS is an invaluable tool in any developer’s arsenal.</p><p>📫 <strong>Stay tuned for my next post, where I’ll dive into managing EAS environments for production-ready apps.</strong></p><blockquote>PS. This article isn’t sponsored by Expo — I am only sharing the tool I use daily to make my development workflow smoother. If you have questions, ideas, or feedback, I would love to hear from you! Drop a comment or reach out.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ac620aa648c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[do not be racist to yourself]]></title>
            <link>https://medium.com/@ukpai/dont-be-racist-to-yourself-90389410cf80?source=rss-8aebf678c904------2</link>
            <guid isPermaLink="false">https://medium.com/p/90389410cf80</guid>
            <category><![CDATA[self-awareness]]></category>
            <category><![CDATA[personal-development]]></category>
            <category><![CDATA[inner-voice]]></category>
            <category><![CDATA[personal-growth]]></category>
            <category><![CDATA[reflections]]></category>
            <dc:creator><![CDATA[UKPAI Chukwuemeka]]></dc:creator>
            <pubDate>Sat, 18 Jan 2025 11:03:11 GMT</pubDate>
            <atom:updated>2025-01-19T10:54:55.510Z</atom:updated>
            <content:encoded><![CDATA[<h3>don’t be racist to yourself</h3><h4>reprogram your inner voice to stop limiting you.</h4><blockquote><strong>Read for free </strong><a href="https://dub.sh/racist"><strong>here</strong></a><strong>.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1u-bWoHFQQNzo6dnSDxO9w.jpeg" /></figure><blockquote>Let’s be real for a second. We all face external barriers — judgment, bias, societal nonsense. But honestly? The biggest roadblock isn’t “out there.” It’s inside. Yup, it’s that little voice in your head, the one that loves to whisper things like, <em>“You’re not good enough,”</em> or, <em>“Why even bother?”</em> You know the one I’m talking about.</blockquote><blockquote>Here’s the crazy part. We’re quick to call out racism or injustice when it comes from other people, right? But when it’s our <em>own</em> thoughts doing the damage, we just… let it slide. Why? Think about it. If someone else said, “You’ll never make it because of where you’re from” or “You’re not smart enough for this,” you’d be furious. So why let your inner voice get away with that kind of nonsense?</blockquote><blockquote>Listen, the color of your skin shouldn’t limit you, and neither should your mindset. Where you grew up? How much money you had (or didn’t have)? The mistakes you’ve made? None of that defines you — unless <em>you</em> let it.</blockquote><blockquote>Now, let’s talk about your life for a minute. Be honest. How much time do you spend scrolling through your phone, liking random posts, making money for people who’ve figured out the game while you sat there doubting yourself? Ouch, right? And it’s not just individuals — businesses fall into this trap, too, holding themselves back instead of going all-in.</blockquote><blockquote>But here’s the good news regrets don’t belong here, Only lessons. Think about those superstars you admire. They’re not some magical breed of humans. They made bold moves, invested in themselves, and shut down that inner critic.</blockquote><blockquote>And guess what? You’ve got that same potential. Yeah, you. Don’t let that voice in your head tell you otherwise. Success doesn’t come from being perfect — it comes from showing up, putting in the work, and believing you’re worth it.</blockquote><blockquote>So, the big question is: Are you ready to silence that voice and unlock the future that’s been waiting for you? Because trust me, it’s ready when you are.</blockquote><blockquote>Before you go, don’t forget to <strong>clap</strong> 👏 and <strong>follow.</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90389410cf80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[telegram webhook]]></title>
            <link>https://medium.com/@ukpai/telegram-webhook-981fc3b4294b?source=rss-8aebf678c904------2</link>
            <guid isPermaLink="false">https://medium.com/p/981fc3b4294b</guid>
            <category><![CDATA[webhooks]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <category><![CDATA[telegram]]></category>
            <category><![CDATA[telegram-bot]]></category>
            <dc:creator><![CDATA[UKPAI Chukwuemeka]]></dc:creator>
            <pubDate>Thu, 16 Jan 2025 09:02:09 GMT</pubDate>
            <atom:updated>2025-01-16T09:02:09.136Z</atom:updated>
            <content:encoded><![CDATA[<h3>Telegram webhook</h3><h4>why switch from polling to webhook ?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VJv54VvCzWlFGzaEuy0g8w.jpeg" /><figcaption>Photo of Telegram Bot</figcaption></figure><p>Unlike polling, which repeatedly requests updates from Telegram, webhook allow Telegram to <strong>push updates directly to your server</strong>, reducing server resource usage and improving efficiency.</p><p>In a previous article, I explained how to set up a Telegram bot using <strong>Node.js</strong>, where we implemented polling to fetch updates repeatedly. While this setup works well, <strong>webhooks </strong>are a better alternative if you’re looking to scale, even if you’re not currently experiencing rate limits, switching to webhook ensures your bot runs more efficiently and can handle increased traffic with less strain on your server.</p><h3>Key Considerations for Telegram Webhook</h3><p>When using webhook, it’s crucial to understand the following:</p><h4><strong>Allowed Ports</strong></h4><p>Telegram supports only four ports for webhooks. While the reason for this limitation is still unclear to me, it might change in the future. For now, these are the supported ports:</p><ul><li><strong>443</strong> (recommended for HTTPS)</li><li><strong>80</strong></li><li><strong>88</strong></li><li><strong>8443</strong></li></ul><p>Either of these ports must be free and accessible for the webhook to function correctly. If you don’t explicitly specify a port, the webhook will default to using port<strong> 8443</strong>.</p><h4><strong>Server Limits</strong></h4><p>Since only four ports are allowed, you cannot run more than four apps using webhook on the same server.</p><h3>Prerequisites</h3><p>Before diving into the setup, ensure you have the following:</p><ol><li><strong>Node.js Installed</strong>: Download and install Node.js from <a href="https://nodejs.org/">nodejs.org</a> if you haven’t already.</li><li><strong>Telegram Account</strong>: You’ll need a Telegram account to obtain a bot token and interact with your bot.</li><li><strong>Ngrok for HTTPS URL: </strong>Telegram requires an HTTPS endpoint for webhooks. Use <a href="https://ngrok.com/">Ngrok</a> to expose your local server to the internet.</li></ol><blockquote>You can find full code on <a href="https://dub.sh/tg-webhook">Github</a>.</blockquote><h4>Setting Up Telegram Webhook (Node.js Example)</h4><pre>const TelegramBot = require(&#39;node-telegram-bot-api&#39;);<br><br>// Replace with your bot token<br>const token = &#39;your telegram token&#39;;// checkout my article on how to get bot token from @BotFather on Telegram<br><br>const WEB_HOOK_URL = &#39;https://localhost:3000/telegram-bot-webhook&#39;; // It won&#39;t work on local host so make use of ngrok.<br><br>// Create a bot that uses webhook<br>const bot = new TelegramBot(token, { webHook: {<br>    port: 88 // 443, 80, 88, 8443 allowed ports for telegram webhook<br>} });<br><br><br>const initWebHook = async () =&gt; {<br>    const webhookInfo = await bot.getWebHookInfo();<br>    if (webhookInfo.url !== WEB_HOOK_URL) {<br>      await bot.setWebHook(WEB_HOOK_URL, {<br>        max_connections: 100,<br>      });<br>    }<br>  };<br>  <br>  initWebHook();<br><br>// Listen for any message<br>bot.on(&#39;message&#39;, (msg) =&gt; {<br>    const chatId = msg.chat.id;<br><br>    // Simple command handling<br>    if (msg.text.toLowerCase() === &#39;/start&#39;) {<br>        bot.sendMessage(chatId, &#39;Welcome! How can I assist you today?&#39;, {reply_markup: {<br>            keyboard: [[&#39;/start&#39;, &#39;/help&#39;]]<br>        }});<br>    } else if (msg.text.toLowerCase() === &#39;hello&#39;) {<br>        bot.sendMessage(chatId, `Hello, ${msg.from.first_name}!`);<br>    } else {<br>        bot.sendMessage(chatId, &quot;I&#39;m not sure how to respond to that.&quot;);<br>    }<br>});<br><br>module.exports = bot;</pre><h4>Telegram Webhook Route</h4><pre>const express = require(&quot;express&quot;);<br>const app = express();<br>const bot = require(&quot;./bot&quot;);<br><br>// parse json body  for post request<br>app.use(express.json());<br><br>app.get(&quot;/&quot;, (req, res) =&gt; {<br>  res.send(&quot;Hello World&quot;);<br>});<br><br>app.post(&quot;/telegram-bot-webhook&quot;, (req, res) =&gt; {<br>  bot.processUpdate(req.body);<br>  res.sendStatus(200);<br>});<br><br>app.listen(process.env.PORT || 3000, () =&gt; {<br>  console.log(&quot;Server is running on port 3000&quot;);<br>});</pre><h3>Conclusion</h3><p>Switching to webhook eliminates telegram rate-limiting issue and improves your bot’s efficiency. Just ensure you configure your server properly, use the allowed ports, and secure your connection with HTTPS.</p><p>Kindly follow me to get notified on my next post 📫.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=981fc3b4294b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL React Native]]></title>
            <link>https://medium.com/@ukpai/graphql-react-native-0e53bf40e292?source=rss-8aebf678c904------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e53bf40e292</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[tanstack-query]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[UKPAI Chukwuemeka]]></dc:creator>
            <pubDate>Thu, 09 Jan 2025 09:01:44 GMT</pubDate>
            <atom:updated>2025-01-15T12:01:37.100Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>When building a client-facing application, effective communication with an API is crucial. Two of the most commonly used API paradigms are <strong>REST</strong> and <strong>GraphQL</strong>, though they are not the only options — others include <strong>gRPC</strong> and <strong>SOAP</strong>.</blockquote><h3>My First Encounter with GraphQL</h3><p>The first time I heard about GraphQL, I was amazed by its capabilities. Imagine being able to specify exactly what data you want back from an endpoint — that feature alone stood out to me. Of course, GraphQL offers many other powerful features, but this was the one that initially caught my attention.</p><p>It was back in 2019 during one of Andela’s bootcamps — or maybe it was DevFest. I can’t recall the exact event, but I vividly remember the speaker, Benjamin Ogidan (<a href="https://medium.com/u/71dfc9aafef4">Benny Ogidan</a>), giving an engaging talk about GraphQL. I was so captivated that I saved the slides from that session, and they’ve been a valuable resource ever since.</p><p>Fast forward to the 2020 lockdown, and I had my first real-world experience working with GraphQL on a project called Hulp.io — a “GoFundMe” platform designed for Africa. Sadly, the project never launched, but it was an incredible learning experience. It was my first time writing GraphQL queries and mutations, and I also got to work with AWS, AppSync, and DynamoDB for the first time.</p><p>In this article, I’ll guide you through the process of configuring GraphQL in a React Native application. While many tools and approaches exist, I’ll share a method I’ve used successfully in multiple projects. It leverages tanstack query<strong>(@tanstack/react-query)</strong> for state management, enhancing performance and simplifying data-fetching workflows.</p><h3>What is GraphQL ?</h3><p>GraphQL is a query language and runtime for APIs, developed by Facebook in 2015. Unlike REST, which relies on multiple endpoints to fetch different sets of data, GraphQL enables clients to request precisely the data they need with a single query. This eliminates over-fetching and under-fetching, offering more efficient and flexible data handling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*bc6LhT7LMQNpgNEyr-kojA.png" /><figcaption>Photo by Benjamin Ogidan — REST API and GRAPHQL Comparison.</figcaption></figure><h3><strong>GraphQL Benefits</strong></h3><ol><li><strong>Single Endpoint:</strong> All queries are handled through one endpoint, simplifying API design and usage.</li><li><strong>Precise Data Fetching:</strong> Clients can request only the necessary fields, reducing payload size.</li><li><strong>Real-Time Data:</strong> With subscriptions, GraphQL can push real-time updates to clients.</li><li><strong>Strongly Typed Schema:</strong> GraphQL APIs are defined with a schema, which serves as a contract between the client and the server.</li></ol><h3>React Native GraphQL clients</h3><p>When working with GraphQL, you’ll need a client to make queries and mutations. Some popular GraphQL Client options include:</p><h3>Libraries for Queries and Mutations</h3><ul><li><a href="https://github.com/urql-graphql/urql"><strong>URQL</strong></a></li><li><a href="https://www.npmjs.com/package/graphql-request"><strong>graphql-request</strong></a></li><li><a href="https://www.npmjs.com/package/@apollo/client"><strong>Apollo Client</strong></a></li></ul><h3>React Native GraphQL GUI Client</h3><ol><li>GraphiQL</li><li>Insomnia</li><li>Apollo Studio Sandbox Explorer</li></ol><h3>Can I use GraphQL in React Native?</h3><p>Yes, you can use GraphQL in a React Native application. There are several ways to set up GraphQL in a React Native project, depending on your preferences and project requirements.</p><p>Let’s build a simple app that allows us to add students and assign hobbies to each student.</p><blockquote>You can find the code source for this tutorial on <a href="https://dub.sh/FbvvmgP">GitHub</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*_eIaLHJSYvMshun_Ugl-xg.gif" /><figcaption>React Native GraphQL example</figcaption></figure><h3>Prerequisites</h3><p>Before diving into the setup, ensure you have the following:</p><ol><li>A basic understanding of React Native.</li><li>Node.js and npm (or yarn) installed.</li><li>A working React Native development environment</li></ol><h4>React Native Init</h4><pre> npx @react-native-community/cli@latest init ReactNativeGQL</pre><h4>Install Required dependencies</h4><pre>npm i @tanstack/react-query graphql-request react-native-gesture-handler</pre><h4>Define Types</h4><pre>#types/index.ts<br><br>export interface IStudent {<br>    _id: string;<br>    firstName: string;<br>    email: string;<br>    hobbies?: IHobby[];<br>  }<br><br>  export interface IHobby {<br>    _id: string;<br>    title: string;<br>  }</pre><h4>Create GraphQL Service</h4><pre>import {GraphQLClient, RequestDocument} from &#39;graphql-request&#39;;<br><br>class GraphQLService {<br>  private client: GraphQLClient;<br><br>  constructor(url: string) {<br>    if (!url) {<br>      throw new Error(&#39;GraphQL endpoint URL must be provided&#39;);<br>    }<br><br>    this.client = new GraphQLClient(url);<br>  }<br><br>  async run&lt;T&gt;(query: RequestDocument, variables: Record&lt;string, any&gt; = {}): Promise&lt;T&gt; {<br>    try {<br>      // const token = await AsyncStorage.getItem(&#39;token&#39;);<br>      // Log the token for debugging, if needed (ensure not to log sensitive information in production)<br>      // const token = process.env.API_KEY ?? &#39;&#39;;<br>      // console.log(`Using token: ${token ? &#39;Provided&#39; : &#39;Not Provided&#39;}`);<br><br>      // Use the existing headers or set new ones as needed<br>      this.client.setHeaders({<br>        // Authorization: `Bearer ${token}`,<br>      });<br>      console.log(&#39;Executing GraphQL request:&#39;, {query, variables});<br>      // Execute the request and return the response<br>      return await this.client.request&lt;T&gt;(query, variables);<br>    } catch (error: any) {<br>      // Enhanced error handling<br>      console.error(&#39;GraphQL Request Error:&#39;, error);<br><br>      throw error;<br>    }<br>  }<br>}<br><br>export default GraphQLService;</pre><h4>Writing Queries and Mutations</h4><h4>Queries</h4><pre>import { gql } from &#39;graphql-request&#39;;</pre><pre>export const GET_STUDENT = gql`<br>  query GetStudent($id: ID!) {<br>    getStudent(id: $id) {<br>      _id<br>      firstName<br>      email<br>      hobbies {<br>        _id<br>        title<br>      }<br>    }<br>  }<br>`;</pre><pre>export const GET_HOBBIES = gql`<br>  query GetHobbies {<br>    getHobbies {<br>      _id<br>      title<br>    }<br>  }<br>`;<br></pre><pre>export const GET_ALL_STUDENTS = gql`<br>  query GetAllStudents {<br>    getAllStudents {<br>      _id<br>      firstName<br>      email<br>      hobbies {<br>        _id<br>        title<br>      }<br>    }<br>  }<br>`;</pre><h4>Mutations</h4><pre>import {gql} from &#39;graphql-request&#39;;<br><br>export const CREATE_STUDENT = gql`<br>  mutation CreateStudent($firstName: String!, $email: String!) {<br>    createStudent(firstName: $firstName, email: $email) {<br>      _id<br>      firstName<br>      email<br>    }<br>  }<br>`;<br><br><br>export const CREATE_HOBBY = gql`<br>  mutation CreateHobbies($studentId: String!, $title: String!) {<br>    createHobbies(studentId: $studentId, title: $title) {<br>      _id<br>      title<br>    }<br>  }<br>`;</pre><h4>Create Main Screen and Fetching Data using Tanstack Query</h4><pre>import React from &#39;react&#39;;<br>import {StyleSheet, View, Text, TouchableOpacity} from &#39;react-native&#39;;<br>import {useQuery} from &#39;@tanstack/react-query&#39;;<br>import {studentService} from &#39;../services/&#39;;<br>import {IStudent} from &#39;../types&#39;;<br>import {FlatList} from &#39;react-native&#39;;<br>import {Modal, TextInput} from &#39;react-native&#39;;<br>import {useMutation, useQueryClient} from &#39;@tanstack/react-query&#39;;<br>import {hobbiesService} from &#39;../services&#39;;<br><br>const Main = () =&gt; {<br>  const queryClient = useQueryClient();<br>  const [studentToAddHobby, setStudentToAddHobby] =<br>    React.useState&lt;IStudent | null&gt;(null);<br>  const [isModalVisible, setModalVisible] = React.useState(false);<br>  const [newHobby, setNewHobby] = React.useState(&#39;&#39;);<br>  const [isAddStudentModalVisible, setAddStudentModalVisible] =<br>    React.useState(false);<br>  const [newStudent, setNewStudent] = React.useState({<br>    firstName: &#39;&#39;,<br>    email: &#39;&#39;,<br>  });<br><br>  const {data, isLoading, error} = useQuery({<br>    queryKey: [&#39;students&#39;],<br>    queryFn: () =&gt; studentService.getStudents(),<br>  });<br>  console.log(JSON.stringify(data, null, 2));<br><br>  const {mutate: addHobby, isPending} = useMutation({<br>    mutationFn: async (hobby: string) =&gt; {<br>      await hobbiesService.createHobby(studentToAddHobby?._id!, hobby);<br>    },<br>    onSuccess: () =&gt; {<br>      setModalVisible(false);<br>      setNewHobby(&#39;&#39;);<br>      queryClient.invalidateQueries({queryKey: [&#39;students&#39;]});<br>    },<br>    onError: error =&gt; {<br>      console.error(&#39;Error adding hobby:&#39;, error);<br>    },<br>  });<br><br>  const handleSaveHobby = React.useCallback(() =&gt; {<br>    addHobby(newHobby);<br>    setModalVisible(false);<br>  }, [newHobby, addHobby]);<br><br>  const handleAddHobby = (student: IStudent) =&gt; {<br>    // Logic to add a hobby for the student with the given ID<br>    setStudentToAddHobby(student);<br>    setModalVisible(true);<br>  };<br><br>  const {mutate: addStudent, isPending: isAddingStudent} = useMutation({<br>    mutationFn: async (student: Omit&lt;IStudent, &#39;_id&#39;&gt;) =&gt; {<br>      await studentService.createStudent(student.firstName, student.email);<br>    },<br>    onSuccess: () =&gt; {<br>      setAddStudentModalVisible(false);<br>      setNewStudent({firstName: &#39;&#39;, email: &#39;&#39;});<br>      queryClient.invalidateQueries({queryKey: [&#39;students&#39;]});<br>    },<br>  });<br><br>  const handleSaveStudent = React.useCallback(() =&gt; {<br>    addStudent({firstName: newStudent.firstName, email: newStudent.email});<br>    setAddStudentModalVisible(false);<br>  }, [newStudent, addStudent]);<br><br>  if (isLoading) {<br>    return (<br>      &lt;View style={styles.container}&gt;<br>        &lt;Text&gt;Loading...&lt;/Text&gt;<br>      &lt;/View&gt;<br>    );<br>  }<br>  if (error) {<br>    return (<br>      &lt;View style={styles.container}&gt;<br>        &lt;Text&gt;Error: {error.message}&lt;/Text&gt;<br>      &lt;/View&gt;<br>    );<br>  }<br><br>  return (<br>    &lt;View style={styles.container}&gt;<br>      &lt;View&gt;<br>        &lt;TouchableOpacity<br>          onPress={() =&gt; setAddStudentModalVisible(true)}<br>          style={[<br>            styles.button,<br>            {marginVertical: 10, maxWidth: 200, alignSelf: &#39;flex-end&#39;},<br>          ]}&gt;<br>          &lt;Text style={[styles.buttonText, {textAlign: &#39;center&#39;}]}&gt;<br>            Add Student<br>          &lt;/Text&gt;<br>        &lt;/TouchableOpacity&gt;<br>      &lt;/View&gt;<br>      &lt;FlatList<br>        data={data?.getAllStudents as IStudent[]}<br>        keyExtractor={item =&gt; item._id}<br>        renderItem={({item}) =&gt; (<br>          &lt;View style={styles.studentItem}&gt;<br>            &lt;Text style={styles.studentName}&gt;{item.firstName}&lt;/Text&gt;<br>            &lt;Text style={styles.studentEmail}&gt;{item.email}&lt;/Text&gt;<br>            {item.hobbies &amp;&amp; item.hobbies.length &gt; 0 &amp;&amp; (<br>              &lt;View style={styles.hobbiesContainer}&gt;<br>                {item.hobbies.map(hobby =&gt; (<br>                  &lt;Text key={hobby._id} style={styles.hobby}&gt;<br>                    {hobby.title}<br>                  &lt;/Text&gt;<br>                ))}<br>              &lt;/View&gt;<br>            )}<br>            &lt;TouchableOpacity<br>              style={styles.addHobbyButton}<br>              onPress={() =&gt; handleAddHobby(item)}&gt;<br>              &lt;Text style={styles.addHobbyButtonText}&gt;Add Hobby&lt;/Text&gt;<br>            &lt;/TouchableOpacity&gt;<br>          &lt;/View&gt;<br>        )}<br>      /&gt;<br>      &lt;Modal<br>        visible={isModalVisible}<br>        transparent={true}<br>        animationType=&quot;slide&quot;<br>        onRequestClose={() =&gt; setModalVisible(false)}&gt;<br>        &lt;View style={styles.modalContainer}&gt;<br>          &lt;View style={styles.modalContent}&gt;<br>            &lt;Text style={{fontSize: 16, fontWeight: &#39;bold&#39;, marginBottom: 10}}&gt;<br>              Add a new hobby for {studentToAddHobby?.firstName}<br>            &lt;/Text&gt;<br>            &lt;TextInput<br>              style={styles.input}<br>              placeholder=&quot;Enter hobby&quot;<br>              value={newHobby}<br>              onChangeText={setNewHobby}<br>              placeholderTextColor={&#39;#333&#39;}<br>              autoFocus={true}<br>            /&gt;<br>            &lt;View<br>              style={{<br>                flexDirection: &#39;row&#39;,<br>                justifyContent: &#39;space-between&#39;,<br>                gap: 20,<br>              }}&gt;<br>              &lt;TouchableOpacity<br>                style={[styles.button, {flex: 1}]}<br>                onPress={handleSaveHobby}<br>                disabled={isPending || !newHobby}&gt;<br>                &lt;Text style={styles.buttonText}&gt;Save Hobby&lt;/Text&gt;<br>              &lt;/TouchableOpacity&gt;<br>              &lt;TouchableOpacity<br>                onPress={() =&gt; setModalVisible(false)}<br>                style={[<br>                  styles.button,<br>                  {<br>                    backgroundColor: &#39;transparent&#39;,<br>                    borderColor: &#39;gray&#39;,<br>                    borderWidth: 1,<br>                    shadowColor: &#39;transparent&#39;,<br>                  },<br>                ]}&gt;<br>                &lt;Text style={[styles.buttonText, {color: &#39;gray&#39;}]}&gt;Cancel&lt;/Text&gt;<br>              &lt;/TouchableOpacity&gt;<br>            &lt;/View&gt;<br>          &lt;/View&gt;<br>        &lt;/View&gt;<br>      &lt;/Modal&gt;<br><br>      {/* Add Student Modal */}<br>      &lt;Modal<br>        visible={isAddStudentModalVisible}<br>        transparent={true}<br>        animationType=&quot;slide&quot;<br>        onRequestClose={() =&gt; setAddStudentModalVisible(false)}&gt;<br>        &lt;View style={styles.modalContainer}&gt;<br>          &lt;View style={styles.modalContent}&gt;<br>            &lt;Text style={{fontSize: 16, fontWeight: &#39;bold&#39;, marginBottom: 10}}&gt;<br>              Add a new student<br>            &lt;/Text&gt;<br>            &lt;TextInput<br>              style={styles.input}<br>              placeholder=&quot;Enter first name&quot;<br>              value={newStudent.firstName}<br>              placeholderTextColor={&#39;#333&#39;}<br><br>              onChangeText={text =&gt;<br>                setNewStudent({...newStudent, firstName: text})<br>              }<br>            /&gt;<br>            &lt;TextInput<br>              style={styles.input}<br>              placeholder=&quot;Enter email&quot;<br>              placeholderTextColor={&#39;#333&#39;}<br>              value={newStudent.email}<br>              onChangeText={text =&gt; setNewStudent({...newStudent, email: text})}<br>            /&gt;<br>            &lt;View<br>              style={{<br>                flexDirection: &#39;row&#39;,<br>                justifyContent: &#39;space-between&#39;,<br>                gap: 20,<br>              }}&gt;<br>              &lt;TouchableOpacity<br>                style={[styles.button, {flex: 1}]}<br>                onPress={handleSaveStudent}<br>                disabled={<br>                  isAddingStudent || !newStudent.firstName || !newStudent.email<br>                }&gt;<br>                &lt;Text style={styles.buttonText}&gt;Save Student&lt;/Text&gt;<br>              &lt;/TouchableOpacity&gt;<br><br>              &lt;TouchableOpacity<br>                onPress={() =&gt; setAddStudentModalVisible(false)}<br>                style={[<br>                  styles.button,<br>                  {<br>                    backgroundColor: &#39;transparent&#39;,<br>                    borderColor: &#39;gray&#39;,<br>                    borderWidth: 1,<br>                    shadowColor: &#39;transparent&#39;,<br>                  },<br>                ]}&gt;<br>                &lt;Text style={[styles.buttonText, {color: &#39;gray&#39;}]}&gt;Cancel&lt;/Text&gt;<br>              &lt;/TouchableOpacity&gt;<br>            &lt;/View&gt;<br>          &lt;/View&gt;<br>        &lt;/View&gt;<br>      &lt;/Modal&gt;<br>    &lt;/View&gt;<br>  );<br>};<br><br>const styles = StyleSheet.create({<br>  container: {<br>    flex: 1,<br>    backgroundColor: &#39;white&#39;,<br>    paddingHorizontal: 24,<br>  },<br>  button: {<br>    backgroundColor: &#39;#4CAF50&#39;,<br>    paddingVertical: 8,<br>    paddingHorizontal: 16,<br>    borderRadius: 25,<br>    marginTop: 10,<br>    alignItems: &#39;center&#39;,<br>    shadowColor: &#39;#000&#39;,<br>    shadowOffset: {width: 0, height: 2},<br>    shadowOpacity: 0.3,<br>    shadowRadius: 3,<br>    elevation: 5,<br>  },<br>  buttonText: {<br>    color: &#39;white&#39;,<br>    fontSize: 14,<br>    fontWeight: &#39;600&#39;,<br>  },<br>  studentItem: {<br>    padding: 10,<br>    borderBottomWidth: 1,<br>    borderBottomColor: &#39;#ccc&#39;,<br>  },<br>  studentName: {<br>    fontSize: 16,<br>    fontWeight: &#39;bold&#39;,<br>  },<br>  studentEmail: {<br>    fontSize: 14,<br>    color: &#39;#666&#39;,<br>  },<br>  hobbiesContainer: {<br>    flexDirection: &#39;row&#39;,<br>    flexWrap: &#39;wrap&#39;,<br>  },<br>  hobby: {<br>    backgroundColor: &#39;#f0f0f0&#39;,<br>    padding: 5,<br>    margin: 2,<br>  },<br>  addHobbyButton: {<br>    backgroundColor: &#39;#4CAF50&#39;,<br>    paddingVertical: 8,<br>    paddingHorizontal: 16,<br>    borderRadius: 25,<br>    marginTop: 10,<br>    alignItems: &#39;center&#39;,<br>    shadowColor: &#39;#000&#39;,<br>    shadowOffset: {width: 0, height: 2},<br>    shadowOpacity: 0.3,<br>    shadowRadius: 3,<br>    elevation: 5,<br>  },<br>  addHobbyButtonText: {<br>    color: &#39;white&#39;,<br>    fontSize: 14,<br>    fontWeight: &#39;600&#39;,<br>  },<br>  modalContainer: {<br>    flex: 1,<br>    justifyContent: &#39;center&#39;,<br>    alignItems: &#39;center&#39;,<br>    backgroundColor: &#39;rgba(0, 0, 0, 0.5)&#39;,<br>  },<br>  modalContent: {<br>    backgroundColor: &#39;white&#39;,<br>    padding: 20,<br>    width: &#39;80%&#39;,<br>    borderRadius: 10,<br>  },<br>  input: {<br>    borderWidth: 1,<br>    borderColor: &#39;#ccc&#39;,<br>    padding: 10,<br>    marginBottom: 10,<br>    color: &#39;black&#39;,<br>  },<br>});<br><br>export default Main;</pre><h4>Update App.tsx</h4><pre>/**<br> * Sample React Native App using GraphQL<br> * https://github.com/facebook/react-native<br> *<br> * @format<br> */<br><br>import React from &#39;react&#39;;<br>import {QueryClient, QueryClientProvider} from &#39;@tanstack/react-query&#39;;<br>import {GestureHandlerRootView} from &#39;react-native-gesture-handler&#39;;<br>import {StyleSheet} from &#39;react-native&#39;;<br>import Main from &#39;./src/screens/main&#39;;<br><br>// init query client<br>const queryClient = new QueryClient();<br><br>function App(): React.JSX.Element {<br>  return (<br>    &lt;GestureHandlerRootView style={{flex: 1}}&gt;<br>      &lt;QueryClientProvider client={queryClient}&gt;<br>        &lt;Main /&gt;<br>      &lt;/QueryClientProvider&gt;<br>    &lt;/GestureHandlerRootView&gt;<br>  );<br>}</pre><h4>Wrap Up</h4><p>Congratulations on making it through! 🎉</p><p>If you found this article helpful, be sure to follow me here to stay updated on my upcoming posts, as well as the tips and tricks I share from time to time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e53bf40e292" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Generate JWT Token in React Native]]></title>
            <link>https://medium.com/@ukpai/how-to-generate-jwt-token-in-react-native-6d7d29aae567?source=rss-8aebf678c904------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d7d29aae567</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[jwt-token]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[UKPAI Chukwuemeka]]></dc:creator>
            <pubDate>Thu, 02 Jan 2025 13:31:57 GMT</pubDate>
            <atom:updated>2025-01-02T13:31:57.195Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*zUR4wGQ_TA8aZmj1oaSliQ.png" /><figcaption>Generate JWT Token</figcaption></figure><p>Do you need to generate a jwt token in your react native application for whatever reason?</p><p>Recently, I faced an intriguing challenge while working on <strong>EMV 3-D Secure authentication </strong>with <strong>Trust Payment</strong>, a third-party payment solution. This specific use case required generating a JWT token in a React Native application to securely encode sensitive transaction data before transmitting it over the network.</p><p>While generating JWT tokens on the web is straightforward, doing so in React Native poses unique challenges due to the lack of native web APIs.</p><p>In this article, I’ll walk you through the process of generating a JWT in React Native, explain the underlying technical details, and highlight the use of JWT in frontend applications, particularly in fintech.</p><blockquote><strong>EMV 3-D Secure authentication</strong>, also known as <strong>3DS2</strong>, is an advanced security protocol used for online credit and debit card transactions to reduce fraud and enhance the security of digital payments.</blockquote><h3>Why Generate JWT Tokens on the Frontend?</h3><p>Before we dive into the technical details, I would like to address why JWT generation often happens on the frontend especially when sensitive information is involved. You should also note that Json web token are typically generated on the server side to avoid exposing secrets.</p><p>However there are specific use cases where generating a JWT on the client side is both necessary and practical, such as:</p><p><strong>Encoding Sensitive Information</strong>: Normal HTTP requests leave payloads exposed, making them visible in network tabs. By encoding the payload, you add an additional layer of security to your application, reducing the risk of data exposure.</p><p><strong>Third-Party API Requirements</strong>: Some APIs expect JWT to authenticate or securely transmit data, even from the client.</p><p>In certain domains, where sensitive information such as card details is frequently handled, client-side encoding minimizes exposure risks during data transmission.</p><h3>Challenges Generating JWT token in React Native</h3><p>React Native lacks some native web APIs that simplify JWT generation in browser-based applications. For example, packages like jsonwebtoken rely on Node.js modules like crypto, which aren’t natively supported in React Native. This creates compatibility issues that polyfills alone may not resolve.</p><h3>Exploring JWT Solutions</h3><p>During my exploration, I tried several solutions and tools to generate JWT in a React Native application. Here’s a breakdown of the approaches I came across:</p><h3>1. Online Tools</h3><p>The online <a href="https://jwt.io/">jwt.io</a> encoder is a great debugging tool but impractical for live applications, it can be used to test payloads and verify JWT structures.</p><h3>2. <a href="https://www.npmjs.com/package/expo-jwt">Expo JWT</a></h3><p>This package simplifies the process of generating JWT in Expo-based React Native projects by abstracting the complexity of cryptographic operations.</p><p>However, I wasn’t sure if I could use it in my bare React Native setup. Nevertheless, by exploring the library’s source code, I found that it leverages <strong>crypto-js</strong>, a powerful JavaScript library for performing cryptographic algorithms. This insight became key in solving my JWT generation challenge.</p><h3>3. <a href="https://www.npmjs.com/package/crypto-js">Crypto-JS</a></h3><p>Crypto-js offers a wide range of cryptographic algorithms and is well-suited for environments like React Native, where native modules such as Node’s crypto are unavailable.</p><p>Since expo-jwt relies on crypto-js, I decided to integrate crypto-js directly into my React Native project. This approach gave me full control over the JWT encoding process and allowed for maximum flexibility and compatibility with my specific use case. Although crypto-js doesn’t support rsa encryption.</p><h3>Understanding JWT Structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y0PqZdBY4jfqvF3J7yM1pw.png" /></figure><p>A JWT consists of three main components: the header, the payload, and the signature. These components are separated by dots (.) and encoded in Base64URL.</p><h3>1. Header</h3><p>The header typically consists of two parts: the type of token, which is JWT, and the signing algorithm being used, such as <strong>HMAC SHA256</strong>.</p><pre>{<br>  &quot;alg&quot;: &quot;HS256&quot;,<br>  &quot;typ&quot;: &quot;JWT&quot;<br>}</pre><h4>2. Payload</h4><p>The payload contains the claims- statements about an entity (usually the user) and additional metadata. There are three types of claims: registered, public, and private. Registered claims are predefined in the JWT specification, while public and private claims can be defined as per the application’s needs.</p><ul><li><strong>Registered Claims</strong>: Predefined fields like iss (issuer) and exp (expiration).</li><li><strong>Public Claims</strong>: Defined for application-wide use.</li><li><strong>Private Claims</strong>: Custom fields for specific use cases.</li></ul><pre>{<br>  &quot;sub&quot;: &quot;1234567890&quot;,<br>  &quot;name&quot;: &quot;John Doe&quot;,<br>  &quot;admin&quot;: true<br>}</pre><h3>3. Signature</h3><p>To create the signature part, the encoded header, the encoded payload, and a secret key or private key are combined. This signature ensures that the token hasn’t been altered.</p><h3>Key Concepts for JWT Encoding</h3><h3>Base64URL</h3><p>URL-encode Base64 means converting a Base64-encoded string into a format that is safe to use in URLs. This ensures the encoded string does not contain characters that may be misinterpreted by URL parsers or result in errors by replacing + with - and / with _ to avoid conflicts in URL parsing.</p><h3>HMAC SHA256</h3><p>HMAC (Hash-based Message Authentication Code) with SHA256 is a cryptographic mechanism used to ensure both the <strong>integrity</strong> and <strong>authenticity</strong> of data. It combines a <strong>secret key</strong> with a cryptographic hash function (in this case, SHA256) to generate a secure hash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*_mdQPaRy5vN9JPygu-5gUQ.png" /></figure><h3>Implementing JWT Generation in React Native</h3><p>To generate a JWT token in react native, using the crypto-js package. you would need to setup your React Native project, then install the required packages.</p><pre>import Base64 from &#39;crypto-js/enc-base64&#39;;<br>import Utf8 from &#39;crypto-js/enc-utf8&#39;;<br>import HmacSHA256 from &#39;crypto-js/hmac-sha256&#39;;<br><br>export async function generateJWT(<br>  header: any,<br>  payload: any,<br>  secret: string,<br>) {<br>  // Step 1: Base64Url encode header and payload<br>  const jsonHeader = Base64.stringify(Utf8.parse(JSON.stringify(header)));<br>  const jsonPayload = Base64.stringify(Utf8.parse(JSON.stringify(payload)));<br><br>  const base64Header = urlEncodeBase64(jsonHeader);<br>  const base64Payload = urlEncodeBase64(jsonPayload);<br><br>  // Step 2: Create the message to sign<br>  const message = `${base64Header}.${base64Payload}`;<br><br>  // Step 3: Sign the message using HMAC SHA256 with the secret key<br>  const signature = HmacSHA256(message, secret);<br>  const base64Signature = signature.toString(Base64);<br><br>  // Step 4: Base64Url encode the signature<br>  const base64UrlSignature = urlEncodeBase64(base64Signature);<br>  console.log(`${base64Header}.${base64Payload}.${base64UrlSignature}`);<br>  // Step 5: Combine the parts to create the JWT<br>  return `${base64Header}.${base64Payload}.${base64UrlSignature}`;<br>}<br><br>export const urlEncodeBase64 = (signature: string): string =&gt; {<br>  signature = signature.replace(/(=+)$/g, &#39;&#39;);<br>  signature = signature.replace(/\//g, &#39;_&#39;);<br>  signature = signature.replace(/\+/g, &#39;-&#39;);<br><br>  return signature;<br>};</pre><blockquote>Github gist <a href="https://dub.sh/react-native-jwt">here</a>.</blockquote><pre>const header = {alg: &#39;HS256&#39;, typ: &#39;JWT&#39;};<br>const payload = {name: &quot;test&quot;};<br>const secret = xxxxxx;<br><br>//<br>generateJWT(header, payload, secret);</pre><h3>Summary</h3><p>While generating JWT on the frontend is feasible for certain use cases, it’s generally better to store secrets on the server. Additionally, when client-side generation is necessary, ensure sensitive data is protected by:</p><ol><li>Avoiding direct exposure of secrets in the code.</li><li>Using secure storage solutions like <strong>SecureStore</strong> or <strong>Keychain</strong>.</li></ol><h3><strong>Hire React Native Developer</strong></h3><p>Are you looking for a skilled developer to create secure, scalable mobile applications ?</p><p>📧 <strong>Email:</strong> speak2c.emeka@gmail.com<br>🌐 <strong>Portfolio:</strong> <a href="http://dub.sh/aimes">dub.sh/aimes</a><br>💼 <strong>LinkedIn:</strong> <a href="https://linkedin.com/in/ukpai">linkedin.com/in/ukpai</a></p><p>Let’s create something amazing together ! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d7d29aae567" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>