Mobile development : Go serverless with AWS Amplify, a game changer !

Khalid BOURHABA
Nov 29, 2019 · 11 min read

Note-taking mobile app tutorial

Today’s busy and fast life forces developers to launch their apps quickly in order to stay ahead of the competition, and carry out their projects on-time and on-budget!

Every mobile application is typically built on two interconnected layers : Frontend and Backend. However, most mobile apps developers are frontend engineers with limited knowledge in backend development. As a frontend developer, working on your mobile app backend infrastructure from zero could be a nightmare, and you will certainly experience a delay in launching your app.

Before starting working on a custom backend, one should ask the following questions :

  • Will my backend be secure enough ?
  • How much time/money will the backend development costs ?
  • Who will maintain the servers hosting the backend ?
  • Am I sure that my app will be performant and resilient ?
  • How can I implement privacy requirements like GDPR ?
  • Will it be easily scalable ?

Usually when a mobile app idea crosses your mind, and you decide to start developing it, you are alone. Securing all the points stated above in a reasonable time is nearly impossible, and most importantly, you just want to make your idea come to life quickly.

MBaaS

This is where BaaS/MBaaS (Backend as a Service/Mobile Backend as a Service) comes in. MBaaS enables developers to focus on client-side development, and let them outsource the responsibilities of developing a backend to a third party.

Additionally, most MBaaS providers offer a set of tools that make development even faster. They provide many ready to use features like Users Management, Authentication, File Storage, Push Notifications, etc…

There is many MBaaS providers out there on the market. I had the opportunity to work with Strapi and Parse for the past few months. Both are open source and easy to get started with.

Strapi — Open source Node.js Headless CMS

Even if its creators do not define it as a MBaaS, i’ve used Strapi for a small project, and it was a successful experience.

Keep control. Deliver faster. Building self-hosted, customizable and performant Content API has never been easier.

Parse server : The Complete Application Stack

Build applications faster with object and file storage, user authentication, push notifications, dashboard and more out of the box.

no code required.

It was originally created by Parse, Inc. In 2013, Facebook acquiered it before shutting it down in 2017. After this, Parse became open source with a huge community backing it up.

Parse is built with NodeJs and comes up with Parse Dashboard, which is a web interface where you can create your APIs.

Here’s a great tutorial to get started with Parse.

Great solutions, but they don’t answer all the questions above !

With these two solutions, you will still have to host them on a server (or many servers), maintain this server and secure it. Also, you will have to scale it up in case your mobile application become successful.

Quote on outsourcing from azquotes

With that being said, outsourcing comes with a risk. You will still have to well undersand what you will outsource and how the third party will do it.

AWS Amplify : The full-stack serverless framework !

After spending some time looking for the perfect solution for my use cases, I discovered Amazon’s amazing framework : AWS Amplify.

Amazon Web Service is one of the best cloud services providers, if not the best provider. It offers services such as hosting, storage, technologies for managing serverless web or mobile applications, and much more.

To help frontend developers accelerate dev cycle, Amazon created AWS Amplify.

AWS Amplify is a JavaScript library for Frontend and mobile developers building fast, secure and scalable cloud-enabled applications.

  • Authentication using AWS Cognito
  • AppSync APIs
  • GraphQL Client through an API, in most uses cases, AWS AppSync with offline and real-time features
  • Supports React, React Native, Angular, Ionic and Vue
  • Push Notifications
  • Cloud Storage
  • GDPR requirements
  • Security
  • Auto-scaling
  • And much more…

Additionaly, one can use Amplify with AWS’s free tier program. So what are you waiting for to get your hands on it :) ?


The rest of this article will be a tutorial on how to build a simple note-taking mobile application using AWS Amplify and Expo. This app will allow a user to sign up and log in using AWS Cognito.

Once logged in, the user can add a note and save it. The user can also display the notes he saved. This will be done by creating an API and querying it using GraphQL.

Prerequisites

In order to follow this tutorial, i will assume that you are good with React Native. You will need to have installed on your machine the following :

  • An AWS account
  • Node.js and npm
  • Expo-cli
  • AWS Amplify CLI

To install the AWS Amplify CLI tool-chain, run the following command :

npm install -g @aws-amplify/cli

Clone this open-source Expo register/login template written by Tomek Przybył from reactnativemarket. This will help us speed up our development.

git clone https://github.com/venits/react-native-login-template.git myNotes

Here’s some screens from this great starter app. You can see the rest of the screens here.

In order to run this static application on your mobile or emulator, run these commands :

cd myNotesnpm installnpm run android//or npm run ios

Now we should configure AWS Amplify CLI tool. Please note that an AWS account is required for the rest of this tutorial.

Run the following commands :

cd myNotesamplify configure
  • Region : Choose on which region servers you want to use. “ us-east-2” for example.
  • IAM username : Choose the name of your IAM profile.

After hitting enter, a tab will be opened in your default browser. Sign-in to your Amazon account, then go back to the console and hit enter again. This will open the following tab in your browser :

Select the first checkbox then click “Next: Permissions” Button.

Click on “Next : Tags” button, then “Next: Review” and finally click “Create user” button. Your IAM profile is now created. Keep the API keys somewhere, we will need them in the next step.

Back to the console, enter the accessKeyId then secretAccessKey. Then enter a profile name (you can set it same as your IAM username). And we are done configuring the AWS Amplify CLI.

We can now start playing with AWS Amplify. In the next step, we will initilize Amplify inside our Expo app using the init command.

