• Stars
    star
    172
  • Rank 221,201 (Top 5 %)
  • Language
  • Created about 6 years ago
  • Updated over 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Building Serverless React Applications with AWS Amplify

Building Serverless Web Applications with React and AWS Amplify

In this workshop we'll learn how to build cloud-enabled web applications with GraphQL, React, & AWS Amplify.

Topics we'll be covering:

Getting Started - Creating the React Application

To get started, we first need to create a new React project & change into the new directory using the Create React App CLI.

If you already have this installed, skip to the next step. If not, either install the CLI & create the app or create a new app using npx:

npm install -g create-react-app
create-react-app my-amplify-app

Or use npx (npm 5.2 & later) to create a new app:

npx create-react-app my-amplify-app

Now change into the new app directory & install the AWS Amplify & AWS Amplify React libraries:

cd my-amplify-app
npm install --save aws-amplify aws-amplify-react uuid
# or
yarn add aws-amplify aws-amplify-react uuid

Installing the CLI & Initializing a new AWS Amplify Project

Installing the CLI

Next, we'll install the AWS Amplify CLI:

npm install -g @aws-amplify/cli

Now we need to configure the CLI with our credentials:

amplify configure

If you'd like to see a video walkthrough of this configuration process, click here.

Here we'll walk through the amplify configure setup. Once you've signed in to the AWS console, continue:

  • Specify the AWS Region: eu-central-1
  • Specify the username of the new IAM user: amplify-workshop-user

In the AWS Console, click Next: Permissions, Next: Tags, Next: Review, & Create User to create the new IAM user. Then, return to the command line & press Enter.

  • Enter the access key of the newly created user:
    accessKeyId: (<YOUR_ACCESS_KEY_ID>)
    secretAccessKey: (<YOUR_SECRET_ACCESS_KEY>)
  • Profile Name: amplify-workshop-user

Initializing A New Project

amplify init
  • Enter a name for the project: amplifyreactapp
  • Enter a name for the environment: dev
  • Choose your default editor: Visual Studio Code (or your default editor)
  • Please choose the type of app that you're building javascript
  • What javascript framework are you using react
  • Source Directory Path: src
  • Distribution Directory Path: build
  • Build Command: npm run-script build
  • Start Command: npm run-script start
  • Do you want to use an AWS profile? Y
  • Please choose the profile you want to use: amplify-workshop-user

Now, the AWS Amplify CLI has iniatilized a new project & you will see a new folder: amplify & a new file called aws-exports.js in the src directory. These files hold your project configuration.

Adding Authentication

To add authentication, we can use the following command:

amplify add auth
  • Do you want to use default authentication and security configuration? Default configuration
  • How do you want users to be able to sign in when using your Cognito User Pool? Username
  • What attributes are required for signing up? Email (keep default)

Now, we'll run the push command and the cloud resources will be created in our AWS account.

amplify push

To view the service you can run the console command the feature you'd like to view:

amplify console auth

Configuring the React applicaion

Now, our resources are created & we can start using them!

The first thing we need to do is to configure our React application to be aware of our new AWS Amplify project. We can do this by referencing the auto-generated aws-exports.js file that is now in our src folder.

To configure the app, open src/index.js and add the following code below the last import:

import Amplify from 'aws-amplify'
import config from './aws-exports'
Amplify.configure(config)

Now, our app is ready to start using our AWS services.

Using the withAuthenticator component

To add authentication, we'll go into src/App.js and first import the withAuthenticator HOC (Higher Order Component) from aws-amplify-react:

src/App.js

import { withAuthenticator } from 'aws-amplify-react'

Next, we'll wrap our default export (the App component) with the withAuthenticator HOC:

export default withAuthenticator(App, { includeGreetings: true })
# run the app

npm start

Now, we can run the app and see that an Authentication flow has been added in front of our App component. This flow gives users the ability to sign up & sign in.

To view the new user that was created in Cognito, go back to the dashboard at https://console.aws.amazon.com/cognito/. Also be sure that your region is set correctly.

Accessing User Data

We can access the user's info now that they are signed in by calling Auth.currentAuthenticatedUser().

src/App.js

import React, { useEffect } from 'react'
import { Auth } from 'aws-amplify'

function App() {
  useEffect(() => {
    Auth.currentAuthenticatedUser()
      .then(user => console.log({ user }))
      .catch(error => console.log({ error }))
  })
  return (
    <div className="App">
      <p>
        Edit <code>src/App.js</code> and save to reload.
      </p>
    </div>
  )
}

export default App

Custom authentication strategies

The withAuthenticator component is a really easy way to get up and running with authentication, but in a real-world application we probably want more control over how our form looks & functions.

Let's look at how we might create our own authentication flow.

