<?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 Rafiul Ansari on Medium]]></title>
        <description><![CDATA[Stories by Rafiul Ansari on Medium]]></description>
        <link>https://medium.com/@rafiulansari?source=rss-5a47494c562a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qTX7iJ8QgM80x917ChrG2w.jpeg</url>
            <title>Stories by Rafiul Ansari on Medium</title>
            <link>https://medium.com/@rafiulansari?source=rss-5a47494c562a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 16:59:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rafiulansari/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[Building a React Native App: Part V, Authentication Using AWS Cognito]]></title>
            <link>https://towardsaws.com/building-a-react-native-app-part-v-authentication-using-aws-cognito-fa88f4608b51?source=rss-5a47494c562a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa88f4608b51</guid>
            <category><![CDATA[cognito]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Rafiul Ansari]]></dc:creator>
            <pubDate>Sun, 19 Jun 2022 12:02:03 GMT</pubDate>
            <atom:updated>2022-06-21T02:42:32.590Z</atom:updated>
            <content:encoded><![CDATA[<p>Before I construct the authentication logic, I make sure that I have the UI for login, registration, and password reset in place.</p><p>Here’s what I’ll be building:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*fGxYtPLen32cnIf_gsUBXw.gif" /><figcaption>Registration</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*fN3bKTj1QK-OVxdLr01rjw.gif" /><figcaption>Login</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ZLpLj11A2sQ1VlaNqVnOCg.gif" /><figcaption>Reset Password</figcaption></figure><h3>AWS Console</h3><p>To start off, I go to the AWS console and head over to the Cognito service. With ‘Add user directories to your app’ as my business case, I click ‘Create user pool’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VGwE2AQAmWoakxLgn2QAgQ.png" /></figure><p>I leave ‘Cognito user pool’ as the default selected provider type but select ‘Email’ as my only Cognito user sign-in option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJBzTv8L3Ex82YpMFvelHw.png" /></figure><p>Then I define my password policy and opt-out of MFA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q3hK8oILFyBukM0cJiNCZg.png" /></figure><p>Leave the default selected options in the next screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3YOvHYOHIg2AdHoz19Uy-A.png" /></figure><p>Opt for ‘Send email with Cognito’ as my email provider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H29z_EoAADGZQu9iTsqa-A.png" /></figure><p>I opt out of Cognito Hosted UI, hit ‘Next’ and then click ‘Create user pool’ in the review screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pqkF7MJ8rXJ4MweBQIUqtA.png" /></figure><p>After the user pool has been created, I need to change the verification message type from a code to a link by heading to the ‘Messaging’ tab and clicking ‘Verification message’ and then ‘Edit’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nLk30ucdi2UUY_BleVf9og.png" /></figure><h3>Frontend Helpers</h3><p>You know the drill, packages. In this case we only need one. Run yarn add <a href="https://www.npmjs.com/package/amazon-cognito-identity-js">amazon-cognito-identity-js</a> and then react-native link amazon-cognito-identity-js .</p><p>Now, in the project’s root directory, I create a file called env-vars.js which will store my environment variables. I get these values from the AWS console. The USER_POOL_ID is available in the user pools dashboard and the CLIENT_ID under ‘App integration’ after I click on my user pool.</p><blockquote>Note: The values below are not real</blockquote><pre>export const USER_POOL_ID = ‘eu-west-2_q6RAfoZDT’;<br>export const CLIENT_ID = ‘7bo4i41opy3hsopl3tip1j1il5’;</pre><p>And then add this file to my .gitignore so that I don’t commit it to my repo where it would be visible to the public.</p><pre># etc.<br>etc.</pre><pre># Secrets<br>env-vars.js</pre><p>In the src folder, I create a utils folder and then a file named cognito-pool.js. This file will return a CognitoUserPool object for my specific user pool.</p><pre>import {CognitoUserPool} from ‘amazon-cognito-identity-js’;<br>import {USER_POOL_ID, CLIENT_ID} from ‘../../env-vars’;</pre><pre>const poolData = {<br>  UserPoolId: USER_POOL_ID,<br>  ClientId: CLIENT_ID,<br>};</pre><pre>export const cognitoPool = new CognitoUserPool(poolData);</pre><p>In the same directory, I create a file called regex.js. This file will contain my app’s regex patterns that I’ll use to validate user inputs.</p><pre>export const emailRegex = /^\S+@\S+\.\S+$/;</pre><h3>Registration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*fGxYtPLen32cnIf_gsUBXw.gif" /></figure><p>As the first and second parameters, I pass the TextInput values email and password (stored in a state). And then in the callback function, if the signup failed, I use a switch case to handle error messages; otherwise I navigate to the login screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mF3ZAfOVksaul9izpsGSRg.png" /></figure><pre>import {cognitoPool} from &#39;../../utils/cognito-pool&#39;;</pre><pre>// Irrelevant code removed<br>// See repo at the bottom of this article for the full code</pre><pre>const onPressRegister = () =&gt; {<br>  cognitoPool.signUp(email, password, [], null, (err, data) =&gt; {<br>    if (err) {<br>      switch (err.name) {<br>        case ‘InvalidParameterException’:<br>          return Alert.alert(General.Error, Auth.InvalidEmail);<br>        case ‘InvalidPasswordException’:<br>          return Alert.alert(General.Error, Auth.InvalidPassword);<br>        case ‘UsernameExistsException’:<br>          return Alert.alert(General.Error, Auth.EmailAlreadyExists);<br>        default:<br>          return Alert.alert(General.Error, General.SomethingWentWrong);<br>      }<br>    }</pre><pre>    Alert.alert(General.Success, Auth.ConfirmEmail, [<br>      {text: ‘OK’, onPress: () =&gt; navigation.navigate(‘login’)},<br>    ]);<br>  });<br>}</pre><h3>Login</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*fN3bKTj1QK-OVxdLr01rjw.gif" /></figure><p>I start off by creating my CognitoUser and AuthenticationDetails objects and then authenticating the former using the latter. If the user is successfully authenticated, I store the refreshToken from the response on the device using AsyncStorage. The reason being, to automatically authenticate returning users who have already logged in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kslADkEGnUK0yzDiOkaVVg.png" /></figure><blockquote>Note: setUser is setting the user state in my useGlobal context layer. This saves me creating a new CognitoUser object in other screens e.g. the reset password screen, as we’ll soon see.</blockquote><pre>import AsyncStorage from &#39;@react-native-async-storage/async-storage&#39;;<br>import {CognitoUser, AuthenticationDetails} from &#39;amazon-cognito-identity-js&#39;;</pre><pre>import {cognitoPool} from &#39;../../utils/cognito-pool&#39;;</pre><pre>// Irrelevant code removed<br>// See repo at the bottom of this article for the full code</pre><pre>const onPressLogin = () =&gt; {<br>  const user = new CognitoUser({<br>    Username: email,<br>    Pool: cognitoPool,<br>  });<br>  setUser(user);</pre><pre>  const authDetails = new AuthenticationDetails({<br>    Username: email,<br>    Password: password,<br>  });</pre><pre>  user.authenticateUser(authDetails, {<br>    onSuccess: async res =&gt; {<br>      const token = res?.refreshToken?.token;<br>      await AsyncStorage.setItem(‘REFRESH_TOKEN’, token);<br>      <br>      setTimeout(() =&gt; {<br>        navigation.navigate(‘main’);<br>      }, 350);<br>    },</pre><pre>    onFailure: err =&gt; {<br>      switch (err.name) {<br>        case ‘UserNotConfirmedException’:<br>          return Alert.alert(General.Error, Auth.UserNotConfirmed);<br>        case ‘NotAuthorizedException’:<br>          return Alert.alert(General.Error, Auth.IncorrectCredentials);<br>        default:<br>          return Alert.alert(General.Error, General.SomethingWentWrong);<br>      }<br>    },<br>  });<br>};</pre><p>When the screen is first rendered, I fetch the refreshToken, if there is any. And then in the sync call, if currentUser exists, I get the sessionToken and if that token matches the previously stored token, the user can navigate to their home screen without having to log in.</p><pre>// Irrelevant code removed<br>// See repo at the bottom of this article for the full code</pre><pre>useEffect(() =&gt; {<br>  getSession();<br>}, []);</pre><pre>const getSession = useCallback(async () =&gt; {<br>  const storageToken = await AsyncStorage.getItem(‘REFRESH_TOKEN’);</pre><pre>  cognitoPool.storage.sync(function (err, res) {<br>    if (res !== ‘SUCCESS’) return;<br>   <br>    const user = cognitoPool.getCurrentUser();<br>    if (!user) return;</pre><pre>    user.getSession((err, session) =&gt; {<br>      if (err) return;<br>    <br>      const sessionToken = session?.refreshToken?.token;<br>      if (sessionToken === storageToken) navigation.navigate(‘main’);<br>    });<br>  });<br>}, []);</pre><blockquote>Note: The refreshToken’s validity period can be adjusted via the AWS console. By default, it’s set to 30 days.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2FRVr_7qzz1gStPP_cQwsg.png" /></figure><h3>Reset Password</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ZLpLj11A2sQ1VlaNqVnOCg.gif" /></figure><p>When a user requests a password reset email, I call the forgotPassword method. On success, I navigate to the reset password screen where they can input the verification code that was emailed to them and their new password.</p><blockquote>Note: I create a CognitoUser object here again because in my case, it’s still part of the same screen i.e. the button for requesting a password reset email is in a modal on the login screen.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4YWNoeKPvo7IxUT3ogaNPw.png" /></figure><pre>// Irrelevant code removed<br>// See repo at the bottom of this article for the full code</pre><pre>const onPressSendEmail = () =&gt; {<br>  const user = new CognitoUser({<br>    Username: resetEmail,<br>    Pool: cognitoPool,<br>  });<br>  setUser(user);</pre><pre>  user.forgotPassword({<br>    onSuccess: res =&gt; {<br>      Alert.alert(General.Success, Auth.ResetEmailSent, [<br>        {<br>          text: ‘OK’,<br>          onPress: () =&gt; {<br>            setModalVisible(false);<br>            setTimeout(() =&gt; {<br>              navigation.navigate(‘reset-password’);<br>            }, 500);<br>          },<br>        },<br>      ]);<br>    },</pre><pre>    onFailure: err =&gt; {<br>      Alert.alert(General.Error, General.SomethingWentWrong, [{text: ‘OK’}]);<br>    },<br>  });<br>};</pre><p>I then call the confirmPassword method by passing the verificationCode and new password as the first and second parameters. In the callback function, if the password change succeeds, I show an alert which will navigate to the login screen when the OK button is pressed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FAUIdFkleY-S-6-r7Ic2ng.png" /></figure><pre>// Irrelevant code removed<br>// See repo at the bottom of this article for the full code</pre><pre>const onPressChangePassword = () =&gt; {<br>  user.confirmPassword(verificationCode, password, {<br>    onSuccess: res =&gt; {<br>      Alert.alert(General.Success, Auth.PasswordChanged, [<br>        {<br>          text: ‘OK’,<br>          onPress: () =&gt; {<br>            navigation.reset({<br>              index: 0,<br>              routes: [{name: ‘login’}],<br>            });<br>          },<br>        },<br>      ]);<br>    },<br>   <br>    onFailure: err =&gt; {<br>      Alert.alert(General.Error, err.message);<br>    },<br>  });<br>};</pre><p>In the future I’d like to add Google sign-in via Cognito but for now, that’s everything! In the next article of this series, I’ll cover AWS AppSync.</p><blockquote>Tip: Press and hold the clap button 😉</blockquote><p><a href="https://github.com/raf723/three-good-things/tree/feature/part-five">GitHub - raf723/three-good-things at feature/part-five</a></p><p>Thank you,<br>Raf</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa88f4608b51" width="1" height="1" alt=""><hr><p><a href="https://towardsaws.com/building-a-react-native-app-part-v-authentication-using-aws-cognito-fa88f4608b51">Building a React Native App: Part V, Authentication Using AWS Cognito</a> was originally published in <a href="https://towardsaws.com/">Towards AWS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a React Native App: Part IV, Onboarding Screens]]></title>
            <link>https://medium.com/@rafiulansari/building-a-react-native-app-part-iv-onboarding-screens-6ef48caefd6c?source=rss-5a47494c562a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ef48caefd6c</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[app-development]]></category>
            <dc:creator><![CDATA[Rafiul Ansari]]></dc:creator>
            <pubDate>Sat, 04 Jun 2022 12:51:16 GMT</pubDate>
            <atom:updated>2022-06-19T12:04:39.929Z</atom:updated>
            <content:encoded><![CDATA[<p>When the user first launches the app, I want to present a few screens which summarise the app’s capabilities and purpose. Every launch thereafter should present the login screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/1*Ybuf-nyYdRLRDE8kMza4iA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*VsaDh_sff6jdqpjT4fOPUg.gif" /></figure><blockquote>Note: I got my onboarding images for free from <a href="https://unsplash.com/">Unsplash</a></blockquote><h4>First things first, packages</h4><ul><li>yarn add <a href="https://github.com/react-native-async-storage/async-storage">@react-native-async-storage/async-storage</a> - in order to remember whether a user has already been through the onboarding flow, I need to store a value which indicates this on the device. Async storage is a key-value storage system that will allow me to do exactly this.</li><li>yarn add <a href="https://github.com/DylanVann/react-native-fast-image">react-native-fast-image</a> - a replacement for React Native’s Image component but more performant with better cache control.</li><li>yarn add <a href="https://github.com/oblador/react-native-vector-icons">react-native-vector-icons</a> - add free icons to the UI.</li></ul><blockquote>Note: Always add packages in separate commits and relaunch the app after each addition to check that everything is okay</blockquote><p>For the last package, I couldn’t get it to work following the provided installation instructions. So for iOS, after running the yarn add command, I added the package’s font file names to my Info.plist and then ran pod install from the ios folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SIipXX8mA9caFK5-MKSIXg.png" /></figure><p>For Android, I added following line of code to the end of my android/app/build.gradle file.</p><pre>apply from: “../../node_modules/react-native-vector-icons/fonts.gradle”</pre><h4>Routing</h4><p>In app.js, I call the getStorage function (triggered by the useEffect on first render of the screen) which retrieves the value for the ONBOARDED key and then stores it in a state. This state is then passed down to the AppContainer component as a prop. The reason I do this here and not inside AppContainer is to minimise any lag.</p><pre>import React, {useState, useEffect, useCallback} from ‘react’;</pre><pre>import {NavigationContainer} from ‘@react-navigation/native’;<br>import {ScaleProvider} from ‘react-native-design-to-component’;<br>import {SafeAreaProvider} from ‘react-native-safe-area-context’;<br>import AsyncStorage from ‘@react-native-async-storage/async-storage’;</pre><pre>import {StyleProvider} from ‘./hooks/styles’;</pre><pre>import {AppContainer} from ‘./containers/app-container’;</pre><pre>const App = () =&gt; {<br>  const [onboarded, setOnboarded] = useState();</pre><pre>  // — — — — — — — — — — EFFECTS — — — — — — — — — — //<br>  useEffect(() =&gt; {<br>    getStorage();<br>  }, []);</pre><pre>  // — — — — — — — — — — ACTIONS — — — — — — — — — — //<br>  const getStorage = async () =&gt; {<br>    const onboarded = await AsyncStorage.getItem(‘ONBOARDED’);<br>    setOnboarded(JSON.parse(onboarded));<br>  };</pre><pre>  // — — — — — — — — — — RENDER — — — — — — — — — — //<br>  return (<br>    &lt;SafeAreaProvider&gt;<br>      &lt;ScaleProvider config={{height: 844, width: 390}}&gt;<br>        &lt;StyleProvider&gt;<br>          &lt;NavigationContainer&gt;<br>            &lt;AppContainer onboarded={onboarded} /&gt;<br>          &lt;/NavigationContainer&gt;<br>        &lt;/StyleProvider&gt;<br>      &lt;/ScaleProvider&gt;<br>    &lt;/SafeAreaProvider&gt;<br>  );<br>};</pre><pre>export default App;</pre><p>Now, in app-container.js for the Stack.Navigator, if the onboarded prop passed from AppContainer is true i.e. the user has completed the onboarding flow, the initial route will be the LoginScreen, otherwise it’ll be the OnboardingOneScreen.</p><pre>import React, {useState, useEffect, useCallback} from ‘react’;<br>import {createNativeStackNavigator} from ‘@react-navigation/native-stack’;</pre><pre>import {LoginScreen} from ‘../screens/auth/login-screen’;<br>import {OnboardingOneScreen} from ‘../screens/onboarding/onboarding-one-screen’;</pre><pre>const Stack = createNativeStackNavigator();</pre><pre>export const AppContainer = ({onboarded}) =&gt; {<br>  return (<br>    &lt;&gt;<br>      &lt;Stack.Navigator initialRouteName={onboarded ? &#39;login&#39; : &#39;onboarding-one&#39;}&gt;<br>        &lt;Stack.Screen<br>          name=”onboarding-one”<br>          component={OnboardingOneScreen}<br>          options={{<br>            headerShown: false,<br>          }}<br>        /&gt;<br>        &lt;Stack.Screen<br>          name=”login”<br>          component={LoginScreen}<br>          options={{<br>            headerShown: false,<br>          }}<br>        /&gt;<br>      &lt;/Stack.Navigator&gt;<br>    &lt;/&gt;<br>  );<br>};</pre><p>How do I set the onboarded prop to true once the user has completed the onboarding flow? In the fourth onboarding screen in the GIF at the top of this article, when I click the Finish button, here is the code I’m executing:</p><pre>const onPressFinish = async () =&gt; {<br>  await AsyncStorage.setItem(‘ONBOARDED’, ‘true’);<br>  navigation.navigate(‘login’);<br>};</pre><p>Now, the next time I launch the app, the ONBOARDED key from Async Storage will return true and so the initial route in the Stack.Navigator will be the LoginScreen.</p><h4>Side Notes</h4><p>I probably should have compressed my onboarding images before adding them to the project but I’ll leave as is for now and maybe I can have a section on optimisation towards the end. I’ve also decided to not use any form libraries for this project since I won’t have many user input fields. For cool things like the progress header animation, all of my code is available at:</p><p><a href="https://github.com/raf723/three-good-things/tree/feature/part-four">GitHub - raf723/three-good-things at feature/part-four</a></p><p>In the next part of this series, I’ll cover authentication using AWS Cognito and AWS AppSync.</p><p><a href="https://medium.com/@rafiulansari/building-a-react-native-app-part-v-authentication-using-aws-cognito-fa88f4608b51">Building a React Native App: Part V, Authentication Using AWS Cognito</a></p><blockquote>Tip: Press and hold the clap button 😉</blockquote><p>Thank you,<br>Raf</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ef48caefd6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a React Native App: Part III, App Icon and Splash Screen]]></title>
            <link>https://medium.com/@rafiulansari/building-a-react-native-app-part-iii-app-icon-and-splash-screen-a14505aa9036?source=rss-5a47494c562a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a14505aa9036</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[splash-screen]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[app-development]]></category>
            <dc:creator><![CDATA[Rafiul Ansari]]></dc:creator>
            <pubDate>Tue, 31 May 2022 21:30:51 GMT</pubDate>
            <atom:updated>2022-06-19T12:05:26.972Z</atom:updated>
            <content:encoded><![CDATA[<p>In part one of this series, I designed some of the app’s screens. Those same designs will form the basis of the app icon and splash screen in this article.</p><p><a href="https://medium.com/@rafiulansari/creating-a-react-native-app-part-i-laying-the-foundations-e6b81cd4f92">Building a React Native App: Part I, Laying the Foundations</a></p><h3>Display Name</h3><p>Traditional naming conventions aren’t kind when you have spaces in your app’s name. I’ll show you how to fix that. In app.json, I change the displayName property. For iOS, I change the value of the CFBundleDisplayName key in ios/ThreeGoodThings/Info.plist to &lt;string&gt;Three&amp;#x2007;Good&amp;#x2007;Things&lt;/string&gt; - where &amp;#x2007; represents a space. For Android, I just change the app_name string resource in android/app/src/main/res/values/strings.xml.</p><h3>App Icon</h3><p>A logo should be simple but meaningful. And it doesn’t need to be perfect the first time round. The logos of some of the most popular brands have been continuously evolving over time. Ferrari, Nike, Adidas, Coca-Cola, you name it. They’re also simple enough to draw; so much so that even a bad drawing of Airbnb or Tesla can still be recognised by the average person.</p><p>A few Google image searches of the word ‘three’ and eventually I stumble upon the mathematical symbol sigma, Σ. My thinking is that it can pass as a 3 that’s been flipped. And the deeper meaning is that in mathematics, sigma is a symbol that denotes the sum of numbers. Quite fitting for an app that emphasises looking back at many good things that have happened to you.</p><p>Once I have my icon, I use my <a href="https://coolors.co/palette/f4f2ee-e9e5dd-bab4ac-402e26-f8b44a">Coolors</a> palette to <a href="https://manytools.org/image/colorize-filter/">recolour</a> my icon. Download it, stick it on a square in PowerPoint, group the objects, right-click and save it as a PNG file and voila, I have my icon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*16qNHRFMlTwm6rYK44_KHQ.png" /></figure><p>Time to generate the logo assets for XCode and Android Studio. I open the project in XCode by running either xed ios in the terminal or heading to the ios folder of the project and opening the .xcworkspace file. Once I navigate to the AppIcon image, XCode shows me the image resolutions that are required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H1lU5W68KiOCjXoI5E6gbA.png" /></figure><p>Using a <a href="https://onlinepngtools.com/resize-png">PNG resizing tool</a>, I generate image files of my logo for each of the required resolutions, download them and drag and drop them into their respective boxes in XCode.</p><p>For Android, I open the android folder in Android Studio, right-click the res folder, select ‘New’ and then ‘Image Asset’. For the foreground layer, I locate the path of my logo and select ‘Yes’ for Trim. And for the background layer, I set the color to the background color of my logo.</p><blockquote>Note: Confirm any overwrites if prompted</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wrvu5Dc1kyvG9WDJ13mutw.png" /></figure><h3>Splash Screen</h3><p>There’s 2 types of splash screens - static and dynamic. The latter involving the use of animations. I’ll do both and then compare to see which one is more suitable. Anyway, a bit more PowerPoint and look, I have my splash screen image. Adobe who? 😎</p><blockquote>Note: The splash image background should be transparent</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nQESqdMjOn1X73Xf-bLerg.png" /></figure><p>I start off with yarn add <a href="https://www.npmjs.com/package/react-native-splash-screen">react-native-splash-screen</a> and follow the rest of the installation steps outlined in the link. I want this package because it allows me to programatically toggle the visibility of the splash screen.</p><h4><em>iOS</em></h4><p>Using the <a href="https://onlinepngtools.com/resize-png">PNG resizing tool</a>, I create 3 image resolutions and insert them into an image set in XCode.</p><blockquote>Note: A black splash screen can indicate that the image file sizes are too big</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cIsja1pmf0Btj5OOmjnFXw.png" /></figure><p>Then I head over to LaunchScreen.storyboard to create my splash screen. In the top right, I have a plus button which I can use to add things like an Image View or a Label. In the bottom right, I have a ‘Add New Constraints’ button which I use to set constraints, dimensions and ratios. The button to its left provides additional constraints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tniRw64nl5sY2gmHJwZk1A.png" /></figure><h4>Android</h4><p>In app/res/values, I create a Values Resource File named colors.xml and add my splash background color.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;resources&gt;<br>  &lt;color name=&quot;launcher_color&quot;&gt;#E9E5DD&lt;/color&gt;<br>&lt;/resources&gt;</pre><p>And in app/res/drawable, I drag and drop my splash image and name the file splash_logo. Now I can reference both of these files in app/res/layout, where I create a Layout Resource File named launch_screen.xml with the code below.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:background=&quot;@color/launcher_color&quot;<br>    android:orientation=&quot;vertical&quot;&gt;<br><br>    &lt;ImageView<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;0dp&quot;<br>        android:layout_alignParentStart=&quot;true&quot;<br>        android:layout_alignParentTop=&quot;true&quot;<br>        android:layout_alignParentEnd=&quot;true&quot;<br>        android:layout_alignParentBottom=&quot;true&quot;<br>        android:layout_marginStart=&quot;65dp&quot;<br>        android:layout_marginEnd=&quot;65dp&quot;<br>        android:scaleType=&quot;centerInside&quot;<br>        android:src=&quot;@drawable/splash_logo&quot; /&gt;<br>&lt;/RelativeLayout&gt;</pre><blockquote>Note: I had a bit of trouble with Android so check out the changes I made to MainActivity.java and MainApplication.java in <a href="https://github.com/raf723/three-good-things/commit/f750bf54646e0f61bc6a013244aa5d1f7f4e911a">this commit</a> for guidance.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*86woWIszB84O7PHIOqsupg.gif" /></figure><h4>Animated Splash Screen</h4><p>What if I wanted my splash image to fade in and move up? Like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*_MgUOyWS8wHPDEv32GSL9A.gif" /></figure><p>Luckily for us, an awesome chap (me) has already written a tutorial (below) on how to do this so I won’t go through the code again here. However, my code for both the static and dynamic splash screens will still be available in the Git repository posted at the bottom of this article.</p><p><a href="https://medium.com/@rafiulansari/react-native-animated-splash-screens-e3719671dab6">React Native Animated Splash Screens</a></p><p>Honest thoughts? I think the static splash screen looks a lot better so that’s what I’m going to go with. In the next part of this series, I’ll cover onboarding screens.</p><ul><li><a href="https://medium.com/@rafiulansari/building-a-react-native-app-part-iv-onboarding-screens-6ef48caefd6c">Building a React Native App: Part IV, Onboarding Screens</a></li><li><a href="https://github.com/raf723/three-good-things/tree/feature/part-three">GitHub - raf723/three-good-things at feature/part-three</a></li></ul><p>Thank you,<br>Raf</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a14505aa9036" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a React Native App: Part II, Project Setup]]></title>
            <link>https://medium.com/@rafiulansari/building-a-react-native-app-part-ii-project-setup-782917168e01?source=rss-5a47494c562a------2</link>
            <guid isPermaLink="false">https://medium.com/p/782917168e01</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Rafiul Ansari]]></dc:creator>
            <pubDate>Sat, 14 May 2022 12:16:31 GMT</pubDate>
            <atom:updated>2022-06-19T12:05:48.250Z</atom:updated>
            <content:encoded><![CDATA[<p>When setting up the development environment for a React Native app I have 2 choices - Expo CLI and React Native CLI. I’m going to go with the latter. Check out this <a href="https://fulcrum.rocks/blog/react-native-init-vs-expo/">link</a> for a brief comparison of the two. Whichever you choose, follow the <a href="https://reactnative.dev/docs/environment-setup">official docs</a> for setting up the development environment.</p><p>After I open the project, I test that everything works by running the application. Now it’s time to remove the unwanted code - I replace the contents of src/app.js with the code below. If it helps to follow along, the code for this article is available in the Git repository at the bottom of this article.</p><pre>import React from ‘react’;<br>import {Text, SafeAreaView} from ‘react-native’;</pre><pre>const App = () =&gt; {<br>  return (<br>    &lt;SafeAreaView style={{flex: 1, justifyContent: ‘center’,<br>alignItems: ‘center’}}&gt;<br>      &lt;Text&gt;Hello, World!&lt;/Text&gt;<br>    &lt;/SafeAreaView&gt;<br>  );<br>};</pre><pre>export default App;</pre><p>If you haven’t already, go ahead and read the first article of this series:</p><p><a href="https://medium.com/@rafiulansari/creating-a-react-native-app-part-i-laying-the-foundations-e6b81cd4f92">Building a React Native App: Part I, Laying the Foundations</a></p><h3>Dependencies</h3><p>I‘m going to add 2 packages using the yarn add [package name] command:</p><ul><li>yarn add <a href="https://www.npmjs.com/package/react-native-design-to-component">react-native-design-to-component</a> - provides scaling hooks to resize text and components for different devices.</li><li>yarn add <a href="https://www.npmjs.com/package/react-native-safe-area-context">react-native-safe-area-context</a> - allows me to handle safe area insets. Check out this really useful <a href="https://www.freecodecamp.org/news/how-to-use-safe-area-context-to-avoid-notches-in-react-native-apps/">doc</a> for more info.</li></ul><p>If you haven’t installed Yarn, take a look at their official installation guide <a href="https://yarnpkg.com/getting-started/install">here</a>. You can use npm too - just replace yarn add with npm install throughout this guide.</p><h3>Dictionary</h3><p>First, I create a file called dictionary.js inside src/hooks and add some strings categorised by screen. I’ll add more as the project progresses.</p><p><em>Check out this </em><a href="https://marketplace.visualstudio.com/items?itemName=zengxingxin.sort-js-object-keys"><em>VS Code extension</em></a><em> I use to keep my objects alphabetically ordered.</em></p><pre>export const enGB = {<br>  SignIn: {<br>    ForgotPassword: &#39;Forgot Password&#39;,<br>    SignIn: &#39;Sign In&#39;,<br>  },<br>  SignUp: {<br>    AlreadyRegistered: &#39;Already have an account? &#39;,<br>    SignInHere: &#39;Sign in here&#39;,<br>    SignUp: &#39;Sign Up&#39;,<br>  },<br>  ThreeGoodThings: &#39;Three Good Things&#39;,<br>  Today: &#39;Today&#39;,<br>};</pre><h3>Colors</h3><p>Within the same folder, I create a file called colors.js and add some colors.</p><pre>export const colors = {<br>  isabelline: ‘rgb(244, 242, 238)’,<br>  alabaster: ‘rgb(233, 229, 221)’,<br>  paleSilver: ‘rgb(186, 180, 172)’,<br>  bistre: ‘rgb(64, 46, 38)’,<br>  yellowOrange: ‘rgb(248, 180, 74)’,<br>};</pre><h3>Fonts</h3><p>In the project’s root directory, I create a folder called assets and within that folder, another folder called fonts.</p><p>Over at <a href="https://fonts.google.com/">Google Fonts</a>, I select my font ‘Playfair Display’ and hit ‘Download all’ at the bottom right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tCY2LpkwC2HUMHgY2U1lyw.png" /></figure><p>Time to unzip the download folder and copy the relevant .ttf files into assets/fonts. I tell React Native where these assets are located by creating a file called react-native.config.js in the project’s root directory and adding the following:</p><pre>module.exports = {<br>  assets: [‘./assets/fonts’],<br>};</pre><p>Executing the command react-native link will add the font references to Info.plist for iOS and copy the font files to android/app/src/main/assets/fonts for Android.</p><p>Inside src/hooks, I now create a file called fonts.js and add the following code:</p><pre>import {Platform} from ‘react-native’;</pre><pre>export const fonts = {<br>  bold: Platform.select({<br>    ios: ‘Playfair Display Bold’,<br>    android: ‘PlayfairDisplay-Bold’,<br>  }),<br>  medium: Platform.select({<br>    ios: ‘Playfair Display Medium’,<br>    android: ‘PlayfairDisplay-Medium’,<br>  }),<br>  regular: Platform.select({<br>    ios: ‘Playfair Display Regular’,<br>    android: ‘PlayfairDisplay-Regular’,<br>  }),<br>};</pre><p>The reason for doing this is because Android will read from the filename whereas iOS will read from the Full name or PostScript name of the .ttf file - which can often be different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*krxMjJXTEK-Qz_O1hPp-Eg.png" /></figure><h3>Styles</h3><p>Again, in the src/hooks folder (it’s a very important folder 😬), I create a file called styles.js. This file will efficiently provide styling properties to all of my application’s screens and components using the <a href="https://reactjs.org/docs/hooks-reference.html#usecontext">useContext()</a> hook.</p><p>I could just create a function which returns the textStyles object since it <em>is</em> static; but due to the possibility of me choosing to implement a dark mode feature in the future (which requires properties with dynamic values), I need to use the <a href="https://reactjs.org/docs/hooks-reference.html#usecontext">useContext()</a> hook.</p><pre>import React, {useMemo, useContext, createContext} from ‘react’;<br>import {View} from ‘react-native’;</pre><pre>import {ScaleHook} from ‘react-native-design-to-component’;</pre><pre>import {fonts} from ‘./fonts’;<br>import {colors} from ‘./colors’;</pre><pre>const StyleContext = createContext(null);</pre><pre>export const useStyle = () =&gt; {<br>  const context = useContext(StyleContext);<br>  return context;<br>};</pre><pre>export const StyleProvider = ({children}) =&gt; {<br>  const {getHeight, getWidth, fontSize, radius} = ScaleHook();</pre><pre>  // ** ** ** ** ** TEXT STYLES ** ** ** ** **<br>  const textStyles = {<br>    semiBold28_bistre: {<br>      color: colors.bistre,<br>      fontFamily: fonts.semiBold,<br>      fontSize: fontSize(28),<br>    },<br>    semiBold28_yellowOrange: {<br>      color: colors.yellowOrange,<br>      fontFamily: fonts.semiBold,<br>      fontSize: fontSize(28),<br>    },<br>  };</pre><pre>  // ** ** ** ** ** MEMOIZE ** ** ** ** **<br>  const values = useMemo(() =&gt; ({colors, textStyles}), [colors, textStyles]);</pre><pre>  // ** ** ** ** ** RENDER ** ** ** ** **<br>  return (<br>    &lt;View style={{flex: 1}}&gt;<br>      &lt;StyleContext.Provider value={values}&gt;{children}&lt;/StyleContext.Provider&gt;<br>    &lt;/View&gt;<br>  );<br>};</pre><h3>Navigation</h3><p>For routing and navigation, I’ll use <a href="https://reactnavigation.org/">React Navigation</a>. I’d recommend taking a look at their docs if you have any issues in this section. Anyway, time to install a few more packages.</p><ul><li>yarn add @react-navigation/native - the React Native integration for React Navigation.</li><li>yarn add react-native-screens - exposes native navigation container components to React Native.</li><li>yarn add @react-navigation/native-stack - stack navigator for React Native.</li></ul><p>I also need to install the pods for iOS. In the terminal, I run cd ios from project’s root folder and then pod install. For Android, I head over to android/app/src/main/java/threegoodthings/MainActivity.java. and add the following code.</p><p>import android.os.Bundle; to the top of the file and the below to the body of the class.</p><pre>@Override<br>protected void onCreate(Bundle savedInstanceState) {<br>  super.onCreate(null);<br>}</pre><p>Time to bring this all to life in the next and final section.</p><h3>App.js</h3><p>App.js (src/app.js) is the app’s entry file.</p><pre>import React from ‘react’;<br>import {NavigationContainer} from ‘@react-navigation/native’;<br>import {ScaleProvider} from ‘react-native-design-to-component’;<br>import {SafeAreaProvider} from ‘react-native-safe-area-context’;</pre><pre>import {StyleProvider} from ‘./hooks/styles’;</pre><pre>import {AppContainer} from ‘./containers/app-container’;</pre><pre>const App = () =&gt; {<br>  return (<br>    &lt;SafeAreaProvider&gt;<br>      &lt;ScaleProvider config={{height: 844, width: 390}}&gt;<br>        &lt;StyleProvider&gt;<br>          &lt;NavigationContainer&gt;<br>            &lt;AppContainer /&gt;<br>          &lt;/NavigationContainer&gt;<br>        &lt;/StyleProvider&gt;<br>      &lt;/ScaleProvider&gt;<br>    &lt;/SafeAreaProvider&gt;<br>  );<br>};</pre><pre>export default App;</pre><p>At the top of the file, I have my imports. I’d recommend keeping these separated by type as the list of imports can get really long and you don’t want to spend time searching through a single list. Below this, I have my AppContainer wrapped in a NavigationContainer - this takes care of navigating around the application. Above that, I have the StyleProvider I created earlier - this is the context layer that will provide styling properties to all of its child components. That means all of my screens and components that will be nested within AppContainer will be able to access my global state of styling properties. Above that I have a ScaleProvider which helps scale components for different devices. It accepts a config object of the dimensions of the design that I’m working from. Since my Figma designs are based on an iPhone 13 Pro, those are the dimensions I input here. And finally, the SafeAreaProvider provides inset information to all of the application’s components.</p><p>Within AppContainer, I define my first screen, SplashScreen.js. I set headerShown to false because I’m going to create my own header component to use throughout the app.</p><pre>import React from ‘react’;<br>import {createNativeStackNavigator} from ‘@react-navigation/native-stack’;</pre><pre>import {SplashScreen} from ‘../screens/login/splash-screen’;</pre><pre>const Stack = createNativeStackNavigator();</pre><pre>export const AppContainer = () =&gt; {<br>  return (<br>    &lt;&gt;<br>      &lt;Stack.Navigator&gt;<br>        &lt;Stack.Screen<br>          name=”Splash”<br>          component={SplashScreen}<br>          options={{<br>            headerShown: false,<br>          }}<br>        /&gt;<br>      &lt;/Stack.Navigator&gt;<br>    &lt;/&gt;<br>  );<br>};</pre><p>SplashScreen.js is a simple screen to test that all of the hooks from my providers are working.</p><pre>import React, {useState, useEffect, useCallback} from ‘react’;<br>import {View, Text, TouchableOpacity, StyleSheet} from ‘react-native’;<br>import {ScaleHook} from ‘react-native-design-to-component’;<br>import {useSafeAreaInsets} from ‘react-native-safe-area-context’;</pre><pre>import {useStyle} from ‘../../hooks/styles’;<br>import {dictionary} from ‘../../hooks/dictionary’;</pre><pre>export const SplashScreen = () =&gt; {<br>  const insets = useSafeAreaInsets();<br>  const {colors, textStyles} = useStyle();<br>  const {getHeight, getWidth, fontSize, radius} = ScaleHook();<br>  <br>  const {Today} = dictionary;</pre><pre>  const styles = StyleSheet.create({<br>    background: {<br>      flex: 1,<br>      backgroundColor: colors.isabelline,<br>    },<br>    container: {<br>      height: getHeight(44) + insets.top,<br>      alignItems: ‘center’,<br>      justifyContent: ‘flex-end’,<br>    },<br>    title: {<br>      …textStyles.semiBold28_bistre,<br>    },<br>  });</pre><pre>  return (<br>    &lt;View style={styles.background}&gt;<br>      &lt;View style={styles.container}&gt;<br>        &lt;Text style={styles.title}&gt;{Today}&lt;/Text&gt;<br>      &lt;/View&gt;<br>    &lt;/View&gt;<br>  );<br>};</pre><p>The end result?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Unpejy6iOMhiscZoAwSnsw.png" /></figure><p>Code available at:</p><p><a href="https://github.com/raf723/three-good-things/tree/feature/part-two">GitHub - raf723/three-good-things at feature/part-two</a></p><p>Looks like I’m now ready to start bringing those Figma designs to life 🥳. In the next post of this series, I’ll cover the app icon and splash screen.</p><p><a href="https://medium.com/@rafiulansari/building-a-react-native-app-part-iii-app-icon-and-splash-screen-a14505aa9036">Building a React Native App: Part III, App Icon and Splash Screen</a></p><p>Thank you,<br>Raf</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=782917168e01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native Animated Splash Screens]]></title>
            <link>https://medium.com/@rafiulansari/react-native-animated-splash-screens-e3719671dab6?source=rss-5a47494c562a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3719671dab6</guid>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Rafiul Ansari]]></dc:creator>
            <pubDate>Wed, 09 Mar 2022 15:41:06 GMT</pubDate>
            <atom:updated>2022-05-29T11:39:58.066Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*-NbwhOAnNDOklUjt1RTRnw.gif" /></figure><p>Looks awesome doesn’t it? Okay, now that you agree let me show you how to build it. For legal reasons, I can’t show you the exact code I wrote for the client or use their media assets but I can show you a simplified version. Here it is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*PABYrXg-LMW1qv8T87aygA.gif" /></figure><p>Before we break down the code, here it is as a whole:</p><pre>import React, {useRef, useEffect} from &#39;react&#39;;<br>import {StyleSheet, Animated, Easing} from &#39;react-native&#39;;</pre><pre>export default function App() {</pre><pre>   const backgroundFade = useRef(new Animated.Value(0)).current;<br>   const logoFade = useRef(new Animated.Value(0)).current;<br>   const logoMovement = useRef(new Animated.Value(0)).current;</pre><pre>   useEffect(() =&gt; {<br>      Animated.timing(backgroundFade, {<br>         toValue: 1,<br>         duration: 2000,<br>         useNativeDriver: true,<br>      }).start();</pre><pre>      Animated.timing(logoFade, {<br>         toValue: 1,<br>         duration: 2000,<br>         useNativeDriver: true,<br>      }).start();</pre><pre>      setTimeout(() =&gt; {<br>         Animated.timing(logoMovement, {<br>               toValue: -250,<br>               duration: 2000,<br>               easing: Easing.inOut(Easing.exp),<br>               useNativeDriver: true,<br>         }).start();<br>      }, 2250);<br>   }, []);</pre><pre>   const styles = StyleSheet.create({<br>      container: {<br>         flex: 1,<br>         alignItems: &#39;center&#39;,<br>         justifyContent: &#39;center&#39;,<br>         backgroundColor: &#39;orange&#39;,<br>         opacity: backgroundFade,<br>      },<br>      logo: {<br>         color: &#39;white&#39;,<br>         fontSize: 48,<br>         fontWeight: &#39;bold&#39;,<br>         opacity: logoFade,<br>         transform: [{translateY: logoMovement}],<br>      },<br>   });</pre><pre>   return (<br>      &lt;Animated.View style={styles.container}&gt;<br>         &lt;Animated.Text style={styles.logo}&gt;Logo&lt;/Animated.Text&gt;<br>      &lt;/Animated.View&gt;<br>   );<br>}</pre><p>Initially, the background colour and logo have an opacity of 0, hence setting backgroundFade and logoFade to an animated value of 0. The reason logoMovement is also set to 0 is because the initial position of an element is almost like coordinates on a graph - (0, 0) is the reference point and so the animated value will represent one coordinate/dimension (horizontal or vertical).</p><blockquote>The useRef Hook allows you to persist values between renders. It can be used to store a mutable value that does not cause a re-render when updated.</blockquote><pre>const backgroundFade = useRef(new Animated.Value(0)).current;<br>const logoFade = useRef(new Animated.Value(0)).current;<br>const logoMovement = useRef(new Animated.Value(0)).current;</pre><p>The useEffect has zero dependencies (represented by [] as the second parameter) and so it’ll be triggered on the first render. When it is, we want to run a series of animations across a given period of time.</p><p>The backgroundFade (background opacity) will change from 0 to 1 over a duration of 2000ms (2 seconds). The logoFade will do the same and run concurrently with the backgroundFade animation. Once the background and logo have faded into view, the logo needs to move upwards. setTimeout allows us to delay a block of code until a period of time has passed (passed as an integer as the second parameter of the setTimeout hook). Once 2.25 seconds have passed, the logo will move upwards (hence the negative toValue) by 250 points using an exponential function (the movement will start off slowly and then become a lot quicker) - check out all of the possible easing functions <a href="https://reactnative.dev/docs/easing">here</a>.</p><blockquote>By using the native driver, we send everything about the animation to native before starting the animation, allowing native code to perform the animation on the UI thread without having to go through the bridge on every frame. Once the animation has started, the JS thread can be blocked without affecting the animation.</blockquote><pre>useEffect(() =&gt; {<br>   Animated.timing(backgroundFade, {<br>      toValue: 1,<br>      duration: 2000,<br>      useNativeDriver: true,<br>   }).start();</pre><pre>   Animated.timing(logoFade, {<br>      toValue: 1,<br>      duration: 2000,<br>      useNativeDriver: true,<br>   }).start();</pre><pre>   setTimeout(() =&gt; {<br>      Animated.timing(logoMovement, {<br>         toValue: -250,<br>         duration: 2000,<br>         easing: Easing.inOut(Easing.exp),<br>         useNativeDriver: true,<br>      }).start();<br>   }, 2250);<br>}, []);</pre><p>Finally, we apply the animations to the style properties we wish to animate!</p><pre>const styles = StyleSheet.create({<br>   container: {<br>      flex: 1,<br>      alignItems: &#39;center&#39;,<br>      justifyContent: &#39;center&#39;,<br>      backgroundColor: &#39;orange&#39;,<br>      opacity: backgroundFade,<br>   },<br>   logo: {<br>      color: &#39;white&#39;,<br>      fontSize: 48,<br>      fontWeight: &#39;bold&#39;,<br>      opacity: logoFade,<br>      transform: [{translateY: logoMovement}],<br>    },<br>});</pre><p>Thank you,<br>Raf</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3719671dab6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a React Native App: Part I, Laying the Foundations]]></title>
            <link>https://medium.com/@rafiulansari/creating-a-react-native-app-part-i-laying-the-foundations-e6b81cd4f92?source=rss-5a47494c562a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6b81cd4f92</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ui-design]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[figma]]></category>
            <dc:creator><![CDATA[Rafiul Ansari]]></dc:creator>
            <pubDate>Sun, 06 Mar 2022 17:38:03 GMT</pubDate>
            <atom:updated>2022-06-19T12:06:09.474Z</atom:updated>
            <content:encoded><![CDATA[<p>Over the next few months I’m going to a build a mobile app called Three Good Things and document every step of the journey. It’s simple really, every day you write down three good things that happened to you. And with enough consistency, months down the line you’ll be able to look back at hundreds of good things that have happened to you.</p><h4>Tech Stack</h4><ul><li>AWS Cognito (for authentication)</li><li>AWS DynamoDB (to store data)</li><li>AWS S3 (to store images uploaded by users)</li><li>AWS AppSync (overkill but it’s just a personal challenge)</li></ul><p>I’ll be sure to document the set-up of each of these services along the way.</p><h4>Research</h4><p>Time to do scope out the competition for inspiration and what not to do. Reading their reviews, especially the bad ones, it seems that existing apps just don’t look that good or their scope is too wide. They’re trying to do too much instead of optimising their key feature.</p><h4>UI/UX Design</h4><p>I download some apps, check out <a href="https://dribbble.com/">Dribbble</a> and then head to <a href="https://coolors.co/">Coolors</a> to pick out my app’s colour palette.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7nlBWJHi1cvrt1_iLSkIVQ.png" /></figure><p>Followed by my quest for a classic font style using <a href="https://fonts.google.com/">Google Fonts</a>. I went with Playfair Display.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6zKthlp-K-DTGeHYNjQG6g.png" /></figure><p>Now it’s time to bring this all together with some wire-frames. When I made <a href="https://wali-app.co.uk/">my first app</a>, I didn’t bother. I just made things up as I went along and boy did I regret it. It wasted <em>so</em> much time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M9-cxNxFvzVT3EvIROfpJw.png" /></figure><p>Anyway, I ended up using <a href="https://www.figma.com/">Figma</a>. I find it a lot more intuitive to use than Adobe XD or Sketch. My wireframes aren’t very detailed and that’s okay. It’s the general layout I’m after. I’m also missing some screen designs (for now) but I have enough to start writing some code! Let’s take a quick moment to appreciate UI/UX designers and the amazing, detailed work they do.</p><p>In my next article, I’ll go through setting up the React Native project. Subscribe below for email alerts of new articles. Now. 😠</p><p><a href="https://medium.com/@rafiulansari/building-a-react-native-app-part-ii-project-setup-782917168e01">Building a React Native App: Part II, Project Setup</a></p><p>Thank you,<br>Raf</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6b81cd4f92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Jamstack App]]></title>
            <link>https://awstip.com/creating-a-jamstack-app-50086e091cc7?source=rss-5a47494c562a------2</link>
            <guid isPermaLink="false">https://medium.com/p/50086e091cc7</guid>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[jamstack]]></category>
            <dc:creator><![CDATA[Rafiul Ansari]]></dc:creator>
            <pubDate>Sat, 19 Feb 2022 12:06:14 GMT</pubDate>
            <atom:updated>2022-02-27T13:24:52.015Z</atom:updated>
            <content:encoded><![CDATA[<p>Wtf is Jamstack? Jamstack separates the frontend from the backend using serverless functions. Freed from backend servers, the frontend can then be deployed globally, directly to a CDN whilst dynamic content can be served via APIs - thus allowing for increased performance and security whilst allowing for more modular development.</p><p>In this tutorial, we’ll be creating a serverless React app which displays data from a DynamoDB table using AWS Lambda. Don’t worry if you don’t know React, you can use your own framework or clone my repo to replace my endpoints with your own. Easy peasy. And if you aren’t familiar with serverless functions, check out the previous part of this article where we create a serverless function which redirects visitors according to their OS:</p><p><a href="https://medium.com/@rafiulansari/creating-a-serverless-redirect-function-600816603d48">Creating a Serverless Redirect Function</a></p><p>Here’s a preview of what we’ll be building: https://serverless-react-app.netlify.app. When you click the ‘Redirect Me’ button, a link will open in a tab which triggers a Lambda function that redirects you to my mobile application’s landing page or app store page depending on your device whilst storing a record of your visit in a DynamoDB table. Before you return back to the previous tab, a second Lambda function will have been triggered which fetches all the records from the DynamoDB table to re-render the dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L8AwMkl02pyOrC7b94ZVQg.png" /></figure><p><strong>Creating our DynamoDB Table<br></strong>Before we modify the Lambda we created in our previous tutorial to store a record of each user’s visit, we need to create a DynamoDB table. To do so, let’s head over to the DynamoDB service and click ‘Create table’. Let’s call our table redirects and use id for our partition key. Leave the remaining fields and options as their default values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dHAozklH5H9eTXbOQ-DQDA.png" /></figure><p><strong>Creating IAM roles<br></strong>We need 2 IAM roles, one for write access to our DynamoDB table and one for read access. The former will be used by our Lambda function which redirects visitors according to their OS to store a record of their visit and the latter, by our frontend React app to retrieve data from the table. Already, we can begin to see how a Jamstack app allows for enhanced security.</p><p>Click ‘Policies’ and instead of selecting from the list of existing policies, let’s go ahead and click ‘Create Policy’ to create our own custom policy. Select DynamoDB as the service and PutItem (under Write) for Actions. For Resources, we’ll go over to DynamoDB <strong>in a new tab</strong> to get the resource number of the table we created earlier as shown below. This allows us to restrict our custom policy to particular resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vy2eLl8RjOnNcutHShhNLw.png" /></figure><p>Click ‘Next’ and then again to skip Tags. In the Review section, let’s call our policy ‘DynamoDB-Write’ and then click ‘Create Policy’ to finish creating our custom policy. Now let’s click ‘Roles’ from the sidebar and then ‘Create role’. Select DynamoDB from the dropdown and check the ‘Lambda’ option under ‘Use Case’ and hit ‘Next’. Select the ‘DynamoDB-Write’ policy we just created to attach to our role and hit ‘Next’. We’ll call our role ‘DynamoDB-Write’ (or something more distinct from our policy name if you wish) and click ‘Create role’ to finish creating our first IAM role.</p><p>We’ll repeat the steps above for our read access IAM role by calling our policy and role ‘DynamoDB-Scan’ and selecting ‘Query’ and ‘Scan’ (under Read) instead of ‘PutItem’. And those are our IAM roles done!</p><p><strong>Modifying our Redirect Lambda</strong></p><pre>const aws = require(&quot;aws-sdk&quot;);<br>const dynamoDB = new aws.DynamoDB({ region: &quot;eu-west-2&quot;, apiVersion: &quot;2012-08-10&quot; });</pre><pre>exports.handler = async (event, context) =&gt; {<br>    var redirectURL = &quot;<a href="https://www.wali-app.co.uk/">https://www.wali-app.co.uk</a>&quot;;<br>    var os = &quot;Other&quot;;<br>    <br>    const userAgent = event.headers[&quot;User-Agent&quot;];<br>    switch (true) {<br>        case userAgent.includes(&quot;iPhone&quot;):<br>            os = &quot;iOS&quot;;<br>            redirectURL = &quot;<a href="https://apps.apple.com/gb/app/wali/id1528328161">https://apps.apple.com/gb/app/wali/id1528328161</a>&quot;;<br>            break;<br>        case userAgent.includes(&quot;Android&quot;):<br>            os = &quot;Android&quot;;<br>            redirectURL = &quot;<a href="https://play.google.com/store/apps/details?id=com.thebutterflynetwork.wali">https://play.google.com/store/apps/details?id=com.thebutterflynetwork.wali</a>&quot;;<br>            break;<br>        default:<br>            break;<br>    }<br>    <br>    const response = {<br>        statusCode: 302,<br>        headers: { Location: redirectURL }<br>    };<br>    <br>    var params = {<br>        TableName: &quot;redirects&quot;,<br>        ReturnConsumedCapacity: &quot;TOTAL&quot;,<br>        Item: {<br>            &quot;id&quot;: { S: context.awsRequestId }, <br>            &quot;operating_system&quot;: { S: os }<br>        }<br>    };<br>    <br>    try {<br>        const data = await dynamoDB.putItem(params).promise();<br>        response.body = JSON.stringify(data);<br>    } catch(err) {<br>        console.log(&quot;Error: &quot;, err);<br>        response.body = JSON.stringify(err);<br>    }<br>    <br>    return response;<br>};</pre><p>Okay, let’s break down the additional bits of code. We start off by importing the ‘aws-sdk’ so that we can create a DynamoDB object (be sure to use the same region you used to create your table earlier).</p><pre>const aws = require(&quot;aws-sdk&quot;);<br>const dynamoDB = new aws.DynamoDB({ region: &quot;eu-west-2&quot;, apiVersion: &quot;2012-08-10&quot; });</pre><p>We then create a global variable to store the OS - this is the value which we’ll store in our DynamoDB table.</p><pre>var os = &quot;Other&quot;;</pre><p>Next, we create our response object. The reason we use a 302 (temporary redirect) status code in place of a 301 (permanent redirect), is because a 301 redirect gets cached by the client, thereby skipping the insertion into the DynamoDB table. Every time a client hits our endpoint, whether it’s the same client or not, we want to store a record of it in our database. And the reason we’re creating the response object now, is because the response is dependent on the success of our insertion into our DynamoDB table.</p><pre>const response = {<br>    statusCode: 302,<br>    headers: { Location: redirectURL }<br>};</pre><p>Then we create a params object where redirects is the name of our DynamoDB table and Item is the object we wish to insert. Those S’s denote that our values are strings.</p><pre>var params = {<br>    TableName: &quot;redirects&quot;,<br>    ReturnConsumedCapacity: &quot;TOTAL&quot;,<br>    Item: {<br>        &quot;id&quot;: { S: context.awsRequestId }, <br>        &quot;operating_system&quot;: { S: os }<br>    }<br>};</pre><p>And now we insert our item into the table. If it succeeds, we attach the result to the body of our response; otherwise, we attach the error message.</p><pre>try {<br>    const data = await dynamoDB.putItem(params).promise();<br>    response.body = JSON.stringify(data);<br>} catch(err) {<br>    console.log(&quot;Error: &quot;, err);<br>    response.body = JSON.stringify(err);<br>}</pre><p>Now, let’s assign an IAM role to this Lambda. Click on the ‘Configuration’ tab, and hit ‘Edit’ under ‘Execution role’ in the ‘Permissions’ page. In the ‘Existing role’ dropdown, select the DynamoDB-Write IAM role we created earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o2pd2BhSrZp99Nsh8byvSw.png" /></figure><p><strong>Creating a Lambda to Read our DynamoDB Table</strong></p><p>Let’s create another Lambda but this time, let’s assign its IAM role at the time of creation as opposed to after. Under ‘Permissions’, expand ‘Change default execution role’ and select ‘Use an existing role’. In the dropdown, select the DyanmoDB-Scan IAM role we created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c7juz_rAx4tE6gsTsa3RPQ.png" /></figure><p>The code:</p><pre>const AWS = require(&#39;aws-sdk&#39;);<br>const docClient = new AWS.DynamoDB.DocumentClient();</pre><pre>const getData = async() =&gt; {<br>    const scanResult = await docClient.scan({ &quot;TableName&quot;: &quot;redirects&quot; }).promise();<br>    return scanResult;<br>};</pre><pre>exports.handler = async () =&gt; {<br>    var iOS = 0;<br>    var android = 0;<br>    var other = 0;<br>    <br>    const data = await getData();<br>  <br>    data[&quot;Items&quot;].forEach((item) =&gt; {<br>        switch (item.operating_system) {<br>            case &#39;iOS&#39;:<br>                iOS += 1;<br>                break;<br>            case &#39;Android&#39;:<br>                android += 1;<br>                break;<br>            default:<br>                other += 1;<br>        }<br>    });<br>    <br>    const response = {<br>        statusCode: 200,<br>        headers: {<br>          &#39;Access-Control-Allow-Origin&#39;: &#39;*&#39;,<br>          &#39;Access-Control-Allow-Credentials&#39;: true,<br>        },<br>        body: JSON.stringify([<br>            {<br>                os: &quot;iOS&quot;,<br>                count: iOS<br>            },<br>            {<br>                os: &quot;Android&quot;,<br>                count: android<br>            },<br>            {<br>                os: &quot;Other&quot;,<br>                count: other<br>            }<br>        ])<br>    };<br>    <br>    return response;<br>};</pre><p>You know the drill. Let’s break it down. We start off by creating a function which will query our DynamoDB table using a scan method. Ring a bell? We specified ‘Scan’ as one of the actions for our ‘DynamoDB-Scan’ IAM role.</p><pre>const getData = async() =&gt; {<br>    const scanResult = await docClient.scan({ &quot;TableName&quot;: &quot;redirects&quot; }).promise();<br>    return scanResult;<br>};</pre><p>Then we fetch our data and loop through the array of Items in the response to tally the count by OS.</p><pre>const data = await getData();</pre><pre>data[&quot;Items&quot;].forEach((item) =&gt; {<br>    switch (item.os) {<br>        case &#39;iOS&#39;:<br>            iOS += 1;<br>            break;<br>        case &#39;Android&#39;:<br>            android += 1;<br>            break;<br>        default:<br>            other += 1;<br>    }<br>});</pre><p>And finally, our response.</p><pre>const response = {<br>    statusCode: 200,<br>    headers: {<br>        &#39;Access-Control-Allow-Origin&#39;: &#39;*&#39;,<br>        &#39;Access-Control-Allow-Credentials&#39;: true,<br>    },<br>    body: JSON.stringify({<br>        iOS: iOS,<br>        android: android,<br>        other: other<br>    })<br>};</pre><blockquote>The HTTP <strong><em>200 OK</em></strong> success status response code indicates that the request has succeeded. A 200 response is cacheable by default.</blockquote><ul><li>Access-Control-Allow-Origin is a security feature where setting it to * allows any incoming URL to access our endpoint’s resources. For more info on this, check out <a href="https://www.freecodecamp.org/news/access-control-allow-origin-header-explained">freeCodeCamp</a> for one of the best explanations out there.</li><li>Access-Control-Allow-Credentials is another security feature where setting it to true allows browsers to expose the response to the frontend JavaScript code.</li><li>And then in the body of our response, we return an object of the number of redirects by OS.</li></ul><p>Sweet! Now head over to API Gateway and create a REST API endpoint just like we did for our previous Lambda. Check out the article below for a walkthrough on how to do this:</p><p><a href="https://medium.com/@rafiulansari/creating-a-serverless-redirect-function-600816603d48">Creating a Serverless Redirect Function</a></p><p><strong>Creating our Dashboard</strong></p><p>At this point you have a few options:</p><ul><li>Leave it there</li><li>Create your own dashboard using another framework (or none at all)</li><li>Clone my repo (and ‘Star’ it 😠 pls 🥺) and replace my endpoints with your own (I used React to create my dashboard):</li></ul><p><a href="https://github.com/raf723/serverless-react-app">GitHub - raf723/serverless-react-app: Serverless web app built using React, AWS Lambda, API Gateway and DynamoDB</a></p><p>Thank you,<br>Raf</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50086e091cc7" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/creating-a-jamstack-app-50086e091cc7">Creating a Jamstack App</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing Android 12]]></title>
            <link>https://medium.com/@rafiulansari/introducing-android-12-164b85c7df98?source=rss-5a47494c562a------2</link>
            <guid isPermaLink="false">https://medium.com/p/164b85c7df98</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Rafiul Ansari]]></dc:creator>
            <pubDate>Sat, 12 Feb 2022 08:43:34 GMT</pubDate>
            <atom:updated>2022-02-12T08:43:34.742Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sI3LF1hRNpopD2WYcRs5PA.png" /></figure><p>Android 12 is here and truth be told, Google’s most ambitious visual revamp feels like a breath of fresh air. The latest OS sees enhancements on all fronts to the extent that your next software update might have you wondering if you just bought a new phone.</p><p><strong>It’s Personal</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DFy41v5CsPXMOFBBPeJguw.png" /></figure><p>Google’s new design, named Material You, sees elements from widgets to notifications all purposefully reimagined through colour extraction for Android’s most expressive user interface yet. Colour extraction is a clever little feature that extracts colours from your wallpaper to recolour elements across your phone. The text colour of the clock widget on your lock screen? It’s now a subtle, complementary shade of green because your wallpaper had a lovely, green plant on it. Very clever, I know. The latest OS has also brought forth a redesigned Settings and Quick Settings menu, the latter making use of tiles.</p><p>It doesn’t stop there. The user interface has been energised with smoother animations. Every tap, swipe and scroll takes you on a fluid journey, bolstered by Android 12’s improved system performance. Faster and more responsive with better power efficiency, partly thanks to a respective 15% and 22% reduction in the use of big cores and CPU time needed for the core system services.</p><h4>It’s Accessible</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BIQNz1vsOtq8AzR0Z-4OYw.png" /></figure><p>As we all increase our understanding on the importance of accessibility, Google have done an awesome job hitting the nail on the head with area magnification, bold text option and the ability to make our screens extra dim! In previous versions, a long press of the power button yielded the power menu. This has been replaced by invoking Google Assistant to help open apps, make calls, ask questions or read aloud articles.</p><h4>And It’s Safe</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*9rS8nmAh00nUwSb5WgTIzw.png" /></figure><p>Privacy through design; Android 12 brings us a new indicator in the status bar which tells us when an app is using our microphone or camera. As for applications that require our location, we can now choose between an approximate and precise location. And all of this has been brought together with a lovely, new privacy dashboard allowing you to view which apps have accessed your mic, camera or location and when, over the past 24 hours. Despite all of these new features that may make us feel a lot safer, the podium for new privacy features just might belong to Privacy Compute Core. A first-of-its-kind secure, dedicated environment on the mobile phone isolated from the rest of the OS. That means for features like Live Caption, Now Playing and Smart Reply, all of the audio and language processing is on-device, isolated from the network and thereby providing us all with enhanced privacy.</p><p><strong>Spotlight</strong></p><p>Other cool new Android 12 features start off with scrolling screenshots and an auto-rotate that now uses face detection instead of the device’s accelerometer. Beyond these, we’ve been given lot’s of small new features but the most eye-catching ones seem to be the rich content insertion and quick tap function. The former allowing us to copy and paste images, audio, marked-up text, etc. between apps and the latter, a feature for select Pixel devices that allows us to do things like take a screenshot or play/pause media through tapping the back of the phone.</p><p>Thank you,<br>Raf</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=164b85c7df98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Serverless Redirect Function Using AWS Lambda and API Gateway]]></title>
            <link>https://medium.com/better-programming/creating-a-serverless-redirect-function-600816603d48?source=rss-5a47494c562a------2</link>
            <guid isPermaLink="false">https://medium.com/p/600816603d48</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Rafiul Ansari]]></dc:creator>
            <pubDate>Fri, 11 Feb 2022 21:59:54 GMT</pubDate>
            <atom:updated>2022-04-19T18:46:49.446Z</atom:updated>
            <content:encoded><![CDATA[<h4>Redirect users to the app store and web landing page accordingly</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aTkhmphpfKOeXJcj" /><figcaption>Photo by <a href="https://unsplash.com/@jacksonsophat?utm_source=medium&amp;utm_medium=referral">Jackson So</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>So you’ve created an app that’s published on the app stores and now you want to redirect your users to their respective stores using a single URL? You’ve come to the right place.</p><p>In this article, I’ll be using AWS Lambda and API Gateway to create our serverless function. And in another article, I’ll extend what we build here by storing each user’s visit in a DynamoDB table to create a Jamstack app:</p><p><a href="https://medium.com/@rafiulansari/creating-a-jamstack-app-50086e091cc7">Creating a Jamstack App</a></p><h4><strong>Creating our Lambda Function</strong></h4><p><em>Lambda is the service that will take care of the logic of redirecting our visitors based on their OS.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*toe7M7JOgb_IdU7Eid5n1w.png" /></figure><p>Once we’re on the AWS Console, we’ll head over to the Lambda service. From here, we can create our Lambda using the ‘Create function’ button. Let’s call it redirect and leave the remaining options with their default selections. After we click ‘Next’, we’ll be presented with a method named handler:</p><pre>exports.handler = async (event) =&gt; {<br>    // TODO implement<br>    const response = {<br>        statusCode: 200,<br>        body: JSON.stringify(&#39;Hello from Lambda!&#39;),<br>    };<br>    return response;<br>};</pre><p>The handler can accept additional parameters:</p><pre>exports.handler = (event, context, callback) =&gt; {}</pre><ul><li>event contains the request data</li><li>context contains user information for authentication</li><li>callback is a function we can use to create a response</li></ul><p>For our purposes, we only require event and callback. What we want to do is, analyse the User-Agent of the client’s request data (event) to determine the redirect URL.</p><blockquote>The User-Agent is a request header that allows a characteristic string that allows network protocol peers to identify the Operating System and Browser of the web-server.</blockquote><p>And once we’ve determined the redirect, we use a return statement or a callback function to pass this URL to the Location of the response header. Additionally, passing a status code in the response allows us to send additional information to the client - check out the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status">MDN Web Docs</a> to view a list of possible response status codes.</p><p>For the purposes of an upcoming part of this project, we’ll be using a 302 code in place of 301. Let’s hit ‘Deploy’ and there we have it, our Redirect Lambda function:</p><pre>exports.handler = async (event, context) =&gt; {<br>    var redirectURL = &quot;https://www.wali-app.co.uk&quot;;</pre><pre>    const userAgent = event.headers[&quot;User-Agent&quot;];<br>    switch (true) {<br>        case userAgent.includes(&quot;iPhone&quot;):<br>            redirectURL = &quot;<a href="https://apps.apple.com/gb/app/wali/id1528328161">https://apps.apple.com/gb/app/wali/id1528328161</a>&quot;;<br>            break;<br>        case userAgent.includes(&quot;Android&quot;):<br>            redirectURL = &quot;<a href="https://play.google.com/store/apps/details?id=com.thebutterflynetwork.wali">https://play.google.com/store/apps/details?id=com.thebutterflynetwork.wali</a>&quot;;<br>            break;<br>        default:<br>            break;<br>    }<br>    <br>    return {<br>        statusCode: 302,<br>        headers: { Location: redirectURL }<br>    };<br>};</pre><h4>Setting up our API Gateway</h4><p><em>API Gateway is the service that will pass the client’s request to our Lambda and define its response.</em></p><p>Head over to the API Gateway service and create a REST API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dz4j5eNoYxdDnWHU16AoZg.png" /></figure><p>In the following screen, select ‘Create Methods’ from the ‘Actions’ dropdown. In the newly presented dropdown, select ‘GET’ and click the checkmark. This will present us with a form to connect our API to a Lambda function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UZJ5nMubKbXUc01u6hY6Pg.png" /></figure><p>As we won’t be configuring our Integration Response, let’s check ‘Use Lambda Proxy Integration’ to quickly bring in our Lambda function (this will make more sense in the next paragraph).</p><p>Once we hit ‘Save’, we will be presented with the Method Execution flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vpSn_zvNI3XvQPtkFQxTvw.png" /></figure><ul><li>Method Request: The part of our API that is exposed to our visitors. It handles authentication, input body, headers and query string parameters.</li><li>Integration Request: What the API is integrating with — in our case, a Lambda function.</li><li>Integration Response: Allows us to standardise the response from our integration. This is disabled because our Lambda is already returning a response in the format required by API Gateway.</li><li>Method Response: Defines what the method can return. It’s responsible for defining the status codes and response bodies returned by our API.</li></ul><p>Let’s click the ‘Method Response’, expand the 200 HTTP status and add ‘Access-Control-Allow-Origin’ to the ‘Response Headers’ so that we don’t run into CORS errors.</p><p>Head back to the previous screen and ‘Enable CORS’ for the top-level resource.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-T4WEqhXvpZGtf_1s88Nlw.png" /></figure><p>Leave the default selections as-is and click ‘Enable CORS and replace existing CORS headers’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lTCoCvV873KK-9Tj-APinA.png" /></figure><p>From the Method Execution flow of the GET method, we can test our API and pass in our own query parameters - we’ll skip this step and move onto deploying our API. With the top-level resource selected, let’s click ‘Deploy API’ from the ‘Actions’ dropdown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_BdM8ud3Bs6nJjCZPrvCEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LDaSdVCJ6KQewlnA0i9pHA.png" /></figure><p>And voila! We’ll be presented with an endpoint (<a href="https://11fognbk8e.execute-api.eu-west-2.amazonaws.com/dev">https://11fognbk8e.execute-api.eu-west-2.amazonaws.com/dev</a>) which, if we were to access from a desktop, will redirect us to the application’s landing page.</p><p>And if we were to access it from an Android or iOS device, will redirect us to the Play Store or App Store, respectively.</p><h3>Taking it Further</h3><p>In the next part of this project, we’ll record all visits to our REST endpoint by writing to a DynamoDB table using our existing Lambda function.</p><p>We’ll then create a Jamstack app which calls another REST endpoint integrated to a new Lambda that returns the number of visitors by OS for us to present visually in a dashboard.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=600816603d48" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/creating-a-serverless-redirect-function-600816603d48">Creating a Serverless Redirect Function Using AWS Lambda and API Gateway</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>