<?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 Gregoire Frileux on Medium]]></title>
        <description><![CDATA[Stories by Gregoire Frileux on Medium]]></description>
        <link>https://medium.com/@gregoire.frileux?source=rss-8a9686e6b00a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*a-V1axx_tKctQ85pr0ar4Q.jpeg</url>
            <title>Stories by Gregoire Frileux on Medium</title>
            <link>https://medium.com/@gregoire.frileux?source=rss-8a9686e6b00a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 03:40:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gregoire.frileux/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 mock Auth0 spa hooks to test your React components]]></title>
            <link>https://itnext.io/how-to-mock-auth0-spa-hooks-to-test-your-react-components-e45b6a38fddb?source=rss-8a9686e6b00a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e45b6a38fddb</guid>
            <category><![CDATA[auth0]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Gregoire Frileux]]></dc:creator>
            <pubDate>Fri, 06 Sep 2019 09:03:58 GMT</pubDate>
            <atom:updated>2019-09-17T11:00:02.016Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*3f2tXYghuHbRB_1CvPGyRg.png" /></figure><p>Recently, we started developing a new React Web application, and decided to use <a href="https://auth0.com/">Auth0</a> to handle authentication.</p><p>Auth0 has a new library called <a href="https://github.com/auth0/auth0-spa-js#readme">auth0/auth0-spa-js</a> which handles a lot of the heavy lifting needed to connect your app and Auth0. It provides key login functions, and also includes a bunch of helpful React Hooks, that can be used across your app to access the user profile and logged in status</p><p>You can follow their quickstart linked in the npm package readme file, there is also a nice tutorial <a href="https://auth0.com/docs/quickstart/spa/react/01-login">here</a>, explaining how to integrate the library with your react application.</p><p>The guides are pretty good and we got started pretty quickly, however one aspect is not very well detailed in the library’s documentation: how to mock the hooks when performing unit tests on your components. I’m going to show a small code snippet that we’ve found useful when creating unit tests in our project.</p><h3>Assumptions</h3><p>In this tutorial, I’m assuming the below:</p><ul><li>you have some basic knowledge of what unit tests are, why they’re useful, and you’ve done some in the past</li><li>your project is already wired with the correct dependencies to run jest tests</li><li>my spec files will be saved in the same folder as the main component. You can save yours elsewhere and it will still work, obviously make sure the import paths are correct</li><li>I am also using enzyme in my code, but I believe the tutorial will work in the same way if you use other librairies such as react-test-renderer</li></ul><h3>Navbar as an example</h3><p>Let’s take the NavBar.js file quoted in the example from the tutorial:</p><pre>// src/components/NavBar.js<br><br>import React from &quot;react&quot;;<br>import { useAuth0 } from &quot;../react-auth0-wrapper&quot;;<br><br>const NavBar = () =&gt; {<br>  const { isAuthenticated, loginWithRedirect, logout } = useAuth0();<br><br>  return (<br>    &lt;div&gt;<br>      {!isAuthenticated &amp;&amp; (<br>        &lt;button<br>          onClick={() =&gt;<br>            loginWithRedirect({})<br>          }<br>        &gt;<br>          Log in<br>        &lt;/button&gt;<br>      )}<br><br>      {isAuthenticated &amp;&amp; &lt;button onClick={() =&gt; logout()}&gt;Log out&lt;/button&gt;}<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default NavBar;</pre><p>As you can see, this component references the useAuth0 hook that allows the navbar to access the user profile and logged in status (in isAuthenticated)</p><p>The way you would normally write a unit test for this component would be to do something like:</p><pre>// src/components/Navbar.spec.js</pre><pre>import React from &#39;react&#39;;<br>import { mount } from &#39;enzyme&#39;;<br>// component to test<br>import Navbar from &#39;./Navbar&#39;;</pre><pre>describe(&#39;components/navbar&#39;, () =&gt; {</pre><pre>  it(&#39;Renders with required props&#39;, async () =&gt; {<br>    const wrapper = mount(&lt;Navbar /&gt;);<br>    expect(wrapper).toBeTruthy();<br>  });</pre><pre>});</pre><p>However the issue will be that you will get an error due to the fact that useAuth0 is undefined.</p><p>TypeError: Cannot read property &#39;isAuthenticated&#39; of undefined</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*O_I4NBMabJTtAvogbsbiDQ.png" /></figure><p>This is because in the context of the unit test, the react-auth0-wrapper hasn’t been initialised with the React context, and so the function is undefined.</p><p>On top of that, we want to be able to test the component with different user states: user is logged in, user is logged out, user has verified their email or not, etc.</p><h3>Mocking the useAuth0 hook</h3><p>What we did was write a simple addition on the code above, to allow us to mock the useAuth0 function, and have it return a specific object.</p><p>This is the final code:</p><pre>// src/components/Navbar.spec.js</pre><pre>import React from &#39;react&#39;;<br>import { mount } from &#39;enzyme&#39;;</pre><pre>// component to test<br>import Navbar from &#39;./Navbar&#39;;</pre><pre>// import the auth0 hook<br>import { useAuth0 } from &#39;../react-auth0-wrapper&#39;;</pre><pre>// create a dummy user profile<br>const user = {<br>  email: &#39;johndoe@me.com&#39;,<br>  email_verified: true,<br>  sub: &#39;google-oauth2|2147627834623744883746&#39;,<br>};</pre><pre>// intercept the useAuth0 function and mock it<br>jest.mock(&#39;../react-auth0-wrapper&#39;);</pre><pre>describe(&#39;components/NavBar - logged in&#39;, () =&gt; {</pre><pre>  beforeEach(() =&gt; {</pre><pre>    // Mock the Auth0 hook and make it return a logged in state<br>    useAuth0.mockReturnValue({<br>      isAuthenticated: true,<br>      user,<br>      logout: jest.fn(),<br>      loginWithRedirect: jest.fn(),<br>    });</pre><pre>  });</pre><pre>  it(&#39;Renders with required props&#39;, async () =&gt; {</pre><pre>    const wrapper = mount(&lt;Navbar /&gt;);<br>    expect(wrapper).toBeTruthy();</pre><pre>  });</pre><pre>  it(&#39;Renders with correct link in the menu&#39;, async () =&gt; {</pre><pre>    const wrapper = mount(&lt;Navbar /&gt;);<br>    expect(wrapper).toBeTruthy();</pre><pre>    // should contain a button to be defined<br>    expect(wrapper.find(&#39;button&#39;)).toHaveLength(1);</pre><pre>    // the button should be the &quot;Log out&quot; one since the use is logged in<br>    expect(wrapper.find(&#39;button&#39;).text()).toEqual(&#39;Log out&#39;);</pre><pre>  });</pre><pre>});</pre><p>So what’s going on here:</p><pre>// import the auth0 hook<br>import { useAuth0 } from &#39;../react-auth0-wrapper&#39;;</pre><pre>and </pre><pre>// intercept the useAuth0 function and mock it<br>jest.mock(&#39;../react-auth0-wrapper&#39;);</pre><p>work together to import the function, and then tell Jest to use a mocked version instead</p><p>Then this section:</p><pre>beforeEach(() =&gt; {</pre><pre>// Mock the Auth0 hook and make it return a logged in state<br>    useAuth0.mockReturnValue({<br>      isAuthenticated: true,<br>      user,<br>      logout: jest.fn(),<br>      loginWithRedirect: jest.fn(),<br>    });</pre><pre>});</pre><p>allows us to define a set of tests where for each test, Jest will replace the useAuth0 function with the one we’ve defined. In this case we are returning isAuthenticated: true and the dummy user profile we defined higher up in the file.</p><p>We then test that the component mounts correctly, but also that the condition in NavBar.js which was choosing to show Log in or Log out actuall worked:</p><pre>{isAuthenticated &amp;&amp; &lt;button onClick={() =&gt; logout()}&gt;<strong>Log out</strong>&lt;/button&gt;}</pre><p>and so we test that the button in the Navbar has “Log out” as text.</p><h3>What next?</h3><p>From there, it would be very easy to add another set of tests, where this time we return a different set of data for the useAuth0 call. Simply copy the describe block, and in the beforeEach section, amend the object returned by useAuth0 . It could be simply :</p><pre>{ isAuthenticated: false, user: null, logout: jest.fn(), loginWithRedirect: jest.fn()}</pre><p>and then test that this time the component shows the “Log in” text in the button.</p><p>This small snippet should be very useful to test various components around the app that make use of the useAuth0 hook.</p><p>You could also simulate a click on the button, and test that the functions loginWithRedirect and logout have been called successfully.</p><p>Of course we could argue that the entire react-auth0-wrapper could and should be tested using Jest. For a simple project, you could take the view that the library is the responsibility of Auth0 and that testing this component is out of scope (i.e. it’s Auth0’s job). Or you could argue that the code is actually part of the project, and therefore should be tested. In my view, since we have a full one component and don’t just do an import &#39;@auth0/auth0-spa-js&#39; we’ll most likely very soon take the view that it should be properly tested. Once this is done, it will also give us another way of testing components that use the hook, by wrapping the compoenent being tested with a dummy Auth0Provider component.</p><p>Equally, it could also be argued that end-to-end tests will need to be written, incorporating the library.<br>For example you may well want to test your login page, and test a sequence: <em>Login page mounts correctly</em> &gt; enter <em>username=“&lt;test-value&gt;” + password=“&lt;test-password&gt;” + click “Log In”</em> &gt; <em>page refreshes and user object is present and </em><em>isAuthenticated=true .<br></em>I would also agree with that and I think that test should be a part of the overall test strategy. Again we’ve used the old auth0.js library on other projects, and the new auth0-spa is a new one we haven’t integrated in full on end-to-end tests yet, so maybe something for a next article.</p><h3>Conclusion</h3><p>I hope this short article was helpful, and as always, let me know your thoughts and ideas, and if anyone has some more complex examples to share, please let me know ! If anyone has gone further than we have and have already mocked the Auth0Provider I’d love to hear your experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e45b6a38fddb" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/how-to-mock-auth0-spa-hooks-to-test-your-react-components-e45b6a38fddb">How to mock Auth0 spa hooks to test your React components</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building React Native apps with Environment Variables via AppCenter]]></title>
            <link>https://medium.com/@gregoire.frileux/building-react-native-apps-with-environment-variables-via-appcenter-28d028fd178d?source=rss-8a9686e6b00a------2</link>
            <guid isPermaLink="false">https://medium.com/p/28d028fd178d</guid>
            <category><![CDATA[appcenter]]></category>
            <category><![CDATA[environment-variables]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[gradle]]></category>
            <dc:creator><![CDATA[Gregoire Frileux]]></dc:creator>
            <pubDate>Fri, 02 Aug 2019 10:48:47 GMT</pubDate>
            <atom:updated>2019-08-02T10:48:47.489Z</atom:updated>
            <content:encoded><![CDATA[<p>AppCenter is a Continuous Integration platform, that is incredibly helpful in streamlining testing and deploying our React Native apps. We currently have it setup so that any merge on develop will build an app that any member of the project can easily download to their phones for testing. Any merge on master will build and deploy the app on the stores, saving us hours of work on a monthly basis.</p><p>One of the feature of AppCenter is that you can store your <a href="https://docs.microsoft.com/en-us/appcenter/build/custom/variables/">Environment Variables</a> on each branch. This makes it very easy to have different keys for debug, staging and production, by simply having different values set up on your different branches configurations in AppCenter</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k3aZCFkhY60cOYxgsvdv5A.png" /><figcaption><a href="https://docs.microsoft.com/en-us/appcenter/build/custom/variables/">https://docs.microsoft.com/en-us/appcenter/build/custom/variables/</a></figcaption></figure><p>So far, nothing too crazy. You can use react-native-dotenv or any other library to setup a .env file in your project, and use the ENV VARS in your code.</p><p>The .env file itself can be overwritten by a simple appcenter-post-clone.sh script to copy the values from AppCenter on master or release branch, or to create a custom .env.production version. And your code can now use different API Keys for debug and production.</p><h3>What about the build stage ?</h3><p>One thing we found a little bit more challenging was how to access ENV VARS during the build process. For the purpose of this article, I’m using Fabric, but the idea is not to show a tutorial on how to implement Fabric, but to show the different ways ENV VARS can be useful during the build on Android and iOS.</p><p>If you have <a href="https://fabric.io/home">Fabric</a> installed on your project for example, it will require adding code to your Info.plist file on iOS :</p><pre>&lt;key&gt;Fabric&lt;/key&gt;<br>&lt;dict&gt;<br>  &lt;key&gt;APIKey&lt;/key&gt;<br>  &lt;string&gt;&lt;your-API-KEY&gt;&lt;/string&gt;<br>  &lt;key&gt;Kits&lt;/key&gt;<br>  &lt;array&gt;<br>    &lt;dict&gt;<br>      &lt;key&gt;KitInfo&lt;/key&gt;<br>    &lt;dict/&gt;<br>      &lt;key&gt;KitName&lt;/key&gt;<br>      &lt;string&gt;Crashlytics&lt;/string&gt;<br>      &lt;/dict&gt;<br>    &lt;/array&gt;<br>&lt;/dict&gt;</pre><p>For ios, you also need a custom script in the build phase:</p><pre>&quot;Pods/Fabric/run&quot; &lt;your-api-key&gt;  &lt;a-unique-hash-provided-by-Fabric&gt;</pre><p>And also some code in your Android Manifest:</p><pre>&lt;meta-data<br>  android:name=&quot;io.fabric.ApiKey&quot;<br>  android:value=&quot;&lt;your-api-key&gt;&quot;<br>/&gt;</pre><p>If you wanted to use different keys for debug, staging and master, then you need to either:</p><ul><li>Overwrite the plist and Manifest using a post-clone script, in order to replace the values present by the one required by your branch. So if you have your debug keys by default, and AppCenter is building the master branch, your script would need to inject the production API Keys in the plist and manifest. This will work well in a lot of cases, but typically it’s not easy to handle the custom script in the build phase for IOS.</li><li>OR somehow use a variable instead of a hard coded value, and set the value of that variable in an ENV VAR</li></ul><p>There are plenty of good articles on using post-clone script, so I’ll focus today on the second option and using ENV VARS.</p><p>So for Android, this looks like this:</p><p>AndroidManifest.xml:</p><pre>&lt;meta-data<br>  android:name=&quot;io.fabric.ApiKey&quot;<br>  android:value=&quot;${fabricAPIKey}&quot;<br>/&gt;</pre><p>app/build.gradle</p><pre>/**<br>* Defining build variables from ENV VARS<br>*/</pre><pre>def fabricApiKeyFromEnv = System.getenv(&quot;FABRIC_API_KEY&quot;) ? System.getenv(&quot;FABRIC_API_KEY&quot;) : &quot;&lt;your-debug-key-value&gt;&quot;</pre><pre>android {</pre><pre>   ...<br>   &lt;here is your project configuration, SDK versions, etc.&gt;<br>   ...</pre><pre>buildTypes {<br>   release {<br>      // Set Fabric API Key<br>      manifestPlaceholders = [fabricApiKey : fabricApiKeyFromEnv]<br>   }<br>   debug {<br>      // Set Fabric API Key<br>      manifestPlaceholders = [fabricApiKey : fabricApiKeyFromEnv]<br>   }</pre><pre>  }<br>}</pre><p>So what did we do here?</p><ul><li>We used a build variable inside the manifest, this is pretty standard practice on Android</li><li>We then added a bit of code inside the app/build.gradle file to load the value of the FABRI_API_KEY environment variable. If no value is present (which will be the case when building on your machine, and most likely also when building on develop), we use the debug key. This value shouldn’t be too sensitive so it’s ok to have it in plain in the file and committed to git</li><li>In the buildType section, we tell gradle to use the fabricApiKeyFromEnv variable , and assign it to the placeholder fabicApiKey created in the manifest</li></ul><p>The next step is to make sure that you set up FABRIC_API_KEY in AppCenter, and in theory, you would expect that during the build phase, the following sequence will happen:</p><ul><li>AppCenter will export the FABRIC_API_KEY environment variable and assign it the value you entered for that branch</li><li>fabricApiKeyFromEnv will load the value using the System.getenv function</li><li>the manifest placeholder will inherit the value it needs</li><li>your app will build successfully and use the correct key on each branch</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*oosYsATmknlxCIThI0uVyQ.png" /><figcaption>Adding FABRIC_API_KEY to the AppCenter branch config</figcaption></figure><p>Now for iOS. If we continue with the Fabric example, there are going to be two steps to the process.</p><ol><li>Handling the info.plist file</li></ol><p>As we’ve seen, the Fabric install requires adding a key to the plist file. If you want to have different values for different environments, you’ll need to be able to edit your plist file and change values around depending on the branch currently building.<br>For this step, we decided to go for the scripting option, and use the appcenter-post-clone.sh file to handle the change.</p><pre>if [ &quot;$APPCENTER_BRANCH&quot; == &quot;master&quot; ];</pre><pre>then</pre><pre>/usr/libexec/PlistBuddy -c &quot;Set :Fabric:APIKey $FABRIC_API_KEY&quot; ios/community/Info.plist</pre><pre>fi</pre><p>As discussed, the FABRIC_API_KEY is declared in the list of ENV VARS in our configuration of the master branch on AppCenter. The rest is pretty self explanatory: we use PlistBuddy to simply find the key and replace its value with the ENV VAR value.</p><p>2. Handling the custom build script</p><p>This part is slightly more tricky.</p><p>When you install Fabric, they indicate that you should open XCode, and add a custom build script and paste some code to set the API Key. In XCode, this looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*GRTa6t3B8wb8Jd9mUQ7-RA.png" /><figcaption>Adding a Custom Build Script for Fabric</figcaption></figure><p>The first step was to extract all such scripts to a unique place in our project. For this article I’m using Fabric as an example, but as your app grows, there will be many other tools that will require custom code to be added, and adding a custom step each time is really not ideal for many reasons (maybe another article on this soon).</p><p>Instead, we use this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*S8zz6bbsnpW0VHjkz1Hz1A.png" /><figcaption>Single build script for iOS</figcaption></figure><p>And then we created a file called custom_build_scripts.sh stored at the root of our /ios folder. This enables cleaner tracking of changes in Git, and just makes it easier to maintain.</p><p>Then the code you would add to make Fabric run would be :</p><pre>#!/usr/bin/env bash</pre><pre>if [ &quot;$APPCENTER_BRANCH&quot; == &#39;master&#39; ]; then</pre><pre>echo &#39;Setting Fabric Production Key&#39;</pre><pre>&quot;Pods/Fabric/run&quot; $FABRIC_API_KEY &lt;production-unique-hash&gt;</pre><pre>else</pre><pre>echo &#39;Setting Fabric DEV Key&#39;</pre><pre>&quot;Pods/Fabric/run&quot; &lt;your-plain-dev-key-no-need-for-ENV-VAR&gt; &lt;the-dev-hash&gt;</pre><pre>fi</pre><p>This code looks if we’re on master, and if we are it uses the ENV VAR. If not we left the plain dev key there. Again this value isn’t super sensitive and it means we don’t have to setup the ENV VARS on the AppCenter develop branch.</p><p>Problem: this doesn’t work….</p><h3>Making ENV VARS accessible during Build for iOS</h3><p>Looking into the issue we realised that the problem came from the way bash runs, and the fact that each new script that is launched will have its own ENV. It is also linked to the way AppCenter works, and the fact that they “restrict” usage of ENV VARS to pre-defined phases of te build. For more info see:</p><p><a href="https://docs.microsoft.com/en-us/appcenter/build/custom/variables/">Environment Variables - Visual Studio App Center</a></p><p>and :</p><p><a href="https://github.com/microsoft/appcenter/issues/161">https://github.com/microsoft/appcenter/issues/161</a></p><p>So in order to fix this, we resulted in having to build a custom solution.</p><ol><li>Create a env.txt file that will be accessible anywhere, and will contain all our ENV VARS</li></ol><p>This was relatively easy. Just create/amend your appcenter-post-clone.sh at the root of your project.</p><p>On the branches where you need your ENV VARS, add the lines below:</p><pre>...</pre><pre># Creating an env.txt file with all our ENV VARS</pre><pre>echo &quot;export CODEPUSH_KEY=\&quot;$CODEPUSH_KEY\&quot;&quot; &gt;&gt; env.txt</pre><pre>echo &quot;export MAPBOX_TOKEN=\&quot;$MAPBOX_TOKEN\&quot;&quot; &gt;&gt; env.txt</pre><pre>echo &quot;export FABRIC_API_KEY=\&quot;$FABRIC_API_KEY\&quot;&quot; &gt;&gt; env.txt</pre><pre>...</pre><p>List all the variables you want/need in there. This will create a new env.txt file that will be accessible to any script. Your env.txt file will look like this:</p><pre>export CODEPUSH_KEY=&quot;&lt;value-of-the-env-var-CODEPUSH_KEY&gt;&quot;<br>export MAPBOX_TOKEN=&quot;&lt;value-of-the-env-var-MAPBOX_TOKEN&gt;&quot;<br>export FABRIC_API_KEY=&quot;&lt;value-of-the-env-var-FABRIC_API_KEY&gt;&quot;</pre><p>2. Source the file to export all ENV VARS where needed</p><p>Back to our custom_build_scripts.sh file from earlier, where we needed $FABRIC_API_KEY we can now simply add a few lines to source the file env.txt.</p><p>Because the file is in fact a series of export VARIABLE=value commands, it can be open using source and this will directly export the ENV VARS and make them accessible to bash. So the new file becomes:</p><pre>#!/usr/bin/env bash</pre><pre>if [ -f ../env.txt ]</pre><pre>then</pre><pre>source ../env.txt</pre><pre>fi</pre><pre>if [ &quot;$APPCENTER_BRANCH&quot; == &#39;master&#39; ]; then</pre><pre>echo &#39;Setting Fabric Production Key&#39;</pre><pre>&quot;Pods/Fabric/run&quot; $FABRIC_API_KEY &lt;production-unique-hash&gt;</pre><pre>else</pre><pre>echo &#39;Setting Fabric DEV Key&#39;</pre><pre>&quot;Pods/Fabric/run&quot; &lt;your-plain-dev-key-no-need-for-ENV-VAR&gt; &lt;the-dev-hash&gt;</pre><pre>fi</pre><p>The added lines will check if the file env.txt exists. If it does, it will run source on it , which as explained will make the ENV VARS available to the rest of the script.</p><h3>Conclusion</h3><p>I must be honest, it was harder than we thought it would be, but we got there in the end. It will require a little bit of maintenance to keep you appcenter-post-clone.sh file aligned with your AppCenter branches. You’ll need to ensure that variables are “defined everywhere” or everything to run smoothly. All that said, it’s a huge time saver to be able to “set and forget” these keys, and not have to keep passwords and keys flying around the team the whole time. Any new key gets added to AppCenter, then gets referenced in the clone script, and that’s it, it’ll be available to the code and the build.</p><p>Last note: this article was written using Fabric as an example. The implementation of Fabric is changing with the transition over to Firebase Crashlytics, so perhaps the code will change in the future, but the important thing I wanted to highlight was the management f ENV VARS, so Fabric was just a pretext. Hopefully it helps, and as always: keen to hear your thoughts and improvement ideas ! Just comment below to let me know.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28d028fd178d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native — How to handle an app with both pre-AndroidX and AndroidX dependencies (RN60)]]></title>
            <link>https://itnext.io/react-native-how-to-handle-an-app-with-both-pre-androidx-and-androidx-dependencies-rn60-bf4df7ea0dd2?source=rss-8a9686e6b00a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf4df7ea0dd2</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androidx]]></category>
            <dc:creator><![CDATA[Gregoire Frileux]]></dc:creator>
            <pubDate>Tue, 02 Jul 2019 16:59:13 GMT</pubDate>
            <atom:updated>2019-07-10T17:45:00.962Z</atom:updated>
            <content:encoded><![CDATA[<h3>React Native — How to handle an app with both pre-AndroidX and AndroidX dependencies (RN60)</h3><p>Before starting and diving into the why/how/solutions of how to handle an app with both non AndroidX and AndroidX dependencies, it might be worth talking about what AndroidX is for a minute.</p><p>If you haven’t heard the term yet, <a href="https://developer.android.com/jetpack/androidx">AndroidX</a> is the new program being rolled out by Google to package librairies with Jetpack. Essentially, the old way of managing librairies was becoming overcomplicated and so Google decided to start cleaning up their act and use a new system, along with new library names.</p><p>So if your project was relying on a library called com.android.support:appcompat-v7, and you wanted to migrate to AndroidX, then you would have to call androidx.appcompat:appcompat:1.0.0 . Google has been helpful and even provided a list of old/new names here: <a href="https://developer.android.com/jetpack/androidx/migrate">https://developer.android.com/jetpack/androidx/migrate</a></p><p>So what does that mean for your React Native project ? Well if like us you use a bunch of third party librairies (Firebase, Auth0, Mapbox, etc.) then chances are either your project directly imports Google librairies, or some of your third party rely on Google librairies.</p><p>This mean that somewhere in your android project, in your build.gradle, you may have a line such as :</p><pre>implementation &quot;com.android.support:appcompat-v7:&lt;version-name&gt;&quot;</pre><p>Or perhaps in your dependency tree (in Android Studio, click on Terminal and then run ./gradlew app:dependencies and this will show something like :</p><pre>+--- project :react-native-code-push<br>|    +--- com.facebook.react:react-native:+ -&gt; 0.57.5<br>|    |    +--- com.facebook.infer.annotation:infer-annotation:0.11.2<br>|    |    |    \--- com.google.code.findbugs:jsr305:3.0.1 -&gt; 3.0.2<br>|    |    +--- javax.inject:javax.inject:1<br>|    |    +--- com.android.support:appcompat-v7:27.1.1<br>|    |    |    +--- com.android.support:support-annotations:27.1.1<br>|    |    |    +--- com.android.support:support-core-utils:27.1.1<br>|    |    |    |    +--- com.android.support:support-annotations:27.1.1<br>|    |    |    |    \--- com.android.support:support-compat:27.1.1<br>|    |    |    |         +--- com.android.support:support-annotations:27.1.1<br>|    |    |    |         \--- android.arch.lifecycle:runtime:1.1.0<br>|    |    |    |              +--- android.arch.lifecycle:common:1.1.0<br>|    |    |    |              \--- android.arch.core:common:1.1.0<br>|    |    |    +--- com.android.support:support-fragment:27.1.1<br>|    |    |    |    +--- com.android.support:support-compat:27.1.1 (***)</pre><p>As you can see in there, the react-native-code-push dependency is relying on React Native, which itself is relying on com.android.support:appcompat-v7 which itself relies on com.android.support:support-core-utils</p><p>This is all nice and good, as long as either:</p><ul><li>all your dependencies and third party librairies depend on pre-AndroidX name spaces (ie. com.android.support...)</li></ul><p>OR</p><ul><li>all your dependencies rely on AndroidX name spaces (i.e. androidx.appcompat...)</li></ul><p>What happened to us was that we found ourselves pushed into a state where we had dependencies that were using a mix of the two.</p><h3><strong>How is started going wrong</strong></h3><p>So what happened ? Well, without going into too much detail, we needed to upgrade some of our librairies in order to fix some bugs.The versions we needed had started using AndroidX behind the scene, and that got us into this fated position.</p><p>I think this will also happen to a lot of people migrating to React Native 59 (or 60) and who will find that while React Native now uses AndroidX, some of your third party modules may still not support AndroidX.</p><p>What we started seeing initially was an error related to our AndroidManifest:</p><pre>ERROR: Manifest merger failed : Attribute application@appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0] AndroidManifest.xml:22:18-91<br> is also present at [androidx.core:core:1.0.0] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory).<br> Suggestion: add &#39;tools:replace=&quot;android:appComponentFactory&quot;&#39; to &lt;application&gt; element at manifestMerger4756582261911642725.xml:7:5-9:19 to override.</pre><p>As you can see here, the message is telling us that two librairies are trying to write into the same key of the Manifest, causing merger failed. You will also notice that the two librairies trying to write into the same key are pre-AndroidX and AndroidX but <em>they are in fact the same library</em> — hence the fact that they both try and do the same thing !</p><p>The only solution was to “pick a side” and force our project to use AndroidX name spaces. Thankfully Google has kind of thought of that, and provided a solution. Simply add these keys below into you android &gt; gradle.properties file:</p><pre><strong>android.useAndroidX</strong>=<strong>true<br>android.enableJetifier</strong>=<strong>true</strong></pre><p>In theory, what these lines of code do is “intercept” the old name spaces required by your project and third party modules, and swap them out with the new AndroidX name spaces. In other words, when building the dependency tree, it would “see” that com.android.support:support-compat is needed, and instead of loading it, it would load androidx.core.app . Great right?</p><p>Except the next step introduced a new problem:</p><pre>&gt; Task :@mapbox_react-native-mapbox-gl:compileReleaseJavaWithJavac</pre><pre>/Users/vsts/agent/2.153.2/work/1/s/node_modules/@mapbox/react-native-mapbox-gl/android/rctmgl/src/main/java/com/mapbox/rctmgl/utils/ResourceUtils.java:6: error: package android.support.v4.content does not exist</pre><pre>import android.support.v4.content.ContextCompat;</pre><pre>^</pre><pre>/Users/vsts/agent/2.153.2/work/1/s/node_modules/@mapbox/react-native-mapbox-gl/android/rctmgl/src/main/java/com/mapbox/rctmgl/components/camera/constants/CameraMode.java:3: error: package android.support.annotation does not exist</pre><pre>import android.support.annotation.IntDef;</pre><pre>^</pre><pre>/Users/vsts/agent/2.153.2/work/1/s/node_modules/@mapbox/react-native-mapbox-gl/android/rctmgl/src/main/java/com/mapbox/rctmgl/components/camera/constants/CameraMode.java:14: error: cannot find symbol</pre><pre>@IntDef({ FLIGHT, EASE, NONE })</pre><pre>^</pre><pre>symbol:   class IntDef</pre><pre>location: class CameraMode</pre><pre>/Users/vsts/agent/2.153.2/work/1/s/node_modules/@mapbox/react-native-mapbox-gl/android/rctmgl/src/main/java/com/mapbox/rctmgl/components/camera/CameraStop.java:4: error: package android.support.annotation does not exist</pre><pre>import android.support.annotation.NonNull;</pre><p>Now we had a different problem: the useAndroidX flag had made the swap dynamically, but some third party libraries, (installed via npm and linked using react-native link) were now explicitly calling modules that could no longer be found as they were not part of the project.</p><p>So if you navigated to the file node_modules/@mapbox/react-native-mapbox-gl/android/rctmgl/src/main/java/com/mapbox/rctmgl/utils/ResourceUtils.java you would indeed see :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*O4dHwhVHolzuJDrcHs8gwg.png" /></figure><p>So in that file we have two error messages:</p><ul><li>android.support.v4.content no longer exist, because it was swapped at build time by androidx.core.content . As a result you can’t import ContextCompat</li><li>return ContextCompat.getDrawable() obviously doesn’t work either</li></ul><p>If you were to replace the import with (again you can find the mapping of old name / new name <a href="https://developer.android.com/jetpack/androidx/migrate">here</a>):</p><pre>import androidx.core.content.ContextCompat;</pre><p>Everything would be fine.</p><p>OK, so the problem is clear : you need to update the code of your third party librairies in order to get the project to build. So our options were:</p><ul><li>make sure you use the latest version of your librairies, as some may already support AndroidX: we did that and that solved some issues.</li><li>for the librairies that don’t have a version that supports AndroidX, get the developers to update their librairies to support AndroidX. Well for some we would be waiting weeks, for others months. Not really a valid strategy</li><li>Manually find all the Java files that specifically import pre-AndroidX librairies, and change the code to use the new AndroidX name spaces.</li></ul><h3>Bash to the rescue</h3><p>While option 3 works fine, albeit it’s a time consuming, painstaking job, it doesn’t really scale.</p><p>We don’t build our apks manually, we use AppCenter to do that, so already that’s a blocker. AppCenter performs a clean npm install before every build, so re-writing the code inside node_modules works locally but not in the CI environment.</p><p>Also, we work in a team, and we don’t want to have to re-write our node_module code on every single machine.</p><p>Plus every time you have to do an npm install, you’d overwrite your changes and have to do it all over again.</p><p>So we had to find a way of doing this in an automated fashion, that could be used in the CI environment. And as is always the case, a bash script ended up being the preferred option. Ultimately, all there is to do is a search and replace. If you look at the mapping table, it’s pretty straighforward:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*PeLPYbaucLo8acYbtm-O_A.png" /><figcaption>AndroidX mapping table</figcaption></figure><p>What we need is to find the values in the left column of the table of old names (see full list <a href="https://developer.android.com/jetpack/androidx/migrate">here</a>), and replace them with the new value given in the new name column. Plus we know that the imports only happens in .java files, that (in 99.9% of cases) are found in node_modules/.../android/.. file structure.</p><p>One thing to note though, is that the table of names given by Google is long: it has nearly 2,000 entries. So searching for every single name would take ages. Plus we knew from our error messages in the build stage that we were only needing to search for a few specific strings.</p><p>So what we did was:</p><ul><li>We manually fixed the errors by replacing the imports in the node_modules files one at a time (sounds hideous but only took 1 hour or so)</li><li>we wrote down all the artifcats that were being imported using old names</li><li>we wrote a list of of old name -&gt; new name in a txt file</li><li>We then wrote the script below, to search and replace these strings in our project</li></ul><pre>#!/bin/bash</pre><pre>for f in $(find node_modules -wholename &quot;*/android/*.java&quot;);</pre><pre>do</pre><pre>   cat androidxNodeModuleReplaceList.txt| while read line || [ -n   &quot;$line&quot; ]</pre><pre>   do</pre><pre>      if grep -q $(echo $line | sed &#39;s/\/.*//&#39;) $f;</pre><pre>         then</pre><pre>         sed s/$line/g $f &gt; $f.new &amp;&amp; mv $f.new $f</pre><pre>         echo &quot;$f &gt;&gt; $line \n&quot;</pre><pre>      fi</pre><pre>   done</pre><pre>done</pre><p>This simple script does what it says on the tin: search .java files under node_module/../android/..<br>When it finds a file, it searches for any key present in our reference file called androidxNodeModuleReplaceList.txt . Replace the old string with the new one. Console log the replacement and move on.</p><p>For reference, here is our androidxNodeModuleReplaceList.txt:</p><pre>android.support.v4.content.ContextCompat/androidx.core.content.ContextCompat<br>android.support.annotation.IntDef/androidx.annotation.IntDef<br>android.support.annotation.NonNull/androidx.annotation.NonNull<br>android.support.annotation.Nullable/androidx.annotation.Nullable<br>android.support.v4.app.NotificationManagerCompat/androidx.core.app.NotificationManagerCompat<br>android.support.v4.app.NotificationCompat/androidx.core.app.NotificationCompat<br>android.support.v4.content.res.ResourcesCompat/androidx.core.content.res.ResourcesCompat<br>android.support.annotation.RequiresApi/androidx.annotation.RequiresApi<br>android.support.v4.app.ActivityCompat/androidx.core.app.ActivityCompat<br>android.support.v4.content.FileProvider/androidx.core.content.FileProvider<br>android.support.v4.net.ConnectivityManagerCompat/androidx.core.net.ConnectivityManagerCompat<br>android.support.customtabs.CustomTabsIntent/androidx.browser.customtabs.CustomTabsIntent<br>android.support.v4.util.Pools/androidx.core.util.Pools<br>android.support.annotation.Keep/androidx.annotation.Keep<br>android.support.annotation.RequiresPermission/androidx.annotation.RequiresPermission<br>android.support.v4.content.LocalBroadcastManager/androidx.localbroadcastmanager.content.LocalBroadcastManager<br>android.support.v4.app.RemoteInput/androidx.core.app.RemoteInput<br>android.support.annotation.StyleRes/androidx.annotation.StyleRes<br>android.support.v7.app.AlertDialog/androidx.appcompat.app.AlertDialog<br>android.support.annotation.MainThread/androidx.annotation.MainThread</pre><p>Now, simply place the txt file at the root of the project, and place your bash script at the root of the project.</p><p>In order to build locally, you can run your bash script by simply calling in in the console. We called it appcenter-pre-build.sh so you would simply go to the command line and type ./appcenter-pre-build.sh and hit Enter. You will see that the script will replace many imports throughout the file structure.</p><h3>How to run it in AppCenter</h3><p>AppCenter provides Build Script facilities, something that is pretty common across the CI world, and will exist also in Circle CI and others.</p><p>For AppCenter to recognise your script, you need to give it a specific name, depending on where you want to call it. In our case, the script needs to run after npm install and before the build . This is why we used appcenter-pre-build.sh . You can see more documentation here: <a href="https://docs.microsoft.com/en-us/appcenter/build/custom/scripts/">https://docs.microsoft.com/en-us/appcenter/build/custom/scripts/</a></p><p>One thing to note though is that for your script to be taken into account, you will need to :</p><ul><li>commit your changes including your new files and push into your remote branch.</li><li>Login to AppCenter, and navigate to the build settings for this branch</li><li>You will have a visual indication that your script was recognise by seeing the little blue tick (see below)]</li><li>You still need to “Save” or “Save and Build”, even without making any changes, otherwise the script will not run. Bit weird but here you go..</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*jltvDvQ1Ul59jxPIQCzKfA.png" /><figcaption>AppCenter Build Settings</figcaption></figure><p>Et voila ! Your branch will now build and use the script. You can check the logs and should be able to see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Fz-5X7wkVyXQpuUrPDKjw.png" /><figcaption>AppCenter Build with pre build script</figcaption></figure><h3>Handling special cases</h3><p>There might be cases when updating the code of the Java files might not be enough. Typically, if you use react-native-image-crop-picker then you might have error messages related to the AndroidManifest.xml. This is because the library tries to insert some code in the main AndroidManifest.xml which references old classes:</p><pre>&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;</pre><pre>package=&quot;com.reactnative.ivpusic.imagepicker&quot;&gt;</pre><pre>&lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot; /&gt;</pre><pre>&lt;application&gt;</pre><pre>&lt;provider</pre><pre>android:name=&quot;android.support.v4.content.FileProvider&quot;</pre><pre>android:authorities=&quot;${applicationId}.provider&quot;</pre><pre>android:exported=&quot;false&quot;</pre><pre>android:grantUriPermissions=&quot;true&quot;&gt;</pre><pre>&lt;meta-data</pre><pre>android:name=&quot;android.support.FILE_PROVIDER_PATHS&quot;</pre><pre>android:resource=&quot;@xml/provider_paths&quot; /&gt;</pre><pre>&lt;/provider&gt;</pre><pre>&lt;activity</pre><pre>android:name=&quot;com.yalantis.ucrop.UCropActivity&quot;</pre><pre>android:theme=&quot;@style/Theme.AppCompat.Light.NoActionBar&quot; /&gt;</pre><pre>&lt;/application&gt;</pre><pre>&lt;/manifest&gt;</pre><p>As you can see, the provider key is using android:name=&quot;android.support.v4.content.FileProvider&quot;</p><p>As mentioned above, this reference will not work once useAndroidX has been set to true, and so the build will work, but when installing the app on a device or simulator, you might run into this message:</p><pre>E/AndroidRuntime: FATAL EXCEPTION: main<br>    Process: net.communityapp, PID: 5107<br>    java.lang.RuntimeException: Unable to get provider android.support.v4.content.FileProvider: java.lang.ClassNotFoundException: Didn&#39;t find class &quot;android.support.v4.content.FileProvider&quot; on path: DexPathList[[zip file &quot;/data/app/&lt;your-app-id&gt;-EANMnjI7DZQI_uIRCAQ7Sg==/base.apk&quot;, zip file &quot;/data/app/net</pre><p>Again, the error about classes not being found..</p><p>This issue is actually fairly simple to resolve. Android provides tools that help you manipulate the data that is being inserted in the Manifest by the different librairies, and offers tool to handle that data.</p><p>In our case, all you need to do is use xmlns:tools=”http://schemas.android.com/tools&quot; in your manifest, and force the use of the new AndroidX name space in the Manifest.</p><p>To do this, insert this piece of code in your Manifest:</p><pre>&lt;!-- Necessary to override the react-native-image-croper Manifest which still references the old android.support... instead of androidx... --&gt;</pre><pre>&lt;!-- Remove whenever that library gets updated to androidx --&gt;</pre><pre>&lt;provider</pre><pre>android:name=&quot;androidx.core.content.FileProvider&quot;</pre><pre>android:authorities=&quot;${applicationId}.provider&quot;</pre><pre>android:enabled=&quot;true&quot;</pre><pre>android:exported=&quot;false&quot;</pre><pre>android:grantUriPermissions=&quot;true&quot;</pre><pre>tools:replace=&quot;android:name&quot;&gt;</pre><pre>&lt;meta-data</pre><pre>android:name=&quot;android.support.FILE_PROVIDER_PATHS&quot;</pre><pre>android:resource=&quot;@xml/provider_paths&quot; /&gt;</pre><pre>&lt;/provider&gt;</pre><p>This can be added just before the closing &lt;/application&gt; tag in your Manifest. What this does is specify a provider key which uses the AndroidX reference. You will also need to make sure that your Manifest references the “tools” :</p><pre>&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;</pre><pre><strong>xmlns:tools=&quot;http://schemas.android.com/tools&quot;</strong></pre><pre>package=&quot;net.communityapp&quot;&gt;</pre><p>There is more detail about tools related to AndroidManifest files here: <a href="https://developer.android.com/studio/build/manifest-merge">https://developer.android.com/studio/build/manifest-merge</a></p><h3>Conclusion</h3><p>While this solution “works” and got us to build and deploy again, it’s only mean to be a temporary fix.</p><p>We’ll keep a close eye on the updates released by the various third party librairies we use, and try and slowly get rid of the script altogether.</p><p>Hopefully it’s helpful to you, and if you have questions, or suggestions for improvement, please let me know ! We’re still fairly new to React Native so maybe there are better, more efficient ways to deal with this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf4df7ea0dd2" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/react-native-how-to-handle-an-app-with-both-pre-androidx-and-androidx-dependencies-rn60-bf4df7ea0dd2">React Native — How to handle an app with both pre-AndroidX and AndroidX dependencies (RN60)</a> was originally published in <a href="https://itnext.io/">ITNEXT</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 manage multiple environments (Dev/Staging/Prod) for Firebase with React Native App +…]]></title>
            <link>https://medium.com/@gregoire.frileux/how-to-manage-multiple-environments-dev-staging-prod-for-firebase-with-react-native-app-205c7c1a5e35?source=rss-8a9686e6b00a------2</link>
            <guid isPermaLink="false">https://medium.com/p/205c7c1a5e35</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[appcenter]]></category>
            <dc:creator><![CDATA[Gregoire Frileux]]></dc:creator>
            <pubDate>Wed, 17 Apr 2019 10:46:33 GMT</pubDate>
            <atom:updated>2019-04-17T10:46:33.742Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*4HERm70C936_UHOkqwwh3A.jpeg" /></figure><p>How to manage multiple environments (Dev/Staging/Prod) for Firebase with React Native App + AppCenter</p><p>Recently, we decided to add Firebase to our project. We are building a React Native App, deploying across both iOS and Android, and also using App Center for CI and pushing the builds to the relevant App Store.</p><p>While the Firebase documentation explains how to deploy the SDK for <a href="https://firebase.google.com/docs/ios/setup">iOS</a> and <a href="https://firebase.google.com/docs/android/setup">Android</a> reasonably well, one element was missing: how do you make sure there is no data pollution between the Dev / Staging / Prod environment?</p><p>We have a small team of developers, but the amount of traffic generated during testing by the dev team is enough to skew the data that shows up in Firebase Analytics, and obviously this was something that needed to be addressed.</p><p>After much consideration and research, we went down the route of creating multiple projects in Firebase, and I will now go into the Setup we ended up choosing. For the sake of clarity, I will only use 2 environments in this tutorial: dev and prod.</p><ol><li><strong>Create your Firebase projects and download the relevant files</strong></li></ol><p>This step is well documented in the Firebase doc. Simply click the big blue button, and give your project a name, for example “My Project — DEV”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*vQpPE8-q-tbNwgYFCMURVg.png" /></figure><p>The next Step is to add your apps to this dev project.</p><p>Simply click the corresponding logo in the header of your project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*aljCei-MkrYmlBWiGQ0OTg.png" /></figure><p>Fill in the relevant information (your package name mostly), then download and save locally the GoogleService-Info.plist for iOS, and the google-services.json for Android.</p><p><strong>Do not add the files to your project structure just yet</strong>, we will be doing this in the next phase. <strong>However, you can execute the steps to add the SDK to your code base as recommended by the Wizard</strong>.</p><p>The next step is to repeat the same thing for your production project: create a Firebase project, add both apps to it, and download both files locally. Make sure you keep track of which is which !</p><p><strong>2. Add the files to your project</strong></p><p>OK, so you should have added some code to your android and ios folders, in order to add the SDK to your app, however we still need to add the files in the right place, and manage the logic to load the correct one depending on the environment.</p><ul><li>Android: this part is fairly easy. In you android folder, navigate to the /app/src folder, and create two new folders called debug and release and then simply add the correct google-services.json file you previously got from Firebase in the correct folder. Your project structure should look something like this when viewed in Android Studio:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*zz5FmQ4v3GgLkOIXtIPU2g.png" /></figure><p>During the build, the Firebase library will parse the correct file depending on which flavour is being built (debug when running the app in the Simulator, release when building for deployment). More details <a href="https://firebase.google.com/docs/projects/multiprojects">here</a>.</p><ul><li>iOS: this part is a little bit more interesting. In the Firebase documentation (link just above), they suggest either associating a file to target, or naming the files differently and using a build script to pick the correct file. I’ve actually opted for a slightly different implementation. The idea is to follow a similar file structure to the one deployed for Android, and use a build script to copy the correct file in the build folder. This allows us to achieve the desired behavior of using the dev file when running in the Simulator, and using the prod file when building for device. As we will see later in this article, it also helps with using the correct file when building on App Center.<br>So how do we do this ? First, locate ios folder in your React Native project. Inside, create a folder called Firebase and two sub folders called Dev and Prod (you can pick any name here, you’ll simply need to make sure you use the right name in the bash scrips below).<br>Once you have created these folders, move the files GoogleService-Info.plist downloaded earlier from Firebase .</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*i1PvHS2JtzDPgaLGi7KStA.png" /></figure><ul><li>Then, you will want to open Xcode, and drag (from a Finder window) your newly created Firebase folder into the project structure. This will prompt Xcode to ask if the files should be copied and added to a particular target. You want to untick “Copy items if needed” and also we don’t want to add the files to any target. The popup should look as below:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*fBl4IFYAbLWRB45IOPoXqQ.png" /></figure><ul><li>Once you are finished, you will have a project structure in Xcode that will look like this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*PlYWXA3e2LE8X5kb7mz7Hg.png" /></figure><ul><li>OK, so now the files are added to the project, but they are not linked to any target, so they won’t be added to the build. In order to make this happen, we will implement a script in the Build Phases. To do that, use Xcode and click on your application target, then navigate to the Build Phases tab. Add a new step:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*1BIFTkjPHaJ-Zav64udHBg.png" /></figure><ul><li>Give this step a name, such as “Setup Firebase Environment GoogleService-Info.plis”, and then copy paste the script below (slightly modified from the version written by <a href="http://twitter.com/tyler">@tyler</a>.milner):</li></ul><pre># Name of the resource we&#39;re selectively copying<br>GOOGLESERVICE_INFO_PLIST=GoogleService-Info.plist</pre><pre># Get references to dev and prod versions of the GoogleService-Info.plist<br># NOTE: These should only live on the file system and should NOT be part of the target (since we&#39;ll be adding them to the target manually)<br>GOOGLESERVICE_INFO_DEV=${PROJECT_DIR}/Firebase/Dev/${GOOGLESERVICE_INFO_PLIST}<br>GOOGLESERVICE_INFO_PROD=${PROJECT_DIR}/Firebase/Prod/${GOOGLESERVICE_INFO_PLIST}</pre><pre># Make sure the dev version of GoogleService-Info.plist exists<br>echo &quot;Looking for ${GOOGLESERVICE_INFO_PLIST} in ${GOOGLESERVICE_INFO_DEV}&quot;<br>if [ ! -f $GOOGLESERVICE_INFO_DEV ]<br>then<br>echo &quot;No Development GoogleService-Info.plist found. Please ensure it&#39;s in the proper directory.&quot;<br>exit 1<br>fi</pre><pre># Make sure the prod version of GoogleService-Info.plist exists<br>echo &quot;Looking for ${GOOGLESERVICE_INFO_PLIST} in ${GOOGLESERVICE_INFO_PROD}&quot;<br>if [ ! -f $GOOGLESERVICE_INFO_PROD ]<br>then<br>echo &quot;No Production GoogleService-Info.plist found. Please ensure it&#39;s in the proper directory.&quot;<br>exit 1<br>fi</pre><pre># Get a reference to the destination location for the GoogleService-Info.plist<br>PLIST_DESTINATION=${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app<br>echo &quot;Will copy ${GOOGLESERVICE_INFO_PLIST} to final destination: ${PLIST_DESTINATION}&quot;</pre><pre># Copy over the prod GoogleService-Info.plist for Release builds<br>if [ &quot;${CONFIGURATION}&quot; == &quot;Release&quot; ]<br>then<br>echo &quot;Using ${GOOGLESERVICE_INFO_PROD}&quot;<br>cp &quot;${GOOGLESERVICE_INFO_PROD}&quot; &quot;${PLIST_DESTINATION}&quot;<br>else<br>echo &quot;Using ${GOOGLESERVICE_INFO_DEV}&quot;<br>cp &quot;${GOOGLESERVICE_INFO_DEV}&quot; &quot;${PLIST_DESTINATION}&quot;<br>fi</pre><ul><li>You will need to move this step immediately after the one called Link Binary With Libraries as shown below:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*HbQH0k7YnGYrNE1ER8WbNg.png" /></figure><ul><li>Make sure that your app builds without errors, and run some tests to ensure that depending on the build type you are using. The article written <a href="https://medium.com/rocket-fuel/using-multiple-firebase-environments-in-ios-12b204cfa6c0">here</a> has some good tips on debugging and verifying that the right file has been used in your build.</li></ul><p>OK, so that was quite a lot of work, but hopefully by now, you should have 2 projects in Firebase, 2 files for Android and iOS, and your React Native app should build on both platforms without errors, and send data to the correct Firebase project depending on the build type.</p><p>However, we wanted to go one step further. Indeed the issue with the setup above is this:</p><ul><li>When the app is build for the Simulator, by developers working locally, iOS and Android will use the dev files, and data will be sent to the Firebase dev account =&gt; GREAT!</li><li>When the app is built on AppCenter, it will use the prod file, and send data to the Firease Prod account =&gt; NOT SO GREAT ! Why? Because when the appis built on the develop branch, for testing by the internal team, we would still want the data to be sent to the Firebase DEV account. Only when the app is built on the master branch, do we want to use the Firebase prod files, and send data to the Firebase Prod account.</li></ul><p><em>(Note: I am assuming that you’re using a similar Git structure on your project: feature branches get merged in </em><em>develop for testing locally on real devices. Whenever we plan a release, we merge on </em><em>master and our branch builds with all the live certs and keys, and deploys the build to the iOS AppStore and Android Store directly from AppCenter).</em></p><p>So how do we do that ?</p><p><strong>3. Making sure the AppCenter build uses the correct dev/staging/prod files</strong></p><p>AppCenter has a concept of <a href="https://docs.microsoft.com/en-us/appcenter/build/custom/scripts/">Build Scripts</a> which is very useful. We already use them to inject the live API Keys and Environment Variables in our React Native project on master. They are very powerful and simple to use.</p><p>For the purpose of this tutorial, we decided to use a simple trick: using the appcenter-post-clone script to overwrite the production file with the dev files on all branches except master.</p><p>It’s a little bit of a cheat, but it works really well, and plugs in to the work we’ve done above. On any branch other than master, immediately after the files are copied from Bitbucket/Git, AppCenter will run this script. It will copy the dev file (the google-service.json for Android and the GoogleService-Info.plist for iOS) and paste it into the prod folder.</p><p>Then, when the build runs on both platforms, it will use a release build flavour, using the prod Firebase file, but since it was overwritten by the dev one, it will contain all the dev values. You end up with an ipa and apk that uses your dev Firebase file, and therefore all the Analytics data will be sent to the Firebase DEV account.</p><p>The Script itself is really easy:</p><pre>#!/usr/bin/env bash</pre><pre>set -e<br>set -x</pre><pre>echo &quot;$APPCENTER_BRANCH&quot;</pre><pre>if [ &quot;$APPCENTER_BRANCH&quot; == &#39;master&#39; ]; then</pre><pre>#here you can do stuff for master, like injecting keys, etc.</pre><pre>else</pre><pre>echo &#39;copying iOS Dev Firebase file into Prod folder, so analytics uses the Dev file&#39;</pre><pre>cp -rf &quot;ios/Firebase/Dev/GoogleService-Info.plist&quot; &quot;ios/firebase/Prod&quot;</pre><pre># we do the same for Android</pre><pre>echo &#39;copying Android debug Firebase file into release folder, so analytics uses the Dev file&#39;</pre><pre>cp -rf &quot;android/app/src/debug/google-services.json&quot; &quot;android/app/src/release/google-services.json&quot;</pre><pre>fi</pre><p>If you decided to modify the file names, or the folder structure in the previous steps, you’ll obviously want to amend the script to match your setup.</p><p>This script can simply be added to a file called appcenter-post-clone.sh and have that file at the root of your React Native Project as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*QYJvMIjXup51bZKiughY0w.png" /><figcaption>AppCenter post clone script</figcaption></figure><p>AppCenter will automatically detect the file and run it on every build.</p><p>Note: you can test your bash script easily bu running sh appcenter-post-clone.sh in your terminal. You should see it change the files in your project accordingly.</p><p>At this point, everything will work and you will have a clean, separated environment in Firebase, with your analytics cleanly separated in two different projects. If you want to add more environments, such as Staging, QA, etc, you should be able to adapt the tactics above to match your needs.</p><p><em>One thing I noticed on Android, was that the Firebase setup was sometimes a bit buggy. There were cases when I created a project (say the DEV one for example), and added the SDK, added the file, etc. but still Firebase wouldn’t see the data coming in. This was really weird, because when running the App in a simulator in debug mode, I could see the analytics events being fired, and using the correct app ids. What helped was to do a single build and run of the app with the dev file at the root of </em><em>/android/app/src . After building and running the app in a simulator once, I could then remove the file, and keep the folder structure as described, and everything would work, i.e. Firebase would start showing me the data in the UI. I’m not entirely sure if this was a bug or not, but just thought I would add the note anyway.</em></p><p><strong>Conclusion</strong></p><p>I hope this was helpful, and please don’t hesitate to comment to tell me what you thoughts. I am pretty sure this can be improved and streamlined so please do contribute and I will update the article.</p><p>Having a clean set of data is absolutely essential for building a successful app, so I felt like the time spent on this was worthwhile and I hope it will be helpful to others.</p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=205c7c1a5e35" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>