To get started, we would probably want to create input fields that would hold user input data in the state. For instance when signing up a new user, we would probably need 4 user inputs to capture the user's username, email, password, & phone number.

To do this, we could create some initial state for these values & create an event handler that we could attach to the form inputs:

// initial state
import React, { useReducer } from 'react'

// define initial state
const initialState = {
  username: '', password: '', email: ''
}

// create reducer
function reducer(state, action) {
  switch(action.type) {
    case 'SET_INPUT':
      return { ...state, [action.inputName]: action.inputValue }
    default:
      return state
  }
}

// useReducer hook creates local state
const [state, dispatch] = useReducer(reducer, initialState)

// event handler
function onChange(e) {
  dispatch({
    type: 'SET_INPUT',
    inputName: e.target.name,
    inputValue: e.target.value
  })
}

// example of usage with input
<input
  name='username'
  placeholder='username'
  value={state.username}
  onChange={onChange}
/>

We'd also need to have a method that signed up & signed in users. We can use the Auth class to do this. The Auth class has over 30 methods including things like signUp, signIn, confirmSignUp, confirmSignIn, & forgotPassword. These functions return a promise so they need to be handled asynchronously.

// import the Auth component
import { Auth } from 'aws-amplify'

// Class method to sign up a user
async function signUp() {
  const { username, password, email } = state
  try {
    await Auth.signUp({ username, password, attributes: { email }})
    console.log('user successfully signed up!')
  } catch (err) {
    console.log('error signing up user...', err)
  }
}

<button onClick={signUp}>Sign Up</button>

Adding a GraphQL API

To add a GraphQL API, we can use the following command:

amplify add api

Answer the following questions

  • Please select from one of the above mentioned services GraphQL
  • Provide API name: CryptoGraphQL
  • Choose an authorization type for the API API key
  • Do you have an annotated GraphQL schema? N
  • Do you want a guided schema creation? Y
  • What best describes your project: Single object with fields (e.g. β€œTodo” with ID, name, description)
  • Do you want to edit the schema now? (Y/n) Y

When prompted, update the schema to the following:

type Coin @model {
  id: ID!
  clientId: ID
  name: String!
  symbol: String!
  price: Float!
}

Next, let's push the configuration to our account:

amplify push
  • Do you want to generate code for your newly created GraphQL API Y
  • Choose the code generation language target: javascript
  • Enter the file name pattern of graphql queries, mutations and subscriptions: (src/graphql/**/*.js)
  • Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions? Y
  • Enter maximum statement depth [increase from default if your schema is deeply nested] 2

To view the service you can run the console command the feature you'd like to view:

amplify console api

Adding mutations from within the AWS AppSync Console

In the AWS AppSync console, open your API & then click on Queries.

Execute the following mutation to create a new coin in the API:

mutation createCoin {
  createCoin(input: {
    name: "Bitcoin"
    symbol: "BTC"
    price: 9000
  }) {
    id name symbol price
  }
}

Now, let's query for the coin:

query listCoins {
  listCoins {
    items {
      id
      name
      symbol
      price
    }
  }
}

We can even add search / filter capabilities when querying:

query listCoins {
  listCoins(filter: {
    price: {
      gt: 2000
    }
  }) {
    items {
      id
      name
      symbol
      price
    }
  }
}

Interacting with the GraphQL API from our client application - Querying for data

Now that the GraphQL API is created we can begin interacting with it!

The first thing we'll do is perform a query to fetch data from our API.

To do so, we need to define the query, execute the query, store the data in our state, then list the items in our UI.

src/App.js

// src/App.js
import React, { useEffect, useState } from 'react'

// imports from Amplify library
import { API, graphqlOperation } from 'aws-amplify'
import { withAuthenticator } from 'aws-amplify-react'

// import query
import { listCoins } from './graphql/queries'

function App() {
  const [coins, updateCoins] = useState([])

  useEffect(() => {
    getData()
  }, [])

  async function getData() {
    try {
      const coinData = await API.graphql(graphqlOperation(listCoins))
      console.log('data from API: ', coinData)
      updateCoins(coinData.data.listCoins.items)
    } catch (err) {
      console.log('error fetching data..', err)
    }
  }

  return (
    <div>
      {
        coins.map((c, i) => (
          <div key={i}>
            <h2>{c.name}</h2>
            <h4>{c.symbol}</h4>
            <p>{c.price}</p>
          </div>
        ))
      }
    </div>
  )
}

export default withAuthenticator(App, { includeGreetings: true })

Performing mutations

Now, let's look at how we can create mutations. Let's change the component to use a useReducer hook.

// src/App.js
import React, { useEffect, useReducer } from 'react'
import { API, graphqlOperation } from 'aws-amplify'
import { withAuthenticator } from 'aws-amplify-react'
import { listCoins } from './graphql/queries'
import { createCoin as CreateCoin } from './graphql/mutations'

