<?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 prdjed on Medium]]></title>
        <description><![CDATA[Stories by prdjed on Medium]]></description>
        <link>https://medium.com/@prdjed?source=rss-5ef77fd472dc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*tPnd3prji3ncinqq</url>
            <title>Stories by prdjed on Medium</title>
            <link>https://medium.com/@prdjed?source=rss-5ef77fd472dc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 01:44:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prdjed/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to use Google reCAPTCHA in React Native/Expo]]></title>
            <link>https://medium.com/@prdjed/how-to-use-google-recaptcha-in-react-native-expo-b956eccca3d3?source=rss-5ef77fd472dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/b956eccca3d3</guid>
            <category><![CDATA[expo]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[hybrid-app-development]]></category>
            <category><![CDATA[recaptcha]]></category>
            <dc:creator><![CDATA[prdjed]]></dc:creator>
            <pubDate>Wed, 05 Nov 2025 13:27:31 GMT</pubDate>
            <atom:updated>2025-11-05T13:27:31.645Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ge__HQYjSRJi8RKkBhA5jg.png" /></figure><p>Two Main Approaches:</p><ol><li><strong>WebView</strong> — This is the older method. It loads the reCAPTCHA widget inside a WebView and essentially simulates a browser environment. It works, but it’s not clean. It adds unnecessary overhead, can introduce security concerns, and is generally less reliable. <br><strong>Still, it’s widely used today simply because it was the only option available for a long time.</strong></li><li><a href="https://github.com/GoogleCloudPlatform"><strong>GoogleCloudPlatform</strong></a><strong>/</strong><a href="https://github.com/GoogleCloudPlatform/recaptcha-enterprise-react-native"><strong>recaptcha-enterprise-react-native</strong></a><strong> — This is the official library provided by Google for using reCAPTCHA in React Native.</strong> Instead of relying on a WebView, it uses the native reCAPTCHA SDKs under the hood, which makes it cleaner, more secure, and more reliable. It was <strong>released in early 2024</strong> and is now the recommended way to integrate reCAPTCHA in React Native. <strong>In this article, I’ll show how to set it up and use it.</strong></li></ol><h3>Instructions:</h3><p>First we need to configure reCAPTCHA on our Google Cloud console.<br>Do that by opening Google Cloud Console and search for reCAPTCHA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*41qcrJwg7jul5XYUAyYkIA.png" /></figure><p>After enabling it, create new key.<br><strong>You will need different keys for Android and iOS.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*IaQUz5MkHGgUIr0gJDB0kA.png" /><figcaption>Example screenshot of creating key for Android app</figcaption></figure><p>We will proceed with instructions for mobile apps.</p><p><strong>*This instruction does not explain how to setup reCAPTCHA on backend and how to define actions.</strong></p><p>In React Native/Expo app you need to install <a href="https://github.com/GoogleCloudPlatform">GoogleCloudPlatform</a><a href="https://github.com/GoogleCloudPlatform/recaptcha-enterprise-react-native">recaptcha-enterprise-react-native</a> library and follow installation instructions.</p><p><strong>USAGE:</strong><br>After installation is done you are able to use library:</p><h4>1. Import Recaptcha</h4><p>Use the following imports to access the APIs provided by the SDK.</p><pre>import {<br>  Recaptcha,<br>  RecaptchaAction,<br>  type RecaptchaClient,<br>} from &#39;@google-cloud/recaptcha-enterprise-react-native&#39;;</pre><h4>2. Initialize the client</h4><p>Instantiate a client by using the reCAPTCHA key (KEY_ID) that you created for your Android/iOS app.</p><pre>const client = await Recaptcha.fetchClient(SITE_KEY);</pre><p>Note:You must initialize the reCAPTCHA client only once during the lifetime of your app.</p><h4>3. Fetch Token</h4><p>For each action of your app that is protected using reCAPTCHA, call the execute method passing a RecaptchaAction. reCAPTCHA provides a built-in set of actions and if necessary you can create custom actions.</p><p>The following code snippet shows how to use execute to protect a LOGIN action.</p><pre>const token = await client.execute(RecaptchaAction.LOGIN());</pre><p><strong>*In case a custom action use </strong><strong>RecaptchaAction.custom(&#39;ACTION&#39;);</strong></p><h3>EXAMPLE:</h3><p>Here is example of my sign in function that uses reCAPTCHA:</p><pre> const signIn = async () =&gt; {<br>    try {<br>      let token;<br>      let signupRes;<br>      if (Platform.OS == &quot;android&quot;) {<br>        const client = await Recaptcha.fetchClient(Config.RECAPTCHA_ANDROID);<br>        token = await client.execute(RecaptchaAction.custom(&quot;auth/register&quot;));<br>        signupRes = await signin(<br>          axios,<br>          password,<br>          email,<br>          Config.RECAPTCHA_ANDROID,<br>          token,<br>          &quot;auth/login&quot;<br>        );<br>        await setSession(signupRes);<br>      } else {<br>        const client = await Recaptcha.fetchClient(Config.RECAPTCHA_IOS);<br>        token = await client.execute(RecaptchaAction.custom(&quot;auth/register&quot;));<br>        signupRes = await signin(<br>          axios,<br>          password,<br>          email,<br>          Config.RECAPTCHA_IOS,<br>          token,<br>          &quot;auth/login&quot;<br>        );<br>        await setSession(signupRes);<br>      }<br><br>      router.replace({ pathname: &quot;/&quot; });<br>      setLoading(false);<br>    } catch (error) {<br>      setLoading(false);<br>      console.log(error);<br>    }<br>  };</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b956eccca3d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Partial/Intermediate Hashing for eID and Smart Card Signatures]]></title>
            <link>https://medium.com/@prdjed/partial-intermediate-hashing-for-eid-and-smart-card-signatures-d95c3a4c60d1?source=rss-5ef77fd472dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/d95c3a4c60d1</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[smart-card-readers]]></category>
            <category><![CDATA[hashing]]></category>
            <dc:creator><![CDATA[prdjed]]></dc:creator>
            <pubDate>Sun, 24 Aug 2025 08:23:01 GMT</pubDate>
            <atom:updated>2025-08-24T13:16:18.910Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DTXlkw50DTSaFOQuQOelfw.png" /></figure><p>When working with eID and smart cards that support digital signatures, you’ll likely encounter the challenge of <strong>partial hashing</strong>. This becomes especially relevant when the card enforces strict security standards, such as those required by <strong>eIDAS-compliant protocols</strong>.</p><p>The reason this problem is hard to Google is that it’s actually a very <strong>niche use case</strong>. In most everyday programming, we never deal with intermediate hash states. Languages and libraries abstract that complexity away, giving us a neat <strong><em>hash()</em></strong> function that returns the final digest.<strong> Even though intermediate or partial hash is actually quite simple.</strong></p><h4>Why partial hashing is needed?</h4><p>Smart cards have tiny <strong>memory</strong> and <strong>limited APDU size</strong>:</p><ul><li>They can’t receive a whole PDF (megabytes) in one command.</li><li>Instead, the host streams the document in small APDUs.</li><li>The card performs <strong>partial hashing</strong>: each APDU updates the digest state.</li><li>Finally, the card signs the digest (e.g. via <strong><em>PSO: COMPUTE DIGITAL SIGNATURE</em></strong>).</li></ul><p><strong>Security</strong> reasons:</p><ul><li>If you hash externally, the <strong>card never sees the real data</strong> — it only sees a digest provided by the PC or mobile.</li><li>A malicious application could give the card a hash of <strong>different data</strong> than what the user thinks is being signed.</li></ul><p>Legal and Regulatory Requirements:</p><ul><li>Under <strong>eIDAS</strong> and similar frameworks, a <em>Qualified Signature Creation Device (QSCD)</em> must ensure that: the <strong>data-to-be-signed </strong>is correctly represented and the signature is created inside the secure device.</li><li>If hashing is done outside, the QSCD cannot guarantee that the digest really corresponds to the DTBS.</li><li>Therefore, <strong>intermediate or partial hashing</strong> is required for a qualified electronic signature.</li></ul><h3>Theory</h3><h4>What is a hash?</h4><p>A <strong>hash function</strong> (like SHA-256, SHA-512, SHA-1, etc.) is a mathematical function that takes input data of <strong>any size</strong> (1 byte, 1 GB, 1 TB …) and produces a <strong>fixed-size output</strong> (e.g. 256 bits = 32 bytes for SHA-256).</p><p>Key properties of hash functions:</p><ul><li><strong>Deterministic</strong> → same input always gives the same output.</li><li><strong>Collision resistance</strong> → practically impossible to find two different inputs with the same output.</li><li><strong>Preimage resistance</strong> → practically impossible to reconstruct the original input from its hash.</li><li><strong>Avalanche effect</strong> → changing even 1 bit in the input completely changes the output.</li></ul><h4>How does hashing works internally?</h4><p>Most cryptographic hash functions are <strong>iterative </strong>meaning that they do not process the whole input in one big mathematical step.</p><p>Instead, they:</p><ol><li>Split the input into <strong>blocks</strong> of fixed size (e.g. 512 bits = 64 bytes for SHA-256).</li><li>Process each block one at a time with a compression function.</li><li>Keep an <strong>internal state</strong> (called the chaining value).</li><li>At the end, output the final state as the digest.</li></ol><h4>What is partial hash?</h4><p><strong>Partial hashing</strong> means taking advantage of this block-by-block nature described previously.</p><ul><li>Instead of giving the entire data in one go, you feed it in <strong>chunks</strong>.</li><li>Each chunk updates the internal state of the hash.</li><li>When all chunks are processed, you finalize and get the digest.</li></ul><p>Example:</p><pre>State0 = IV (initial value)<br>State1 = f(State0, Block1)<br>State2 = f(State1, Block2)<br>State3 = f(State2, Block3)<br>...<br>Digest = StateN</pre><p>So, hashing <strong><em>“ABCDE”</em></strong> (where each letter represents one block e.g. 512 bits for SHA-256) in one go is mathematically the same as hashing <strong><em>“AB”</em></strong>, then updating with <strong><em>“CD”</em></strong>, then updating with <strong><em>“E”</em></strong>.</p><p>And if we would like to have partial hash of <strong><em>“ABCDE”</em></strong> that partialy hashes everything except last block (this is the case we need for smart card) we need to hash <strong><em>“AB”</em></strong> then update with <strong><em>“CD”</em></strong> and then give to the card <strong><em>“E”</em></strong> to finish hashing.</p><h4>Implementation</h4><p>As I already said, in most everyday programming, we never deal with intermediate hash states. Languages and libraries abstract that complexity away, giving us a neat <strong><em>hash()</em></strong> function that returns the final digest.</p><p>This means that we need to create “normal” full hashing by ourselves and then expose partial hash.</p><p>Here I will first put whole class doing this and below I will explain each part (I did implementation of this in Kotlin):</p><pre>package com.example.eid<br><br>import java.nio.ByteBuffer<br><br>class Sha256Intermediate {<br>    private val K = intArrayOf(<br>        0x428a2f98.toInt(), 0x71374491.toInt(), 0xb5c0fbcf.toInt(), 0xe9b5dba5.toInt(),<br>        0x3956c25b.toInt(), 0x59f111f1.toInt(), 0x923f82a4.toInt(), 0xab1c5ed5.toInt(),<br>        0xd807aa98.toInt(), 0x12835b01.toInt(), 0x243185be.toInt(), 0x550c7dc3.toInt(),<br>        0x72be5d74.toInt(), 0x80deb1fe.toInt(), 0x9bdc06a7.toInt(), 0xc19bf174.toInt(),<br>        0xe49b69c1.toInt(), 0xefbe4786.toInt(), 0x0fc19dc6.toInt(), 0x240ca1cc.toInt(),<br>        0x2de92c6f.toInt(), 0x4a7484aa.toInt(), 0x5cb0a9dc.toInt(), 0x76f988da.toInt(),<br>        0x983e5152.toInt(), 0xa831c66d.toInt(), 0xb00327c8.toInt(), 0xbf597fc7.toInt(),<br>        0xc6e00bf3.toInt(), 0xd5a79147.toInt(), 0x06ca6351.toInt(), 0x14292967.toInt(),<br>        0x27b70a85.toInt(), 0x2e1b2138.toInt(), 0x4d2c6dfc.toInt(), 0x53380d13.toInt(),<br>        0x650a7354.toInt(), 0x766a0abb.toInt(), 0x81c2c92e.toInt(), 0x92722c85.toInt(),<br>        0xa2bfe8a1.toInt(), 0xa81a664b.toInt(), 0xc24b8b70.toInt(), 0xc76c51a3.toInt(),<br>        0xd192e819.toInt(), 0xd6990624.toInt(), 0xf40e3585.toInt(), 0x106aa070.toInt(),<br>        0x19a4c116.toInt(), 0x1e376c08.toInt(), 0x2748774c.toInt(), 0x34b0bcb5.toInt(),<br>        0x391c0cb3.toInt(), 0x4ed8aa4a.toInt(), 0x5b9cca4f.toInt(), 0x682e6ff3.toInt(),<br>        0x748f82ee.toInt(), 0x78a5636f.toInt(), 0x84c87814.toInt(), 0x8cc70208.toInt(),<br>        0x90befffa.toInt(), 0xa4506ceb.toInt(), 0xbef9a3f7.toInt(), 0xc67178f2.toInt()<br>    )<br><br>    private val H = intArrayOf(<br>        0x6a09e667.toInt(), 0xbb67ae85.toInt(),<br>        0x3c6ef372.toInt(), 0xa54ff53a.toInt(),<br>        0x510e527f.toInt(), 0x9b05688c.toInt(),<br>        0x1f83d9ab.toInt(), 0x5be0cd19.toInt()<br>    )<br><br>    private val buffer = ByteArray(64)<br>    private var bufferPos = 0<br>    private var bytesProcessed: Long = 0<br><br>    private fun rotr(value: Int, bits: Int): Int {<br>        return (value ushr bits) or (value shl (32 - bits))<br>    }<br><br>    private fun processBlock(data: ByteArray, offset: Int) {<br>        val W = IntArray(64)<br><br>        // Prepare message schedule<br>        for (t in 0..15) {<br>            val i = offset + t * 4<br>            W[t] = ((data[i].toInt() and 0xFF) shl 24) or<br>                    ((data[i + 1].toInt() and 0xFF) shl 16) or<br>                    ((data[i + 2].toInt() and 0xFF) shl 8) or<br>                    (data[i + 3].toInt() and 0xFF)<br>        }<br>        for (t in 16..63) {<br>            val s0 = rotr(W[t - 15], 7) xor rotr(W[t - 15], 18) xor (W[t - 15] ushr 3)<br>            val s1 = rotr(W[t - 2], 17) xor rotr(W[t - 2], 19) xor (W[t - 2] ushr 10)<br>            W[t] = W[t - 16] + s0 + W[t - 7] + s1<br>        }<br><br>        // Initialize working variables<br>        var a = H[0]<br>        var b = H[1]<br>        var c = H[2]<br>        var d = H[3]<br>        var e = H[4]<br>        var f = H[5]<br>        var g = H[6]<br>        var h = H[7]<br><br>        for (t in 0..63) {<br>            val S1 = rotr(e, 6) xor rotr(e, 11) xor rotr(e, 25)<br>            val ch = (e and f) xor (e.inv() and g)<br>            val temp1 = h + S1 + ch + K[t] + W[t]<br>            val S0 = rotr(a, 2) xor rotr(a, 13) xor rotr(a, 22)<br>            val maj = (a and b) xor (a and c) xor (b and c)<br>            val temp2 = S0 + maj<br><br>            h = g<br>            g = f<br>            f = e<br>            e = d + temp1<br>            d = c<br>            c = b<br>            b = a<br>            a = temp1 + temp2<br>        }<br><br>        H[0] += a<br>        H[1] += b<br>        H[2] += c<br>        H[3] += d<br>        H[4] += e<br>        H[5] += f<br>        H[6] += g<br>        H[7] += h<br>    }<br><br>    fun update(input: ByteArray, offset: Int = 0, length: Int = input.size) {<br>        var pos = offset<br>        var len = length<br>        bytesProcessed += len<br><br>        // Fill buffer and process blocks<br>        if (bufferPos &gt; 0) {<br>            val toCopy = minOf(len, 64 - bufferPos)<br>            System.arraycopy(input, pos, buffer, bufferPos, toCopy)<br>            bufferPos += toCopy<br>            pos += toCopy<br>            len -= toCopy<br><br>            if (bufferPos == 64) {<br>                processBlock(buffer, 0)<br>                bufferPos = 0<br>            }<br>        }<br><br>        // Process complete 64-byte blocks<br>        while (len &gt;= 64) {<br>            processBlock(input, pos)<br>            pos += 64<br>            len -= 64<br>        }<br><br>        // Buffer remaining bytes<br>        if (len &gt; 0) {<br>            System.arraycopy(input, pos, buffer, bufferPos, len)<br>            bufferPos += len<br>        }<br>    }<br><br>    /**<br>     * Returns the intermediate hash state (H0-H7) as 32 bytes.<br>     * Only valid if bufferPos == 0 (no partial block pending).<br>     */<br>    fun getIntermediateState(): ByteArray {<br>        require(bufferPos == 0) { &quot;Intermediate state available only after processing full blocks (buffer empty)&quot; }<br><br>        val state = ByteArray(32)<br>        for (i in H.indices) {<br>            val v = H[i]<br>            val off = i * 4<br>            state[off] = (v ushr 24).toByte()<br>            state[off + 1] = (v ushr 16).toByte()<br>            state[off + 2] = (v ushr 8).toByte()<br>            state[off + 3] = v.toByte()<br>        }<br>        return state<br>    }<br>    fun finalizeHash(suffix: ByteArray): ByteArray {<br>        // Update with suffix<br>        update(suffix)<br><br>        // Add SHA-256 padding<br>        val totalBits = bytesProcessed * 8<br>        // Append &#39;1&#39; bit (0x80)<br>        update(byteArrayOf(0x80.toByte()))<br><br>        // Append zeros until buffer length is 56 bytes (448 bits)<br>        while (bufferPos != 56) {<br>            update(byteArrayOf(0x00))<br>        }<br><br>        // Append 64-bit message length (big endian)<br>        val lengthBytes = ByteBuffer.allocate(8).putLong(totalBits).array()<br>        update(lengthBytes)<br><br>        // Now the hash is ready in H[]<br>        val result = ByteArray(32)<br>        for (i in H.indices) {<br>            val v = H[i]<br>            val off = i * 4<br>            result[off] = (v ushr 24).toByte()<br>            result[off + 1] = (v ushr 16).toByte()<br>            result[off + 2] = (v ushr 8).toByte()<br>            result[off + 3] = v.toByte()<br>        }<br>        return result<br>    }<br>}</pre><p>Let’s explain each part:</p><pre>private val K = intArrayOf(... 64 constants ...)<br>private val H = intArrayOf(0x6a09e667, 0xbb67ae85, ... 0x5be0cd19)</pre><ul><li><strong><em>K</em></strong> are the 64 round constants from FIPS 180‑4.</li><li><strong><em>H</em></strong> holds the <strong>current chaining value</strong> (initial IV, then accumulates per block).</li></ul><pre>private val buffer = ByteArray(64)<br>private var bufferPos = 0<br>private var bytesProcessed: Long = 0</pre><ul><li><strong><em>buffer</em></strong> collects partial input until we have a full 64‑byte message block.</li><li><strong><em>bufferPos</em></strong> is <strong><em>bytesProcessed mod 64</em></strong> in effect.</li><li><strong><em>bytesProcessed</em></strong> counts <strong>all message bytes you’ve fed so far</strong> (before padding). It’s used to write the 64‑bit big‑endian length in the pad.</li></ul><pre>private fun rotr(value: Int, bits: Int) = (value ushr bits) or (value shl (32 - bits))</pre><ul><li>Correct 32‑bit rotate‑right using Java/Kotlin’s wraparound <strong><em>Int</em></strong> arithmetic (works modulo 2³² as required).</li></ul><pre>processBlock(...)</pre><p>This is where “normal” hashing is done and I will jump over explaining it since it’s already well documented on internet and it would require whole another blog story to explain it fully.</p><pre>update(input, offset, length)</pre><ul><li>Increments <strong><em>bytesProcessed</em></strong> by <strong><em>length</em></strong>.</li><li>Fills any partial block in <strong><em>buffer</em></strong>, processes full 64‑byte blocks directly from <strong><em>input</em></strong>, then stores any tail bytes back into <strong><em>buffer</em></strong>.</li><li>This is the core that enables <strong>partial hashing</strong> (streaming).</li></ul><pre>getIntermediateState()</pre><ul><li>Requires bufferPos == 0 (i.e., you are exactly at a block boundary).</li><li>Returns H0..H7 as 32 bytes (big‑endian).</li><li>This is a <strong>midstate</strong>: the chaining value <em>after</em> processing N full blocks.</li></ul><pre>finalizeHash(suffix)</pre><p>This function does same as smart card when it finalizes last round of hashing, it’s not needed for functionality itself but I added to be able to check if my finalized hash is same as what card returned.</p><p><strong>What if you need SHA-1 instead of SHA-256?</strong></p><p>Converting your mid‑state helper from SHA‑256 to SHA‑1 boils down to three concrete changes although the theory stays the same:</p><ol><li>different IV/state size</li><li>different round function &amp; constants</li><li>different message schedule</li></ol><h4>Pseudocode for feeding smart card with partial hash:</h4><pre>val totalBytes = myData.readBytes() //whole data in bytes<br>val prefixLen = totalBytes.size - (totalBytes.size % 64) //this tells you how many “extra” bytes don’t fit into a full 64-byte block.<br>val prefix = totalBytes.sliceArray(0 until prefixLen) //this gives us prefix data<br>val suffix = totalBytes.sliceArray(prefixLen until totalBytes.size) //this gives us suffix data<br><br>val sha256 = Sha256Intermediate() //create instance of out class<br><br><br>sha256.update(prefix, 0, prefixLen) //feed the prefix (must be multiple of 64 bytes)<br><br>val digest = sha256.getIntermediateState() //get the intermediate hash<br><br>//send apdu command to the card to finalize hashing e.g. 00 2A 90 A0 Lc 90 28 intermediateHash 8bytes(nbofbitsalreadyhashed) 80 suffixSize suffix</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d95c3a4c60d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Ionic Sucks]]></title>
            <link>https://medium.com/@prdjed/why-ionic-sucks-146f967f2102?source=rss-5ef77fd472dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/146f967f2102</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[hybrid-app-development]]></category>
            <category><![CDATA[ionic]]></category>
            <dc:creator><![CDATA[prdjed]]></dc:creator>
            <pubDate>Thu, 30 Jan 2025 13:11:13 GMT</pubDate>
            <atom:updated>2025-01-30T13:18:42.351Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zEDFu-BOEcLNBV1vVS25QQ.jpeg" /><figcaption>How it Feels to be an Ionic Developer</figcaption></figure><p>I am a mobile developer, and I used <strong>Ionic</strong> with the <strong>Ionic/Angular</strong> approach for two of my projects. After completing those, <strong>I decided to quit using</strong> <strong>Ionic</strong>. Now, I’m writing about the reasons why, hoping this will help someone <strong>avoid choosing Ionic altogether</strong>. Most reviews of <strong>Ionic</strong> on the internet are too generic and often written by AI or content writers who simply recycle content, such as “Why to Use Ionic in 2024” becoming “Why to Use Ionic in 2025.”</p><p>I quit using <strong>Ionic</strong> over a month ago, and I regret not writing this article sooner when my thoughts were fresher. However, I’ll do my best to share my experience.</p><h3>Why Ionic Sucks</h3><p>In explaining why <strong>Ionic</strong> sucks I will start with the list of <strong>general reasons</strong>, and in the second part of this story I will write about more <strong>specific problems</strong> that exist.</p><h3>General Reasons</h3><h4>You Can’t Make a Pie Out of Shit</h4><p>In my language, there’s a saying: <em>“Pita se ne pravi od govana”</em> which translates to <em>“You can’t make a pie out of shit.”</em> The point is simple — if you aim to build a high-quality app, Ionic isn’t the right choice unless your app is incredibly simple. However, if you’re content with lower-quality apps, Ionic works just fine.</p><p>In my opinion, Ionic shows no intention of improving. It lacks the capacity to evolve into something better and seems content with its current popularity. Unlike React Native, backed by Meta, or Flutter, backed by Google, Ionic doesn’t have the support of a major company driving its development forward.</p><p>Later in this article, I’ll dive into specific reasons why Ionic isn’t suitable for building advanced apps. One general issue worth mentioning upfront is its weak community.</p><h4>Weak community</h4><p>When I say <em>weak community</em>, I’m not just referring to the small number of developers using Ionic. More importantly, I’m talking about the lack of experienced developers building advanced apps with it.</p><p><strong>Why is that? </strong><br>The answer is simple: Ionic doesn’t offer enough. As soon as a skilled developer realizes that Ionic falls short in delivering the quality they aim for, they switch to a better framework or go fully native. This leaves the Ionic community filled mostly with beginners who fumble through it blindly, asking questions that often go unanswered.</p><p><strong>All in all, being an Ionic developer feels like swimming in the mud — constantly struggling to produce something of quality but never quite getting there.</strong></p><h4><strong>Endless Bug Fixing</strong></h4><p>Ionic is riddled with bugs. Due to its weak community, searching for solutions often leads you to countless unanswered questions. Even when you do find answers, they frequently involve fixes that come with their own bugs, requiring yet more fixes.</p><p>As a result, your project gradually turns into a chaotic mess, filled with patchwork solutions that barely hold together.</p><h4>Bad components</h4><p>Ionic can be divided into two parts: Capacitor and Ionic components. While Capacitor is also a product of the Ionic team, let’s focus on the components.</p><p>At first glance, the Ionic website looks promising, boasting a wide array of “native-like” components that are supposedly customizable. However, the real trouble begins when you actually try to use them. One component often forces you to use another, creating a frustrating chain reaction of dependency on buggy components.</p><p>As for customization — yes, technically it’s possible, but only if you’re living in the past when system-like components were the norm. Modern apps typically avoid such outdated approaches, opting for unique components that align with their distinct UI designs. Ionic simply doesn’t keep up with these contemporary standards.</p><h4><strong>Poor Native Plugin Support</strong></h4><p>As a consequence of its weak community, Ionic suffers from <strong>a lack of high-quality native plugins</strong>. Many plugins are outdated and poorly maintained. This often forces developers to spend valuable time fixing or modifying native plugins just to make them work properly.</p><p><strong>The end result?</strong> Your project becomes a maintenance nightmare, filled with fragile, patched-up solutions that hinder long-term development.</p><h4><strong>The “Native” Approach</strong></h4><p>Before diving into Ionic, <strong>it’s important to understand how it works</strong>, as this will help you better grasp the challenges you’ll face down the line</p><p>In native mobile development, there’s a component called the “<strong>WebView</strong>.” A <strong>WebView</strong> is used to display parts of a web app inside your native mobile app. It’s lightweight and typically used for things like terms and conditions, which may change frequently and are better suited for a <strong>WebView</strong> rather than being hardcoded into the app. For example, a news app might use a <strong>WebView</strong> to display HTML content.</p><p>Ionic, however, takes a different approach by attempting to run an entire web application inside a <strong>WebView</strong>. While this might seem like an interesting, experimental idea, it’s ultimately a poor choice. <strong>WebViews</strong> <strong>weren’t designed</strong> for such heavy lifting. Ionic defends itself by claiming that modern phones are powerful enough to handle it, but that doesn’t make it the right solution.</p><h3>Specific Reasons</h3><h4>Lack of Plugins</h4><p>Due to a weak community and underdeveloped framework, you will often face limitations in creating even basic functionalities for your application.</p><p>For example, while working on a project that already had <strong>Mixpanel</strong> analytics integrated, I needed to connect my mobile app with <strong>Mixpanel</strong>. I found a plugin that was a year old and outdated, not developed by the <strong>Mixpanel</strong> but by an independent developer who needed it. Despite being outdated and built for <strong>Capacitor</strong> <strong>4</strong> (while my project used <strong>Capacitor</strong> <strong>6</strong>), I tried it, and it worked. However, because it depended on Capacitor 4, I had to install both <strong>Capacitor</strong> <strong>4</strong> and <strong>Capacitor</strong> <strong>6</strong> in my project, significantly bloating the app. To make matters worse, I also had <strong>Capacitor</strong> <strong>5</strong> installed for a different plugin.</p><p>Such situations are more common than you’d expect. Big companies often don’t create plugins for <strong>Ionic/Capacitor/Cordova</strong>. To add basic functionalities, developers must rely on third-party plugins that are often unmaintained.</p><p>Take <strong>OneSignal</strong>, for example — a widely used solution for sending push notifications. It uses deprecated APIs internally inside native code of plugin, causing warnings, even though it is official plugin developed by <strong>OneSignal</strong>.</p><p>Another frustrating example is the <strong>Splash Screen plugin</strong>, which is an official <strong>Capacitor</strong> plugin. Using it results in a poorly implemented splash screen: the app icon appears in the middle of the screen on a black or white background (depending on your theme), and it looks blurry. Worse, the splash screen’s appearance varies across devices. <strong>To create a proper splash screen, you must ignore the official recommendations and implement it natively yourself.</strong></p><p>The <strong>Barcode Scanner</strong> (QR Code Scanner) plugin is another example. While it’s one of the better plugins made by <strong>Capacitor/Ionic</strong>, it still lacks essential features. For instance, it doesn’t support autofocus or macro focus (iOS). On iOS, the camera should automatically switch to the ultra-wide lens when the subject is close (around 2–3 cm). However, due to deprecated internal APIs, this functionality isn’t accessible. Additionally, the plugin doesn’t allow changing the camera’s resolution. By default, the resolution on iOS is set to something low, like 720x240. To fix this, you must manually edit the plugin’s internal code to set it to a better resolution like 1280x960.</p><p>Another issue with the <strong>Camera</strong> plugin — when used in a <strong>WebView</strong> environment — is that the camera mounts behind the <strong>WebView</strong>. To display it, you need to make the entire <strong>WebView</strong> transparent, which can cause flickering since <strong>you must manually handle the camera’s mounting and dismounting.</strong></p><p>Other official plugins have similar issues. For example, the <strong>TextZoom</strong> <strong>plugin works on Android</strong>, but the get() method, which retrieves the current zoom level, <strong>always returns “1” on iOS</strong>. <strong>As a result, you cannot determine how much a user has zoomed their font.</strong></p><p><strong>These are just a few examples. Many essential plugins either don’t exist or exist in a broken, incomplete state.</strong></p><h4>Network problems</h4><p>I used the <strong>Ionic/Angular</strong> approach, which is the most common one. Naturally, often app needs to communicate with a web API, and for that, you need to send network requests. Unfortunately, both available options are flawed.</p><p>The first option, which I would consider better, is using <strong>Angular’s HttpClient.</strong> Since you’re developing with <strong>Angular</strong>, it’s natural to use <strong>HttpClient</strong> as it aligns well with <strong>Angular’s</strong> reactive architecture. However, <strong>Ionic</strong> apps that rely on <strong>HttpClient</strong> <strong>become incredibly sensitive to network conditions. If the network isn’t blazing fast, requests often fail or become unreliable.</strong></p><p>The second option is the official <strong>CapacitorHttp</strong> plugin. While it doesn’t suffer from the network sensitivity issues of HttpClient, it’s extremely primitive. <strong>It lacks essential features like interceptors and other standard capabilities that developers expect from an HTTP client.</strong></p><p><strong>Both options leave much to be desired, forcing developers to make compromises that shouldn’t be necessary for robust app development.</strong></p><h4>Frankenstein Problem</h4><p>Due to its hybrid nature, <strong>somewhere between a native app and a web app</strong>, Ionic faces limitations that make it <strong>impossible</strong> to develop certain expected plugins. Two prominent examples are ads (<strong>Google Ads, AdMob, etc.</strong>) and <strong>Google reCAPTCHA</strong>.</p><p><strong>Ads:</strong></p><p><strong>Google</strong> provides two approaches for implementing ads: one for web apps and another for mobile apps. In <strong>Ionic</strong>, you can’t use the mobile approach since it requires native views, not a web view. This limitation forces you to resort to awkward solutions, such as <strong>lifting your web view slightly to display an ad at the bottom or shifting your app content down to fit an ad at the top.</strong> This results in a jarring layout change, where ads never sit naturally within the content. <strong>These are the most unattractive ad formats but unfortunately the only feasible ones in Ionic.</strong></p><p>I even tried faking a web approach by pretending the app was a web app. However, this failed because mobile apps don’t actually live on a domain, which is required for web-based ad solutions.</p><p><strong>Google reCAPTCHA:</strong></p><p>The same issue applies to <strong>Google reCAPTCHA</strong>. You can’t use the web approach due to domain limitations, but the mobile approach also doesn’t work because requests originate from a web view rather than a fully native environment.</p><p><strong>These are just two examples. There are numerous other plugins that simply can’t function because of Ionic’s hybrid nature.</strong></p><h4>Browser Preview</h4><p><strong>Ionic</strong> offers a great feature that allows you to serve your app in a browser, letting you preview how it will look without launching it in a mobile environment. However, there’s a significant drawback: <strong>the browser preview often doesn’t accurately reflect how the app will look on an actual mobile device.</strong></p><p>As a result, you might spend half the day developing based on the browser preview, only to run it on a mobile device and realize it looks completely different or doesn’t behave as expected. It’s a frustrating experience that can waste valuable development time.</p><h4>Capacitor vs Cordova</h4><p><strong>Capacitor</strong> and <strong>Cordova</strong> are essential parts of an <strong>Ionic</strong> app, responsible for managing the native side by connecting the web view to the native environment and exposing native APIs through JavaScript.</p><p><strong>Initially, Ionic relied on Cordova</strong>, which was developed by a separate company. Cordova had (and still has) a <strong>large collection of useful plugins</strong>. However, after some years, <strong>Ionic</strong> decided to move away from <strong>Cordova</strong> and develop its own native manager called <strong>Capacitor</strong>.</p><p>This transition led to a lot of confusion and compatibility issues. <strong>Many Cordova plugins couldn’t be used with Capacitor projects.</strong> While some Cordova plugins still work, others simply don’t. So if Capacitor doesn’t provide a feature and Cordova does, you’re often out of luck.</p><p>Another complication is that searching for <strong>Ionic</strong> plugins has become more complex. You now have to specifically search for <strong>Capacitor</strong> plugins. You <strong><em>can</em></strong> still look for Cordova plugins, but there’s no guarantee they will work, forcing you to spend time testing and troubleshooting.</p><h4>Managing Environments</h4><p><strong>CHAOS</strong></p><h4>Forced to Use Ionic Components(ion-content)</h4><p>In <strong>Ionic</strong>, you’re often <strong>forced to use Ionic components</strong>, even though you should theoretically be able to develop with standard web technologies like HTML. <br>One major issue is that <strong>Ionic caches every screen</strong>, <strong>which breaks normal Angular lifecycle methods like ngOnInit and ngAfterViewInit</strong>. These lifecycle hooks are only triggered the <strong>first time</strong> a component is loaded. To handle this, <strong>Ionic</strong> <strong>introduced its own lifecycle methods such as ionViewWillEnter and ionViewDidEnter</strong>.<strong> However, to use these lifecycle hooks, you must wrap your view in ion-content.</strong></p><p>That sounds manageable, but it’s not that simple. Ionic components can be problematic. Let’s say we have a parent component that covers the entire screen, with multiple child components that have their own nested children. Ideally, we’d want to use Angular lifecycle hooks in these child components, but we can’t because of the caching issue. The obvious solution might be to use ion-content in the child components as well — but that creates even more problems.</p><p><strong>Why?<br></strong>Ion-content is designed exclusively for parent components that hold the entire screen. When used in child components, it introduces unintended issues. For example:</p><p>1. ion-content includes built-in animations for screen transitions, so using it in child components causes erratic and weird transitions.</p><p>2. Inner ion-content instances can cause additional rendering problems due to their complex internals, which involve a mix of CSS, JavaScript, and HTML. These complexities prevent child components from behaving as expected compared to standard &lt;div&gt; elements.</p><p><strong>Possible Solutions:</strong></p><ol><li><strong>Flatten Component Structure</strong>: Use <strong>Ionic</strong> lifecycle methods in the parent component and avoid child components altogether. Put everything in the parent. <strong>This goes against Angular best practices and general programming principles but avoids Ionic lifecycle issues.</strong></li><li><strong>Reactive Subscriptions: </strong>Use observables and subscriptions for everything. Whenever something changes, notify an observable and have child components listen for these changes using live subscriptions. <strong>While this works, it creates additional complexity and maintenance overhead.</strong></li><li><strong>Angular Structure Falls Apart in Ionic: </strong>As I’ve mentioned before, I want to emphasize that if you use <strong>Ionic/Angular</strong> and expect any <strong>Angular</strong> developer to easily understand and navigate the project, you’ll be disappointed. <strong>The structure tends to fall apart, and it ends up being quite messy.</strong> T<strong>he whole idea that a company can have web developers seamlessly transition into mobile development falls apart as well.</strong> Ionic’s unique approach to managing native elements, custom life cycles, and other mobile-specific aspects introduces a complexity that makes it hard for developers familiar with pure Angular to work efficiently in the Ionic ecosystem.</li></ol><h4>What Happens When App Goes Into Background and Memory Leaks</h4><p><strong>This is a significant problem.</strong> There is very little information online about what happens when an <strong>Ionic</strong> app goes into the background. <strong>Ionic</strong> apps often rely on a variety of active subscriptions, and when the app goes into the background, there’s uncertainty about how these subscriptions behave. Sometimes, when an app is relaunched, everything reloads from scratch. Other times, the app simply returns from the background.</p><p>The issue that arises here is <strong>memory leaks</strong>. If you search for memory leaks in Ionic apps, you’ll find a lot of discussions from developers who’ve noticed problems related to the app going into the background. <strong>Specifically, if you send your app to the background and bring it back multiple times, you’ll start to notice a gradual increase in memory usage, which leads to memory leaks.</strong></p><p>This issue isn’t well-documented, and it can be frustrating to track down and fix. As a result, developers often struggle with understanding how to properly manage subscriptions and app lifecycle events to avoid memory leaks.</p><h4>Local Storage</h4><p>In web applications, <strong>Angular relies on localStorage</strong> (part of the Web Storage API) to store data locally, and this works seamlessly in a typical web environment. However, in <strong>Ionic</strong> apps, this isn’t possible in the same way. <strong>The problem arises because when an Ionic app is closed or sent to the background, the native localStorage doesn’t persist like it does in a browser environment.</strong> This is why Ionic uses a <strong>custom local storage solutions, like IonicStorage </strong>that works asynchronously.</p><p>While saving data locally is perfectly acceptable, <strong>the use of asynchronous storage conflicts with Angular’s synchronous nature.</strong> As a result, you quickly find yourself having to convert all of your subscriptions into a format that handles promises, often using the from() function in RxJS to convert them into observables.<strong> This leads to a chain reaction where your entire project becomes filled with subscriptions, and you lose the simplicity of a “normal” Angular subscription.</strong></p><h4>More About Components(ion-toolbar, status bar problem, bottom sheet)</h4><p>In the <strong>official documentation</strong>, it’s mentioned that many <strong>Ionic</strong> components use padding to ensure the content doesn’t go below the status bar. For example, the <strong>ion-toolbar</strong> component (which must be placed inside an ion-header, once again forcing you to use more Ionic components) adds padding to prevent content from being covered by the status bar. <strong>This works fine on iOS. However, on Android, it doesn’t work as expected.</strong></p><p>As a result, you’re forced to install third-party plugins to manage this issue on <strong>Android</strong>. The frustrating part is that since <strong>ion-toolbar</strong> works fine on <strong>iOS</strong>, you don’t need to add these fixes there. It would actually be better if it <em>didn’t</em> work on <strong>iOS</strong> either, so at least the issue would be consistent across both platforms, and you wouldn’t have to worry about platform-specific workarounds.</p><p>The main issue I encountered with the <strong>bottom sheet</strong> component is that it always needs to stay on top of the app, no matter what, because it is variation of <strong>ion-modal</strong> component that is alwasy on the top. There’s no easy way to place it behind other elements. For example, I had a situation where I needed to show a modal but also wanted to open a side menu that should appear over the modal. Unfortunately, that’s not possible with the built-in ion-modal.</p><p>To work around this, I created a <strong>custom bottom-sheet</strong>. However, this introduced its own set of challenges. With a custom modal, you have to handle all the logic yourself. <strong>For instance, on Android, when the user presses the back button, the modal should dismiss, but you also need to prevent the app from navigating back. Additionally, clicking behind the modal should close it, and there are many other small pieces of logic to implement in order to achieve a native-like experience.</strong></p><h4><strong>Customization Challenges with Ionic Components</strong></h4><p><strong>Ionic</strong> claims that its components are “customizable,” and while this is <strong>true to an extent, the level of customization they offer is often basic.</strong> The real problem arises when you try to deeply customize these components. <strong>Unlike standard web elements that you can style with regular classes and CSS properties, Ionic components don’t always follow the same conventions.</strong></p><p><strong>For example, you might want to change the color of a component using a class like “— color: primary”, which is somewhat like saying style=”color: red”. However, for some components, applying a class like “— color” doesn’t work the same as using style=”color:red”, and in other cases, the “— color” class doesn’t even exist. Some components have their own internal color logic that overrides normal styling approaches. This creates confusion and inconsistency.</strong></p><p><strong>The mess deepens when you try to create custom components. Since ion-content (the parent component) has its own internal structure, it can cause issues if you try to nest advanced custom components inside it. For example, if you place a fixed element inside ion-content, it can break navigation transitions.</strong></p><p><strong>Ultimately, customizing Ionic components becomes a balancing act between normal CSS styles, standard classes, Ionic-specific properties, and possibly third-party frameworks like Tailwind. You’ll end up with multiple conflicting approaches on a single element, leading to a lot of frustration and confusion.</strong></p><h4>Using Pixels</h4><p><strong>Ionic</strong> uses a <strong>WebView</strong>, which relies on pixels for layout. However,<strong> in mobile development, using pixels is not the most natural approach</strong>. When you work with pixels, you face difficulties maintaining mobile responsiveness. This becomes especially evident when you need your app to look good on various devices with different screen resolutions and aspect ratios.</p><h4>Controlling Keyboard</h4><p><strong>Controlling keyboard was always a pain in the ass, even for native developers, Ionic takes it to the next level.</strong> In the <strong>Capacitor</strong> configuration, you have a few options: resize your entire body, avoid resizing altogether, or resize certain wrapper elements (though I can’t recall exactly which ones). However, none of these options work well.</p><p>The best solution I found was to disable resizing altogether and instead manage the keyboard behavior manually for each screen. This involves installing a plugin that tracks the keyboard’s height. With this, I can analyze the screen height and adjust the layout accordingly — either by moving elements or making them scrollable all using JavaScript.</p><h4>Little More About Bad Components</h4><p><strong>Most of the components in Ionic are slow and buggy.</strong> The only benefit is that they look native, but once you interact with them, <strong>you can immediately tell they aren’t truly native</strong>. <strong>They might look native, but more like how native components looked 10 years ago</strong>. For instance, <strong>the date picker component is very buggy and slow</strong>. You can’t select a date in wheel mode <strong>until the animation completely stops, which leads to a frustrating experience</strong>. <strong>Sometimes, you might even accidentally select one of the underlying divs by touching, causing the component to turn blue unexpectedly.</strong></p><h4>Debugging is Hard</h4><p>While this is something that all mobile hybrid development shares at some extent I cannot avoid mentioning this.</p><p>While debugging web part of your application is fine, as in normal web app. Native part is much hard, expected solution would be that when something natively fails that you are notified inside web environment, but very often what breaks in native environment stays in native environment and never reaches web, so half of the things you need to debug via web and half by inspecting projects natively.</p><h3><strong>Conclusion</strong></h3><p>There is much more specific problems with <strong>Ionic</strong>, here I wrote the first ones that I could think of.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=146f967f2102" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to Managing Multiple Environments in React Native with react-native-config]]></title>
            <link>https://medium.com/@prdjed/a-guide-to-managing-multiple-environments-in-react-native-with-react-native-config-8af705d4f8b4?source=rss-5ef77fd472dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/8af705d4f8b4</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[expo]]></category>
            <category><![CDATA[react-native-config]]></category>
            <category><![CDATA[environment]]></category>
            <category><![CDATA[configuration]]></category>
            <dc:creator><![CDATA[prdjed]]></dc:creator>
            <pubDate>Wed, 22 Jan 2025 12:14:20 GMT</pubDate>
            <atom:updated>2025-01-23T07:14:26.902Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n5zd1su4nXutn-mp7A5WFg.jpeg" /></figure><p>While working with React Native, I’ve noticed that the internet is flooded with outdated and therefore misleading guides on using the react-native-config library.</p><p>This guide aims to be accurate walkthrough of how to use react-native-config effectively. Whether you&#39;re working with vanilla React Native or Expo, you&#39;ll learn how to manage multiple environments smoothly.</p><p><strong><em>A Note on Expo and Environment Variables</em></strong></p><p>While Expo provides its own mechanism for handling environment variables described <a href="https://docs.expo.dev/guides/environment-variables/">here</a>, it’s important to understand its limitations. To fully leverage Expo’s approach, you’ll need to use Continuous Native Generation (CNG) and Expo Application Services (EAS).</p><p>If, however, you’re not using CNG and EAS, Expo’s solution will not work for you, but <strong>react-native-config will work just fine</strong>.</p><h3><strong>General Setup of react-native config</strong></h3><p>First thing we should do is locate ourselves at the root of the project and run:</p><pre>npm i react-native-config</pre><pre>cd ios</pre><pre>pod install</pre><p>Let’s say that we want to have two environments: staging and production. In this case we need to create two files in the root of our project. Following environment files naming convention our files will be called <strong><em>.env.staging</em></strong> and .<strong><em>env.production. </em></strong>If you also have a development environment, you would create a file called <strong><em>.env.development</em></strong>.</p><p>In first file <strong><em>.env.staging</em></strong> write:</p><pre>ENV=staging</pre><p>In the second file <strong><em>.env.production</em></strong> write:</p><pre>ENV=production</pre><p>You can add any additional fields that you want such as API_URL or APP_NAME.</p><p>Also let’s create <strong><em>.env </em></strong>file and do not write anything in it.</p><h3>Android Setup</h3><p>First step is to add this block at the top of <em>/android/app/build.gradle </em>after lines that start with apply<em>:</em></p><pre>project.ext.envConfigFiles = [<br>        staging: &quot;.env.staging&quot;,<br>        production: &quot;.env.production&quot;,<br>]</pre><p>Second step is to add this line at the top of <em>/android/app/build.gradle </em>just after previously added block<em>:</em></p><pre>apply from: project(&#39;:react-native-config&#39;).projectDir.getPath() + &quot;/dotenv.gradle&quot;</pre><p>After adding that your build.gradle should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*kpAAjXhlJBNhT7TVUMeA4A.png" /><figcaption>added lines are 4,5,6,7,9</figcaption></figure><p>Third step is to create different flavors for different evironments, in order to do that put this block below <strong><em>androidResources</em></strong> block:</p><pre>flavorDimensions &#39;default&#39;<br>    productFlavors {<br>        production {<br>            buildConfigField &quot;String&quot;, &quot;ENVFILE&quot;, &#39;&quot;./.env.production&quot;&#39;<br>            dimension &#39;default&#39;<br>            applicationId &quot;&lt;customIdForProduction&gt;&quot;<br>            resValue &quot;string&quot;, &quot;app_name&quot;, &quot;&lt;customProductionName&gt;&quot;<br>        }<br>        staging {<br>            buildConfigField &quot;String&quot;, &quot;ENVFILE&quot;, &#39;&quot;./.env.staging&quot;&#39;<br>            applicationId &quot;&lt;customIdForStaging&gt;&quot;<br>            dimension &#39;default&#39;<br>            resValue &quot;string&quot;, &quot;app_name&quot;, &quot;&lt;customStagingName&gt;&quot;<br><br>        }</pre><p>This block is responsible for launching our project using an environment file based on the selected flavor. For example if we run production flavor it is going to use <strong><em>.env.production</em></strong> file, also we can create custom <strong><em>applicationId</em></strong> for each flavor so that we have two different applications for each flavor, or for example custom name for each flavor.</p><p>Fourth step is to add this line among our <strong><em>defaultConfig</em></strong> block in <em>android/app/build.gradle</em>:</p><pre>defaultConfig {<br>     resValue &quot;string&quot;, &quot;build_config_package&quot;, &quot;&lt;YOUR_PACKAGE_NAME_IN_ANDROIDMANIFEST_XML&gt;&quot;<br>      ^^add this line^^<br>}</pre><h3><strong><em>iOS Setup</em></strong></h3><p>First step in iOS is to create different schemes for different environments. To do that open Xcode and go to <em>Product&gt;Scheme&gt;New Scheme </em>and create new scheme and for target <strong>select you main app target</strong>.</p><p>Now you have two schemes one is going to represent production and another one staging.</p><p>First select scheme that you want to be your staging scheme by clicking on it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*o0ic79KOpi9xJt58BpMvkw.png" /></figure><p>And go to <strong>Edit Scheme</strong>.</p><p>There you need to open <strong><em>Build&gt;Pre-actions</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*f3NAmP3PuIU2zCLLjz7QXg.png" /></figure><p>In pre-actions add <strong>New Run Script Action</strong> by clickin <strong>+</strong> icon and enter next block.</p><pre>FILE_TO_DELETE=&quot;${PROJECT_DIR}/../node_modules/react-native-config/ios/ReactNativeConfig/GeneratedDotEnv.m&quot;<br><br># Check if the file exists and delete it<br>if [ -f &quot;$FILE_TO_DELETE&quot; ]; the<br>  rm -f &quot;$FILE_TO_DELETE&quot;<br>else<br>  echo &quot;File not found&quot;<br>fi<br>echo &quot;.env.staging&quot; &gt; /tmp/envfile</pre><p><strong><em>This first part of block is needed because library at this moment has problem with caching internal file called GeneratedDotEnv.m</em></strong>.<br><strong><em>The last line is needed anyway since react-native config library picks-up env’s from /tmp/envfile.</em></strong></p><p>After that block add new one:</p><pre>cp &quot;${PROJECT_DIR}/../.env.staging&quot; &quot;${PROJECT_DIR}/../.env&quot;  # replace .env.staging for your file</pre><p>And after that add one more:</p><pre>&quot;${SRCROOT}/../node_modules/react-native-config/ios/ReactNativeConfig/BuildXCConfig.rb&quot; &quot;${SRCROOT}/..&quot; &quot;${SRCROOT}/tmp.xcconfig&quot;</pre><p><strong>Make sure that for all of these blocks, field “Provide build settings from” is set to you main target.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*zDZVUldIhqvaodcKSX_LjQ.png" /></figure><p><strong>After doing these steps for staging you need to repeat same steps for another scheme, but instead of using .env.staging in scripts use .env.production.</strong></p><p>Next step is to create config file:</p><p>Right click on your project top folder&gt;New File from Template, search for Configuration Settings File adn create it with name Config.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*wbXdIk25uzCtCMuz_izHMQ.png" /></figure><p>Inside that file put:</p><pre>#include? &quot;tmp.xcconfig&quot;</pre><p>Final step for iOS is to go to your project view and for both Debug and Release configuration set newly created Config file, <strong>do not set it for target, just for project. As shown below:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*FYuVQCZJavUl3epMg7rqvQ.png" /></figure><h3>General Usage</h3><p>In order to access variables in your code use:</p><pre>import Config from &#39;react-native-config&#39;;<br>console.log(Config.ENV);</pre><p>If you are using Expo you can start your project with next commands:</p><pre>//stagingIos(debug)<br>npx expo run:ios --device --scheme &lt;stagingSchemeName&gt;<br>//stagingIos(release)<br>npx expo run:ios --device --scheme &lt;stagingSchemeName&gt; --configuration Release<br>//productionIos(debug)<br>npx expo run:ios --device --scheme &lt;stagingSchemeName&gt;<br>//stagingAndroid(debug)<br>npx expo run:android --device --variant stagingDebug --app-id &lt;appIdForStagingEnvrionmentThatIsSetInsideBuildFlavorEarlier&gt;<br>//stagingAndroid(release)<br>npx expo run:android --device --variant stagingRelease --app-id &lt;appIdForStagingEnvrionmentThatIsSetInsideBuildFlavorEarlier&gt;<br>//productionAndroid(debug)<br>npx expo run:android --device --variant productionDebug --app-id &lt;appIdForProductionEnvironmentThatIsSetInsideBuildFlavorEarlier&gt;</pre><p>to make it simpler for running you can create scripts inside package.json:</p><pre>&quot;scripts&quot;: {<br>    &quot;stagingDebug:android&quot;: &quot;expo run:android --device --variant stagingDebug --app-id &lt;appId&gt;&quot;,<br>    &quot;productionDebug:android&quot;: &quot;expo run:android --device --variant productionDebug --app-id &lt;appId&gt;&quot;,<br>    &quot;stagingRelease:android&quot;: &quot;expo run:android --device --variant stagingRelease --app-id &lt;appId&gt;&quot;,<br>    &quot;productionRelease:android&quot;: &quot;expo run:android --device --variant productionRelease --app-id &lt;appId&gt;&quot;,<br>    &quot;stagingDebug:ios&quot;: &quot;expo run:ios --device --scheme &lt;stagingScheme&gt;&quot;,<br>    &quot;productionDebug:ios&quot;: &quot;expo run:ios --device --scheme &lt;productionScheme&gt;&quot;,<br>    &quot;stagingRelease:ios&quot;: &quot;expo run:ios --device --scheme &lt;stagingScheme&gt; --configuration Release&quot;,<br>    &quot;productionRelease:ios&quot;: &quot;expo run:ios --device --scheme &lt;productionScheme&gt; --configuration Release&quot;,<br>    &quot;start&quot;: &quot;expo start&quot;,<br>    &quot;android&quot;: &quot;expo run:android&quot;,<br>    &quot;ios&quot;: &quot;expo run:ios&quot;,<br>    &quot;web&quot;: &quot;expo start --web&quot;,<br>    &quot;test&quot;: &quot;jest --watchAll&quot;,<br>    &quot;lint&quot;: &quot;expo lint&quot;<br>  },</pre><p>When releasing project to production you can simple open Xcode/Android studio and run production scheme/flavor. Environment variables will be picked up even when not running with expo commands.</p><h3>Configuring Different App Name and Id for Each Environment</h3><p>When creating environments you probably want to have different bundleId and different app names for each environment, maybe even different icon.</p><p>Let’s make different names for app depending on environment.</p><p>For Android we already did enough, in our flavor block inside build.gradle we configured custom names, app id, we can even configure custom image and similar things.</p><p>For iOS we will use already created .env files. Inside our .env.staging file put next:</p><pre>APP_NAME=&lt;stagingName&gt;<br>BUNDLE_ID_IOS=&lt;stagingBundleID&gt;<br></pre><p>And inside .env.production:</p><pre>APP_NAME=&lt;productionName&gt;<br>BUNDLE_ID_IOS=&lt;productionBundleID&gt;</pre><p>And then inside our Info.plist simply change display name and bundle identifier to reference our variables:</p><pre> &lt;key&gt;CFBundleIdentifier&lt;/key&gt;<br> &lt;string&gt;$(BUNDLE_ID_IOS)&lt;/string&gt;<br> &lt;key&gt;CFBundleDisplayName&lt;/key&gt;<br> &lt;string&gt;$(APP_NAME)&lt;/string&gt;</pre><p>Same approach can be used to change app icon and other fields, beside in Info.plist you can reference our variables anywhere inside build settings using $(*)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8af705d4f8b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>