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

What are the Alternatives of device UDID in iOS? - iOS7 / iOS 6 / iOS 5 – Get Device Unique Identifier UDID

Get Device Unique Identifier UDID Following code will help you to get the unique-device-identifier known as UDID. No matter what iOS user is using, you can get the UDID of the current iOS device by following code. - ( NSString *)UDID { NSString *uuidString = nil ; // get os version NSUInteger currentOSVersion = [[[[[UIDevice currentDevice ] systemVersion ] componentsSeparatedByString: @" . " ] objectAtIndex: 0 ] integerValue ]; if (currentOSVersion <= 5 ) { if ([[ NSUserDefaults standardUserDefaults ] valueForKey: @" udid " ]) { uuidString = [[ NSUserDefaults standardDefaults ] valueForKey: @" udid " ]; } else { CFUUIDRef uuidRef = CFUUIDCreate ( kCFAllocatorDefault ); uuidString = ( NSString *) CFBridgingRelease ( CFUUIDCreateString ( NULL ,uuidRef)); CFRelease (uuidRef); [[ NSUserDefaults standardUserDefaults ] setObject: uuidString ForKey: @" udid " ]; [[ NSUserDefaults standardUserDefaults ] synchro...

16 AWS Gotchas

16 AWS Gotchas In January I launched the MVP for my own startup,  Proximistyle , which helps you find what you’re looking for nearby. On advice from friends and industry contacts I chose AWS as my cloud provider. Having never had to set up my own cloud infrastructure before, the learning curve to get from no experience to a stable VPC system I was happy with was significantly steeper than expected, and had its fair share of surprises. #1 Take advantage of the free resources offered AWS offers a free tier for new accounts. If you have recently bought a domain and set up a company you qualify for the free tier for a year. Additionally, if you are a bootstrapped startup you can apply for  the Startup Builders package  and get $1000 in AWS credits. After doing the above, you’re now ready to get started with setting up the AWS infrastructure for your startup. #2 Set up billing budgets and alerting The very first thing you should do after setting up billing, is enabling a budge...

Ultimate Folder Structure For Your React Native Project

  Ultimate Folder Structure For Your React Native Project React native project structure React Native is a flexible framework, giving developers the freedom to choose their code structure. However, this can be a double-edged sword for beginners. Though it offers ease of coding, it can soon become challenging to manage as your project expands. Thus, a structured folder system can be beneficial in many ways like better organization, simplified module management, adhering to coding practices, and giving a professional touch to your project. This write-up discusses a version of a folder arrangement that I employ in my React Native projects. This structure is based on best practices and can be modified to suit the specific needs of your project. Before we get into the project structure let’s give credit to @sanjay who has the original idea of the structure but I modify his version of the code, to make it better. Base library axios  — For network calling. react-navigation ...