// import uuid to create a unique client ID
import uuid from 'uuid/v4'

const CLIENT_ID = uuid()

// create initial state
const initialState = {
  name: '', price: '', symbol: '', coins: []
}

// create reducer to update state
function reducer(state, action) {
  switch(action.type) {
    case 'SETCOINS':
      return { ...state, coins: action.coins }
    case 'SETINPUT':
      return { ...state, [action.key]: action.value }
    default:
      return state
  }
}

function App() {
  const [state, dispatch] = useReducer(reducer, initialState)

  useEffect(() => {
    getData()
  }, [])

  async function getData() {
    try {
      const coinData = await API.graphql(graphqlOperation(listCoins))
      console.log('data from API: ', coinData)
      dispatch({ type: 'SETCOINS', coins: coinData.data.listCoins.items})
    } catch (err) {
      console.log('error fetching data..', err)
    }
  }

  async function createCoin() {
    const { name, price, symbol } = state
    if (name === '' || price === '' || symbol === '') return
    const coin = {
      name, price: parseFloat(price), symbol, clientId: CLIENT_ID
    }
    const coins = [...state.coins, coin]
    dispatch({ type: 'SETCOINS', coins })
    console.log('coin:', coin)
    
    try {
      await API.graphql(graphqlOperation(CreateCoin, { input: coin }))
      console.log('item created!')
    } catch (err) {
      console.log('error creating coin...', err)
    }
  }

  // change state then user types into input
  function onChange(e) {
    dispatch({ type: 'SETINPUT', key: e.target.name, value: e.target.value })
  }

  // add UI with event handlers to manage user input
  return (
    <div>
      <input
        name='name'
        placeholder='name'
        onChange={onChange}
        value={state.name}
      />
      <input
        name='price'
        placeholder='price'
        onChange={onChange}
        value={state.price}
      />
      <input
        name='symbol'
        placeholder='symbol'
        onChange={onChange}
        value={state.symbol}
      />
      <button onClick={createCoin}>Create Coin</button>
      {
        state.coins.map((c, i) => (
          <div key={i}>
            <h2>{c.name}</h2>
            <h4>{c.symbol}</h4>
            <p>{c.price}</p>
          </div>
        ))
      }
    </div>
  )
}

export default withAuthenticator(App, { includeGreetings: true })

GraphQL Subscriptions

Next, let's see how we can create a subscription to subscribe to changes of data in our API.

To do so, we need to define the subscription, listen for the subscription, & update the state whenever a new piece of data comes in through the subscription.

// import the subscription
import { onCreateCoin } from './graphql/subscriptions'

// update reducer
function reducer(state, action) {
  switch(action.type) {
    case 'SETCOINS':
      return { ...state, coins: action.coins }
    case 'SETINPUT':
      return { ...state, [action.key]: action.value }
    // new πŸ‘‡
    case 'ADDCOIN':
      return { ...state, coins: [...state.coins, action.coin] }
    default:
      return state
  }
}

// subscribe in useEffect
useEffect(() => {
  const subscription = API.graphql(graphqlOperation(onCreateCoin)).subscribe({
      next: (eventData) => {
        const coin = eventData.value.data.onCreateCoin
        if (coin.clientId === CLIENT_ID) return
        dispatch({ type: 'ADDCOIN', coin  })
      }
  })
  return () => subscription.unsubscribe()
}, [])

Adding Authorization to the GraphQL API

To add authorization to the API, we can re-configure the API to use our cognito identity pool. To do so, we can run amplify configure api:

amplify configure api
  • Please select from one of the below mentioned services: GraphQL
  • Choose an authorization type for the API: Amazon Cognito User Pool

Next, we'll run amplify push:

amplify push
  • Do you want to update code for your updated GraphQL API N

Now, we can only access the API with a logged in user.

Adding fine-grained access controls to the GraphQL API

Next, let's add a field that can only be accessed by the current user.

To do so, we'll update the schema to add the following new type below the existing Coin type:

type Note @model @auth(rules: [{allow: owner}]) {
  id: ID!
  title: String!
  description: String
}

Next, we'll deploy the updates to our API:

amplify push
  • Do you want to update code for your updated GraphQL API: Y
  • Do you want to generate GraphQL statements (queries, mutations and subscription) based on your schema types? Y

Now, the operations associated with this field will only be accessible by the creator of the item.

To test it out, try creating a new user & accessing a note from another user.

To test the API out in the AWS AppSync console, it will ask for you to Login with User Pools. The form will ask you for a ClientId. This ClientId is located in src/aws-exports.js in the aws_user_pools_web_client_id field.

Adding a Serverless Function

Adding a basic Lambda Function

To add a serverless function, we can run the following command:

amplify add function