>> amplify init
Enter a name for the project myNotes
? Enter a name for the environment dev
? Choose your default editor: Visual Studio Code
? Choose the type of app that you're building javascript
Please tell us about your project? What javascript framework are you using react native
? Source Directory Path: /
? Distribution Directory Path: /
? Build Command: npm run-script build
? Start Command: npm run-script start
? Do you want to use an AWS profile ? Yes
? Please choose the profile you want to use kbourhaba_
## Choose your aws profile created previously

This will create a folder called amplify with the initial project configuration. It will also create add some lines in your .gitignore file.

If you have done all the steps above right, this should be your project folder structure :

Project structure

Okay let’s start coding !

Authentication

AWS Amplify comes with an Authentication module that uses AWS Cognito. We will add it to our app using this command :

amplify add auth
Adding Authentication to our app

Install the following libraries that will allow our app to communicate with AWS Amplify service :

npm install --save aws-amplify
npm install --save aws-amplify-react-native

For article length reasons, i will implement only the sign up and confirm sign up screens. But you can find the full source code here. It would be a great exercice if you implement the others screens though.

Open the app.js file in your favourite IDE, and add this after the last import :

// Amplify imports and configimport Amplify from '@aws-amplify/core'import config from './aws-exports'import API, { graphqlOperation } from '@aws-amplify/api';Amplify.configure(config)

Next open the RegisterScreen.js file and add the following :

import Auth from '@aws-amplify/auth'

This import will allow us to call the Auth.signUp and Auth.confirmSignUp functions.

Put the following code after the imports :

async function signUp() {
await Auth.signUp({
'username': email.value,
'password': password.value,
attributes: {
'name': name.value,
}
})
.then(() => {
console.log('sign up : OK!')
navigation.navigate('ConfirmSignUpScreen', {name:
name.value});
Alert.alert('Please enter the confirmation code you
received in you email.')
})
.catch(err => {
if (! err.message) {
Alert.alert('Error when signing up. Please try again
later')
}
else {
Alert.alert('Error when signing up: ', err.message)
}
})
}

And call this function from the _onSignUpPressed() function :

const _onSignUpPressed = () => {

const nameError = nameValidator(name.value);
const emailError = emailValidator(email.value);
const passwordError = passwordValidator(password.value);

if (emailError || passwordError || nameError) {
setName({ ...name, error: nameError });
setEmail({ ...email, error: emailError });
setPassword({ ...password, error: passwordError });
return;
}
signUp();
}

After signing up the user will recieve a confirmation code in his email, and must enter it to complete the register process.

Next we will create ConfirmSignUpScreen.js (not provided by the template). Inside the src/screens copy and paste this code.

Append the following line to the src/screens/index.js file :

export { default as ConfirmSignUpScreen } from './ConfirmSignUpScreen';

Sign up is completed. If you want to implement the whole authentication workflow, copy the remaining screens from my GitHub repository.

Notes Screens

The Dashboard.js file will allow the user to write a note, save it and display all of his notes. While the ListNotesScreen.js, will let the user display his saved notes.

API

In this step, we will add an API to our app. The API will have a single object, which will represent a note. For more information about how to implement APIs in AWS Amplify, take a look a the documentation.

Execute the following command :

amplify add api
Ampify add api command

This will open a schema.graphql file in your editor. Add the following schema :

type Note 
@model
@key(name: "byName", fields: ["username", "id"], queryField: "notesByUserName")
{
id: ID!
description: String!
createdAt: AWSDateTime
username: String!
}

In a real life app, i would create a User model in my GraphQL schema, then add a relationship with the Note model using @connection directive. But for this example, i’ll just put a username field in my Note model.

Save and close the file, then back to your terminal and press enter. Fore more information about Amplify Transform and Schema Definition Language, read this documentation.

We have just created our application API and configured Authentication locally. Now we need to push the changes to the cloud to create the corresponding resources. Run this command :

amplify status

This means that we have two resources created locally, but not yet pushed in the cloud.

amplify status command output

Push the resources in the cloud services :

amplify push
amplify push command

This command will create the following resources in AWS :

  • A DynamoDB table to store objects of type Note we’ve just created,
  • An AWS Cognito user pool to handle authentication for our app,
  • An AWS AppSync API with generated mutations and queries;

You can see your API and the GraphQL queries and mutations via the AWS AppSync console :

AWS AppSync API

We will use the queries and mutations generated automatically by AWS Amplify, to save notes and fetching them. You can find them in src/graphql folder :

This is an example on how to save a note, by using graphqlOperation() function :

After saving the note, you can go to your AWS console and look for DynamoDB. You should see a Note table where notes are saved :

DynamoDB table preview

To fetch data stored in DynamoDB, we will use the query notesByUserName() generated by AWS Amplify :

To run the application :

npm installnpm run android //npm run ios

And that’s it ! We’ve just finished creating our cross-platform note-taking app using using cutting-edge technologies like AWS Amplify, Cognito, AppSync and React Native.

I have skipped a lot of source code parts, so the full source code is available in my GitHub. Follow the steps in the readme file to run the mobile app without writing a single line of code !

Conclusion

As you can see, AWS Amplify is really a game changer as it makes it easy to connect all of AWS cloud services together. It also help to speed up developement. That’s being said, AWS Amplify comes up with some flaws. But the community is groing faster and working to improve this framework.

Thanks for reading my article, and stay tuned for my next article where I will explain how to upload files to AWS Cloud storage.

Khalid BOURHABA

Written by

Data engineer during the week. Mobile developer in my free time.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade