Skip to main content

Building Serverless Mobile Applications with React Native & AWS

Building Server-less Mobile Applications with React Native & AWS

When building a real-world mobile application there are a ton of essential basic requirements.

You need to have a way to authenticate users, you want to track user engagement & usage, & you probably want to be able to send push notifications and maybe base these messages on events or user behavior. Then you have to manage your application data and are probably dealing with multiple REST endpoints. You’re also usually dealing with media such as images & videos and you hopefully want to be able to handle offline use cases so that the app continues to work whether or not they are online.

Getting Started

Creating the React Native App

First we’ll create a new React Native project using either the React Native CLI or the Create React Native App CLI:

react-native init ServerlessProject
cd ServerlessProject

Installing the AWS Mobile CLI

The AWS Mobile CLI offers a way to quickly & easily spin up new AWS Mobile Hub projects from the command line.

npm i -g awsmobile-cli
awsmobile configure
awsmobile init
react-native link amazon-cognito-identity-js

Configuring the React Native app with your new AWS Mobile Hub project.

Now that the Mobile Hub project has been created & the dependencies are all installed, we can configure the React Native project to recognize our configuration.

import { AppRegistry } from 'react-native';
import App from './App';
import Amplify from 'aws-amplify' // NEW
import config from './aws-exports' // NEW
Amplify.configure(config
) // NEW
AppRegistry.registerComponent('ServerlessProject', () => App);

User Sign Up & Sign In

The first thing we’ll do is look at how we can add user sign up & sign in.

awsmobile user-signin enableawsmobile push
  1. We can use the React components & higher order components for preconfigured functionality & UI
  2. We can write this functionality from scratch using the Auth class which contains methods like Auth.signUp() & Auth.signIn()

React Native Components

Let’s first check out how to use the withAuthenticator HOC from aws-amplify-react-native.

import { withAuthenticator } from 'aws-amplify-react-native'
class App extends Component {
// all of this code stays the same
}
export default withAuthenticator(App)
react-native run-ios
// or
react-native run-android
<Authenticator>
<App />
</Authenticator>

Auth Class

We can also use the Auth class to authenticate users.

import { Auth } from 'aws-amplify'// in your component
Auth.signIn('myusername', 'mYC0MP13xP@55w0r8')
import { Auth } from 'aws-amplify'

class App extends React.Component {
  state = {
    username: '',
    password: '',
    phone_number: '',
    email: '',
    authCode: '',
    user: {}
  }
  async signUp() {
    const { username, password, email, phone_number } = this.state
    await Auth.signUp({
      username,
      password,
      attributes: { email, phone_number }
    })
    console.log('sign up successful!')
  }
  async confirmSignUp() {
    const { username, authCode } = this.state
    await Auth.configSignignUp(username, authCode)
    console.log('confirm sign up successful!')
  }
  async signIn() {
    const { username, password  } = this.state
    const user = await Auth.signIn(username, password)
    this.setState({ user })
    console.log('sign in successful!')
  }
  async confirmSignIn() {
    const { user, authCode } = this.state
    await Auth.configSignignIn(user, authCode)
    console.log('user now successfully signed in to the app!!')
  }
  render() {
    // render method
  }
}
awsmobile console
AWS Mobile Hub project showing enabled services
Links to all enabled resources

Analytics

Analytics events can be tracked using the Analytics class.

Analytics.record('sale price section viewed')
Analytics.record('sale price item viewed', { itemName: 'USA Socks' , timestamp: 'June 13 2018 4:03pm ET' })
awsmobile console
// Click on Resources, then Pinpoint
Pinpoint dashboard

Storage

Amplify has a Storage class that allows easy interop with React Native making the storage and access of media like images & media much easier, working seamlessly with Amazon S3.

awsmobile user-files enable
awsmobile push
import { Storage } from 'aws-amplify'
Storage.put('test.txt', 'Hello')
.then (result => console.log(result))
.catch(err => console.log(err));
Storage.get('test.txt')
.then(result => console.log(result))
.catch(err => console.log(err));
import RNFetchBlob from 'react-native-fetch-blob';

readFile(filePath) {
return RNFetchBlob.fs.readFile(filePath, 'base64').then(data => new Buffer(data, 'base64'));
}

readFile(imagePath).then(buffer => {
Storage.put('MYKEY', buffer, {
contentType: 'image/jpeg'
})
}).catch(e => {
console.log(e);
});

Lambda Functions

When you hear “Serverless” you may typically think of a Lambda function. We can set one of these up manually and connect it with our existing AWS Amplify resources, or we can use the AWS Mobile CLI to set this up for us. Let’s continue using the CLI to create the new Lambda function.

awsmobile cloud-api enable
/// rest of file omittedapp.get('/items', function(req, res) {
res.json({
body: "HELLO WORLD"
});
});
awsmobile push
awsmobile console
async componentDidMount() {
const data = await API.get('sampleCloudApi', '/items')
console.log('data: ', data)
}

Managed API & Data Layer

type Todo {
id: ID!
name: String!
completed: Boolean!
}
type Query {
fetchTodos(id: ID!): Todo
}
mutation add {
createTodo(input: {
name: "Get groceries"
completed: false
}) { id }
}
query list {
listTodos {
items {
id
name
completed
}
}
}
export default {
  'aws_appsync_graphqlEndpoint': 'https://*******.appsync-api.us-east-1.amazonaws.com/graphql',
  'aws_appsync_region': 'us-east-1',
  'aws_appsync_authenticationType': 'API_KEY',
  'aws_appsync_apiKey': 'da2-*************',
}
import { AppRegistry } from 'react-native';
import App from './App';
import Amplify from 'aws-amplify'
import config from './aws-exports'
import AppSyncConfig from './appsync-config' // NEW
Amplify.configure({ ...config, ...AppSyncConfig }
) // UPDATED
AppRegistry.registerComponent('ServerlessProject', () => App);
import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View
} from 'react-native';

import { withAuthenticator } from 'aws-amplify-react-native'
import { API, graphqlOperation } from 'aws-amplify'

const query = `
  query list {
    listTodos {
      items {
        id
        name
        completed
      }
    }
  }
`

class App extends Component {
  state = { todos: [] }
  async componentDidMount() {
    const todos = await API.graphql(graphqlOperation(query))
    this.setState({ todos: todos.data.listTodos.items })
  }
  render() {
    return (
        <View style={styles.container}>
          <Text style={styles.welcome}>
            Todos
          </Text>
          {
            this.state.todos.map((todo, index) => (
              <Text key={index}>{todo.name}</Text>
            ))
          }
        </View>
    );
  }
}

export default withAuthenticator(App)

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  }
});

Push Notifications are available for both Android & iOS in AWS Amplify.

import { PushNotification } from 'aws-amplify-react-native';

// get the registration token
PushNotification.onRegister((token) => {
  console.log('in app registration', token);
});

PushNotification.onNotification((notification) => {
  // Note that the notification object structure is different from Android and IOS
  console.log('in app notification', notification);

  // required on iOS only (see fetchCompletionHandler docs: https://facebook.github.io/react-native/docs/pushnotificationios.html)
  notification.finish(PushNotificationIOS.FetchResult.NoData);
});

Comments

Popular Posts

How I Reduced the Size of My React Native App by 85%

How and Why You Should Do It I borrowed 25$ from my friend to start a Play Store Developer account to put up my first app. I had already created the app, created the assets and published it in the store. Nobody wants to download a todo list app that costs 25mb of bandwidth and another 25 MB of storage space. So today I am going to share with you how I reduced the size of Tet from 25 MB to around 3.5 MB. Size Matters Like any beginner, I wrote my app using Expo, the awesome React Native platform that makes creating native apps a breeze. There is no native setup, you write javascript and Expo builds the binaries for you. I love everything about Expo except the size of the binaries. Each binary weighs around 25 MB regardless of your app. So the first thing I did was to migrate my existing Expo app to React Native. Migrating to React Native react-native init  a new project with the same name Copy the  source  files over from Expo project Install all de...

How to recover data of your Android KeyStore?

These methods can save you by recovering Key Alias and Key Password and KeyStore Password. This dialog becomes trouble to you? You should always keep the keystore file safe as you will not be able to update your previously uploaded APKs on PlayStore. It always need same keystore file for every version releases. But it’s even worse when you have KeyStore file and you forget any credentials shown in above box. But Good thing is you can recover them with certain tricks [Yes, there are always ways]. So let’s get straight to those ways. 1. Check your log files → For  windows  users, Go to windows file explorer C://Users/your PC name/.AndroidStudio1.4 ( your android studio version )\system\log\idea.log.1 ( or any old log number ) Open your log file in Notepad++ or Any text editor, and search for: android.injected.signing and if you are lucky enough then you will start seeing these. Pandroid.injected.signing.store.file = This is  file path where t...

React Native - Text Input

In this chapter, we will show you how to work with  TextInput  elements in React Native. The Home component will import and render inputs. App.js import React from 'react' ; import Inputs from './inputs.js' const App = () => { return ( < Inputs /> ) } export default App Inputs We will define the initial state. After defining the initial state, we will create the  handleEmail  and the  handlePassword  functions. These functions are used for updating state. The  login()  function will just alert the current value of the state. We will also add some other properties to text inputs to disable auto capitalisation, remove the bottom border on Android devices and set a placeholder. inputs.js import React , { Component } from 'react' import { View , Text , TouchableOpacity , TextInput , StyleSheet } from 'react-native' class Inputs extends Component { state = { ...