Answer the following questions

  • Provide a friendly name for your resource to be used as a label for this category in the project: basiclambda
  • Provide the AWS Lambda function name: basiclambda
  • Choose the function template that you want to use: Hello world function
  • Do you want to access other resources created in this project from your Lambda function? No
  • Do you want to edit the local lambda function now? Y

This should open the function package located at amplify/backend/function/basiclambda/src/index.js.

Edit the function to look like this, & then save the file.

exports.handler = function (event, context) {
  console.log('event: ', event)
  const body = {
    message: "Hello world!"
  }
  const response = {
    statusCode: 200,
    body
  }
  context.done(null, response);
}

Next, we can test this out by running:

amplify function invoke basiclambda

Using service: Lambda, provided by: awscloudformation

  • Provide the name of the script file that contains your handler function: index.js
  • Provide the name of the handler function to invoke: handler

You'll notice the following output from your terminal:

Running "lambda_invoke:default" (lambda_invoke) task

event:  { key1: 'value1', key2: 'value2', key3: 'value3' }

Success!  Message:
------------------
{"statusCode":200,"body":{"message":"Hello world!"}}

Done.
Done running invoke function.

Where is the event data coming from? It is coming from the values located in event.json in the function folder (amplify/backend/function/basiclambda/src/event.json). If you update the values here, you can simulate data coming arguments the event.

Feel free to test out the function by updating event.json with data of your own.

Adding a function running an express server

Next, we'll build a function that will be running an Express server inside of it.

This new function will fetch data from a cryptocurrency API & return the values in the response.

To get started, we'll create a new function:

amplify add function

Answer the following questions

  • Provide a friendly name for your resource to be used as a label for this category in the project: cryptofunction
  • Provide the AWS Lambda function name: cryptofunction
  • Choose the function template that you want to use: Serverless express function (Integration with Amazon API Gateway)
  • Do you want to access other resources created in this project from your Lambda function? No
  • Do you want to edit the local lambda function now? Y

This should open the function package located at amplify/backend/function/cryptofunction/src/index.js.

Here, we'll add the following code & save the file:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
  next()
});
// below the last app.use() method, add the following code πŸ‘‡
const axios = require('axios')

app.get('/coins', function(req, res) {
  let apiUrl = `https://api.coinlore.com/api/tickers?start=0&limit=10`

  console.log(req.query);
  if (req && req.query) {
    const { start = 0, limit = 10 } = req.query
    apiUrl = `https://api.coinlore.com/api/tickers/?start=${start}&limit=${limit}`
  }
  axios.get(apiUrl)
    .then(response => {
      res.json({
        coins: response.data.data
      })
    })
    .catch(err => res.json({ error: err }))
})

Next, we'll install axios in the function package:

cd amplify/backend/function/cryptofunction/src

npm install axios

Next, change back into the root directory.

Now we can test this function out:

amplify function build
amplify function invoke cryptofunction

This will start up the node server. We can then make curl requests agains the endpoint:

curl 'localhost:3000/coins?start=0&limit=1'

If we'd like to test out the query parameters, we can update the event.json to add the following:

{
    "httpMethod": "GET",
    "path": "/coins",
    "query": {
        "start": "0",
        "limit": "1"
    }
}

When we invoke the function these query parameters will be passed in & the http request will be made immediately.

Adding a REST API

Now that we've created the cryptocurrency Lambda function let's add an API endpoint so we can invoke it via http.

To add the REST API, we can use the following command:

amplify add api

Answer the following questions

  • Please select from one of the above mentioned services REST
  • Provide a friendly name for your resource that will be used to label this category in the project: cryptoapi
  • Provide a path (e.g., /items) /coins
  • Choose lambda source Use a Lambda function already added in the current Amplify project
  • Choose the Lambda function to invoke by this path: cryptofunction
  • Restrict API access Y
  • Who should have access? Authenticated users only
  • What kind of access do you want for Authenticated users read/create/update/delete
  • Do you want to add another path? (y/N) N

Now the resources have been created & configured & we can push them to our account:

amplify push

Interacting with the new API

Now that the API is created we can start sending requests to it & interacting with it.

Let's request some data from the API:

// src/App.js
import React, { useEffect, useState } from 'react'
import { API } from 'aws-amplify'
import { withAuthenticator } from 'aws-amplify-react'

function App() {
  const [coins, updateCoins] = useState([])

  async function getData() {
    try {
      // const data = await API.get('cryptoapi', '/coins')
      const data = await API.get('cryptoapi', '/coins?limit=5&start=100')
      console.log('data from Lambda REST API: ', data)
      updateCoins(data.coins)
    } catch (err) {
      console.log('error fetching data..', err)
    }
  }

  useEffect(() => {
    getData()
  }, [])

  return (
    <div>
      {
        coins.map((c, i) => (
          <div key={i}>
            <h2>{c.name}</h2>
            <p>{c.price_usd}</p>
          </div>
        ))
      }
    </div>
  )
}

export default withAuthenticator(App, { includeGreetings: true })

Challenge

Refactor the above component to use useReducer instead of useState to add an additional loading parameter to the initial state to indicate that the app is fetching and loading when launched.

Working with Storage

To add storage, we can use the following command:

amplify add storage

Answer the following questions

  • Please select from one of the below mentioned services Content (Images, audio, video, etc.)
  • Please provide a friendly name for your resource that will be used to label this category in the project: YOURAPINAME
  • Please provide bucket name: YOURUNIQUEBUCKETNAME
  • Who should have access: Auth users only
  • What kind of access do you want for Authenticated users create/update, read, delete
amplify push

Now, storage is configured & ready to use.

What we've done above is created configured an Amazon S3 bucket that we can now start using for storing items.

For example, if we wanted to test it out we could store some text in a file like this:

import { Storage } from 'aws-amplify'

// create function to work with Storage
function addToStorage() {
  await Storage.put('javascript/MyReactComponent.js', `
    import React from 'react'
    const App = () => (
      <p>Hello World</p>
    )
    export default App
  `)
  console.log('data stored in S3!')
}

// add click handler
<button onClick={addToStorage}>Add To Storage</button>

This would create a folder called javascript in our S3 bucket & store a file called MyReactComponent.js there with the code we specified in the second argument of Storage.put.

To view the new bucket that was created in S3, go to the dashboard at https://console.aws.amazon.com/s3. Also be sure that your region is set correctly.

If we want to read everything from this folder, we can use Storage.list:

readFromStorage() {
  const data = Storage.list('javascript/')
  console.log('data from S3: ', data)
}

If we only want to read the single file, we can use Storage.get:

readFromStorage() {
  const data = Storage.get('javascript/MyReactComponent.js')
  console.log('data from S3: ', data)
}

If we wanted to pull down everything, we can use Storage.list:

function readFromStorage() {
  const data = Storage.list('')
  console.log('data from S3: ', data)
}

Working with images

Here's how you can store an image:

function App() {
  async function onChange(e) {
    const file = e.target.files[0];
    await Storage.put('example.png', file)
    console.log('image successfully stored!')
  }

  return (
    <input
      type="file" accept='image'
      onChange={(e) => this.onChange(e)}
    />
  )
}

Here's how you can read and display an image:

import React, { useState } from 'react'

function App() {
  const [imageUrl, updateImage] = useState('')

  async function fetchImage() {
    const imagePath = await Storage.get('example.png')
    updateImage(imagePath)
  }

  return (
    <div>
      <img src={imageUrl} />
      <button onClick={fetchImage}>Fetch Image</button>
    </div>
  )
}

We can even use the S3Album component, one of a few components in the AWS Amplify React library to create a pre-configured photo picker:

import { S3Album, withAuthenticator } from 'aws-amplify-react'

function App() {
  return (
    <div className="App">
      <S3Album path={''} picker />
    </div>
  );
}

Adding Analytics

To add analytics, we can use the following command:

amplify add analytics

Next, we'll be prompted for the following:

  • Provide your pinpoint resource name: amplifyanalytics
  • Apps need authorization to send analytics events. Do you want to allow guest/unauthenticated users to send analytics events (recommended when getting started)? Y
  • overwrite YOURFILEPATH-cloudformation-template.yml Y

Recording events

Now that the service has been created we can now begin recording events.

To record analytics events, we need to import the Analytics class from Amplify & then call Analytics.record:

import { Analytics } from 'aws-amplify'

state = {username: ''}

async componentDidMount() {
  try {
    const user = await Auth.currentAuthenticatedUser()
    this.setState({ username: user.username })
  } catch (err) {
    console.log('error getting user: ', err)
  }
}

recordEvent = () => {
  Analytics.record({
    name: 'My test event',
    attributes: {
      username: this.state.username
    }
  })
}

<button onClick={this.recordEvent}>Record Event</button>

Working with multiple environments

You can create multiple environments for your application in which to create & test out new features without affecting the main environment which you are working on.

When you create a new environment from an existing environment, you are given a copy of the entire backend application stack from the original project. When you make changes in the new environment, you are then able to test these new changes in the new environment & merge only the changes that have been made since the new environment was created back into the original environment.

Let's take a look at how to create a new environment. In this new environment, we'll re-configure the GraphQL Schema to have another field for the coin rank.

First, we'll initialize a new environment using amplify env add:

amplify env add

> Do you want to use an existing environment? No
> Enter a name for the environment: apiupdate
> Do you want to use an AWS profile? Y
> Please choose the profile you want to use: amplify-workshop-profile

Once the new environment is initialized, we should be able to see some information about our environment setup by running:

amplify env list

| Environments |
| ------------ |
| dev          |
| *apiupdate   |

Now we can update the GraphQL Schema in amplify/backend/api/CryptoGraphQL/schema.graphql to the following (adding the rank field):

type Coin {
	id: ID!
	clientId: ID
	name: String!
	symbol: String!
	price: Float!
  rank: Int
}

Now, we can create this new stack by running amplify push:

amplify push

After we test it out, we can now merge it into our original local environment:

amplify env checkout local

Next, run the status command:

amplify status

You should now see an Update operation:

Current Environment: local

| Category | Resource name   | Operation | Provider plugin   |
| -------- | --------------- | --------- | ----------------- |
| Api      | CryptoGraphQL   | Update    | awscloudformation |
| Auth     | cognito75a8ccb4 | No Change | awscloudformation |

To deploy the changes, run the push command:

amplify push
  • Do you want to update code for your updated GraphQL API? Y
  • Do you want to generate GraphQL statements? Y

Now, the changes have been deployed & we can delete the apiupdate environment:

amplify env remove apiupdate

Do you also want to remove all the resources of the environment from the cloud? Y

Now, we should be able to run the list command & see only our main environment:

amplify env list

Deploying via the Amplify Console

For hosting, we can use the Amplify Console to deploy the application.

The first thing we need to do is create a new GitHub repo for this project. Once we've created the repo, we'll copy the URL for the project to the clipboard & initialize git in our local project:

git init

git remote add origin [email protected]:username/project-name.git

git add .

git commit -m 'initial commit'

git push origin master

Next we'll visit the Amplify Console in our AWS account at https://eu-west-1.console.aws.amazon.com/amplify/home.

Here, we'll click Get Started to create a new deployment. Next, authorize Github as the repository service.

Next, we'll choose the new repository & branch for the project we just created & click Next.

In the next screen, we'll create a new role & use this role to allow the Amplify Console to deploy these resources & click Next.

Finally, we can click Save and Deploy to deploy our application!

Now, we can push updates to Master to update our application.

React Native

AWS Amplify also has framework support for React Native.

To get started with using AWS Amplify with React Native, we'll need to install the AWS Amplify React Native package & then link the dependencies.

npm install aws-amplify-react-native

# If using Expo, you do not need to link these two libraries as they are both part of the Expo SDK.
react-native link amazon-cognito-identity-js
react-native link react-native-vector-icons

Implementing features with AWS Amplify in React Native is the same as the features implemented in the other steps of this workshop. The only difference is that you will be working with React Native primitives vs HTML elements.

Removing Services

If at any time, or at the end of this workshop, you would like to delete a service from your project & your account, you can do this by running the amplify remove command:

amplify remove auth

amplify push

If you are unsure of what services you have enabled at any time, you can run the amplify status command:

amplify status

amplify status will give you the list of resources that are currently enabled in your app.

Deleting entire project

amplify delete

More Repositories

1

awesome-aws-amplify

Curated list of AWS Amplify Resources
1,782
star
2

polygon-ethereum-nextjs-marketplace

A full stack digital marketplace running on Ethereum with Polygon & Next.js
JavaScript
1,303
star
3

full-stack-ethereum

Building full stack apps with Solidity, Ethers.js, Hardhat, and The Graph
TypeScript
802
star
4

react-native-ai

Full stack framework for building cross-platform mobile AI apps
TypeScript
794
star
5

semantic-search-nextjs-pinecone-langchain-chatgpt

Embeds text files into vectors, stores them on Pinecone, and enables semantic search using GPT3 and Langchain in a Next.js UI
TypeScript
739
star
6

awesome-aws-appsync

Curated list of AWS AppSync Resources
625
star
7

gpt-travel-advisor

reference architecture for building a travel application with GPT3
TypeScript
543
star
8

foundry-cheatsheet

522
star
9

complete-guide-to-full-stack-solana-development

Code examples for the blog post titled The Complete Guide to Full Stack Solana Development with React, Anchor, Rust, and Phantom
JavaScript
474
star
10

dynamodb-documentclient-cheat-sheet

DynamoDB JavaScript DocumentClient cheat sheet
443
star
11

full-stack-web3

A full stack web3 on-chain blog and CMS
JavaScript
420
star
12

next.js-amplify-workshop

AWS Amplify Next.js workshop
JavaScript
360
star
13

gatsby-auth-starter-aws-amplify

Starter Project with Authentication with Gatsby & AWS Amplify
JavaScript
320
star
14

gpt-fine-tuning-with-nodejs

GPT Fine-Tuning using Node.js - an easy to use starter project
JavaScript
250
star
15

full-stack-serverless-code

Code examples for my book Full Stack Serverless with O'Reilly Publications
JavaScript
244
star
16

openai-functions-god-app

TypeScript
240
star
17

heard

React Native Enterprise Social Messaging App
JavaScript
236
star
18

aws-appsync-react-workshop

Building real-time offline-ready Applications with React, GraphQL & AWS AppSync
JavaScript
228
star
19

nextjs-chatgpt-plugin-starter

ChatGPT plugin starter project using Next.js
TypeScript
209
star
20

micro-frontend-example

Building Micro Frontends with React, Vue, and Single-spa
JavaScript
207
star
21

amplify-photo-sharing-workshop

Building full-stack cloud apps with AWS Amplify and React
JavaScript
197
star
22

chicken-tikka-masala-recipe

Nader's chicken tikka masala recipe
PHP
193
star
23

decentralized-identity-example

An authentication system built with Ceramic & self.id
JavaScript
190
star
24

building-a-subgraph-workshop

In this workshop you'll learn how to build an NFT Subgraph using any smart contract or smart contracts.
TypeScript
165
star
25

graphql-recipes

A list of GraphQL recipes that, when used with the Amplify CLI, will deploy an entire AWS AppSync GraphQL backend.
158
star
26

next.js-cdk-amplify-workshop

Full stack serverless workshop with Next.js, CDK, and AWS Amplify
JavaScript
157
star
27

supabase-next.js

Full stack app built with Supabase and Next.js
JavaScript
152
star
28

titter

Decentralized Twitter prototype built with Polygon, GraphQL, Next.js, Ceramic, Arweave, and Bundlr
JavaScript
152
star
29

supabase-nextjs-auth

Example project implementing authentication, authorization, and routing with Next.js and Supabase
JavaScript
151
star
30

react-native-in-action

React Native in Action, written for Manning Publications
146
star
31

prompt-engineering-for-javascript-developers

Notes summarized from ChatGPT Prompt Engineering for Developers by DeepLearning.ai
145
star
32

write-with-me

Real-time Collaborative Markdown Editor
JavaScript
144
star
33

foundry-workshop

Building and testing smart contracts with Foundry
Solidity
144
star
34

aws-amplify-workshop-react-native

Building Cloud-enabled Mobile Applications with React Native & AWS Amplify
JavaScript
139
star
35

lens-protocol-frontend

Example of a basic front end built on Lens Protocol
JavaScript
136
star
36

cdk-graphql-backend

A real-time GraphQL API deployed with CDK using AWS AppSync, AWS Lambda, and DynamoDB
TypeScript
131
star
37

create-new-cli

Create your own CLI using a series of simple commands.
JavaScript
128
star
38

perma

Perma is a web3 prototype of permanent video storage and viewing using Next.js, Arweave, and Bundlr.
JavaScript
120
star
39

appsync-graphql-real-time-canvas

Collaborative real-time canvas built with GraphQL, AWS AppSync, & React Canvas Draw
JavaScript
119
star
40

full-stack-ethereum-marketplace-workshop

Build a Full Stack Marketplace on Ethereum with React, Solidity, Hardhat, and Ethers.js
JavaScript
118
star
41

amplify-auth-demo

Demo of OAuth + Username / Password authentication in AWS Amplify
JavaScript
111
star
42

hype-beats

Real-time Collaborative Beatbox with React & GraphQL
JavaScript
111
star
43

next.js-authentication-aws

This project deploys a Next.js project to AWS with comprehensive authentication enabled
JavaScript
104
star
44

this-or-that

This or that - Real-time atomic voting app built with AWS Amplify
CSS
98
star
45

react-native-deep-linking

Deep Linking set up in a React Native App
Objective-C
96
star
46

beginning-webpack

This repository goes along with the medium post titled "Beginner's guide to Webpack"
JavaScript
95
star
47

react-native-bootcamp

React Native Bootcamp Materials for TylerMcginnis.com
94
star
48

react-native-mobx-list-app

React Native + Mobx List Application
JavaScript
91
star
49

appsync-auth-and-unauth

How to allow both authenticated & unauthenticated access to an API
JavaScript
91
star
50

aws-amplify-workshop-web

Building web applications with React & AWS Amplify
JavaScript
90
star
51

full-stack-ethereum-workshop

Building full stack dapps on the EVM with Hardhat, React, and Ethers.js
HTML
89
star
52

sign-in-with-ethereum-authentication-flow

Example implementation of how to implement Sign In with Ethereum
JavaScript
85
star
53

react-notes

React notes tutorial
JavaScript
84
star
54

vue-graphql-appsync

Vue example using GraphQL with AWS AppSync
JavaScript
81
star
55

lens-pwa

Lens PWA
TypeScript
80
star
56

amplify-datastore-example

Example of basic app using Amplify DataStore
JavaScript
78
star
57

custom-nft-subgraph-workshop

78
star
58

lens-shadcn

Example application combining Lens Protocol, WalletConnect, Next.js, and ShadCN
TypeScript
78
star
59

amplify-with-cdk

An example project showing how to mix CDK with AWS Amplify
TypeScript
77
star
60

react-aws-live-streaming

This project shows how to implement a live-streaming platform using AWS and React
JavaScript
73
star
61

react-native-navigation-v2

Up and running with React Native Navigation - V2 - by Wix
JavaScript
73
star
62

bored-ape-yacht-club-api-and-subgraph

Graph Protocol Subgraph / API for querying Bored Ape Yacht Club NFT data with full text search
TypeScript
70
star
63

react-appsync-graphql-recipe-app

Example application using React + AWS AppSync + GraphQL
JavaScript
70
star
64

react-amplify-appsync-files-s3

An example project showing how to upload and download public and private images in GraphQL using AppSync and S3
JavaScript
70
star
65

react-strict-dom-example

JavaScript
69
star
66

full-stack-react-native-appsync-workshop

Building Full Stack GraphQL Applications with React Native & AWS AppSync
JavaScript
67
star
67

speakerchat

SpeakerChat - Real-time Event Q&A Platform with Markdown Support
JavaScript
66
star
68

react-p2p-messaging

A real-time peer-to-peer messaging app built with React & Gun.js
JavaScript
65
star
69

graphql-suspense

Lightweight component that allows you to interact with a GraphQL API using React Suspense
JavaScript
65
star
70

nuxt-supabase-full-multi-user-blog

Build a mult-user blogging app with Supabase and Nuxt.js
Vue
65
star
71

archive-forever

HTML
63
star
72

next.js-tailwind-authentication

A Next.js authentication starter built with Tailwind and AWS Amplify
JavaScript
63
star
73

near-subgraph-workshop

Building a NEAR NFT API with The Graph
60
star
74

react-authentication-in-depth

Example of User Authentication using React with React Router and AWS Amplify
JavaScript
60
star
75

graphql-api-cdk-serverless-postgres

TypeScript
59
star
76

curious-cases-of-graphql

Code and examples from my talk - Curious Cases of GraphQL
57
star
77

gasless-transactions-example

Example of Gasless Transactions with Biconomy
JavaScript
57
star
78

react-chatbots

Building Chatbots with React, Amazon Lex, AWS Lambda, & AWS Amplify
JavaScript
57
star
79

xmtp-chat-app-nextjs

Real-time encrypted chat, built with XMTP and Next.js
TypeScript
57
star
80

react-native-lens-example

Example app built with React Native Lens UI Kit
JavaScript
55
star
81

lens-protocol-workshop

Introduction to web3 social media with Next.js and Lens Protocol
TypeScript
54
star
82

zora-nextjs-app

Example Full Stack App built with Next.js, Zora, Tailwind, and The Graph
TypeScript
54
star
83

draw-together

TypeScript
53
star
84

terminal-portfolio

TypeScript
51
star
85

arweave-workshop

JavaScript
50
star
86

lens-gated-publications

Example application implementing gated Lens posts, encryption, and decryption
JavaScript
49
star
87

graphql-search

Implementing Search in GraphQL using AWS AppSync & React Apollo
JavaScript
49
star
88

basic-amplify-storage-example

A basic example app showing how to add storage with Amazon S3
JavaScript
49
star
89

production-ready-vue-authentication

How to implement a real user authentication flow in Vue with Vue Router & AWS Amplify.
Vue
48
star
90

build-an-authenticated-api-with-cdk

Workshop - Build an authenticated CDK back end
TypeScript
48
star
91

real-time-image-tracking

Real-time image tracking with React, GraphQL, and AWS AppSync
JavaScript
48
star
92

appsync-lambda-ai

Demo of using a GraphQL resolver to hit a lambda function, then hit a few AI services, and return the response.
JavaScript
47
star
93

appsync-react-native-with-user-authorization

End to end React Native + AWS AppSync GraphQL application with queries, mutations, subscriptions, & user authentication & authorization
JavaScript
47
star
94

openzeppelin-nft-api

Building NFT APIs with OpenZeppelin and The Graph
46
star
95

cryptocoven-api

Cryptocoven Graph API
TypeScript
46
star
96

transilator

Text translation and synthesization Chrome plugin
JavaScript
46
star
97

xp-mobile-account-abstraction

TypeScript
45
star
98

react-native-navigator-experimental-redux

React Native Navigator Experimental with Redux
JavaScript
45
star
99

next.js-amplify-datastore

An example app using Amplify DataStore with Next.js for static site generation, pre-rendering, and SSR
JavaScript
45
star
100

full-stack-warp-arweave

JavaScript
44
star