{"id":13625206,"url":"https://github.com/amazon-archives/aws-mobile-react-sample","last_synced_at":"2025-04-16T06:32:11.858Z","repository":{"id":141667503,"uuid":"95498418","full_name":"amazon-archives/aws-mobile-react-sample","owner":"amazon-archives","description":"A React Starter App that displays how web developers can integrate their front end with AWS on the backend. The App interacts with AWS Cognito, API Gateway, Lambda and DynamoDB on the backend.","archived":true,"fork":false,"pushed_at":"2020-07-08T15:46:56.000Z","size":12584,"stargazers_count":659,"open_issues_count":3,"forks_count":165,"subscribers_count":57,"default_branch":"master","last_synced_at":"2024-08-01T22:04:27.588Z","etag":null,"topics":["api-gateway","aws","aws-amplify","aws-amplify-react","cognito","dynamodb","javascript","lambda","mobile-hub","react","s3","serverless"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/amazon-archives.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2017-06-26T23:34:27.000Z","updated_at":"2024-07-03T03:50:42.000Z","dependencies_parsed_at":null,"dependency_job_id":"5cfb6c88-30e7-46b6-ba4a-a4cfc99715b4","html_url":"https://github.com/amazon-archives/aws-mobile-react-sample","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/amazon-archives%2Faws-mobile-react-sample","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/amazon-archives%2Faws-mobile-react-sample/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/amazon-archives%2Faws-mobile-react-sample/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/amazon-archives%2Faws-mobile-react-sample/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/amazon-archives","download_url":"https://codeload.github.com/amazon-archives/aws-mobile-react-sample/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":223700305,"owners_count":17188295,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api-gateway","aws","aws-amplify","aws-amplify-react","cognito","dynamodb","javascript","lambda","mobile-hub","react","s3","serverless"],"created_at":"2024-08-01T21:01:52.443Z","updated_at":"2024-11-08T14:30:47.353Z","avatar_url":"https://github.com/amazon-archives.png","language":"JavaScript","readme":"# AWS Mobile React Starter Kit\n\n**This sample application has been archived in favor of [Amplify JS Samples](https://github.com/aws-amplify/amplify-js-samples). While the archived repository will still work, please go +1 this feature request for [AWS Mobile React Starter Kit sample](https://github.com/aws-amplify/amplify-js-samples/issues/15) if you are looking to use this sample.**\n\nBootstrap a React application on AWS. This sample automatically provisions a Serverless infrastructure with authentication, authorization, website hosting, API access and database operations. It also includes user registration and MFA support. The sample use case is a \"Restaurant\" ordering system where after a user registers and logs in they can view different restaurant menus, select items and place orders.\n\nThis starter uses the [AWS Amplify JavaScript library](https://github.com/aws/aws-amplify) to add cloud support to the application.\n\n### Quicklinks\n - [Getting started](#getstarted)\n - [Building and deploying](#builddeploy)\n - [Using Registration and Login components in your App](#reglogin)\n - [Using the REST client in your App](#restclient)\n - [Modifying Express routes in Lambda for your App](#lambdamodify)\n\n### Architecture Overview\n\nYou will be building a React application with User Registration \u0026 Sign-in that allows you to perform CRUD operations against a DynamoDB table by using an [Express](https://expressjs.com) application running in AWS Lambda. Lambda will be invoked by API Gateway using Proxy Integration with greedy paths that only authenticated users can access. The Express server is running with the [AWS Serverless Express framework](https://github.com/awslabs/aws-serverless-express).\n\n![Alt Text](/media/ReactServerless.PNG)\n\nAWS Services used:\n* Amazon Cognito User Pools\n* Amazon Cognito Federated Identities\n* Amazon API Gateway\n* AWS Lambda\n* Amazon DynamoDB\n* Amazon S3\n* Amazon CloudFront\n\n### Prerequisites\n\n+ [AWS Account](https://aws.amazon.com/mobile/details/)\n\n+ [NodeJS](https://nodejs.org/en/download/) with [NPM](https://docs.npmjs.com/getting-started/installing-node)\n\n+ [AWS Mobile CLI](https://github.com/aws/awsmobile-cli)\n  - `npm install -g awsmobile-cli`\n\n\n## Getting Started \u003ca name=\"getstarted\"\u003e\u003c/a\u003e\n\n1. Create your backend resources and download the sample code inside of my-project folder.\n    ```\n    $ awsmobile start my-project react\n    ```\n\n\n2. Finally run the app:\n\n    ```\n    $ cd my-project\n    $ awsmobile run\n    ```\n\n Done!\n\n## Publish the app\n\nTo publish your application to Amazon S3 and Amazon CloudFront:\n\n  ```\n    $ awsmobile publish\n  ```\n\n  * _Alternatively using NPM_:\n\n  ```\n    $ npm install\n    $ npm start\n  ```\n\n Done!\n\n ## Enabling federated sign-in\n\nFederated sign-in controls for Google, Facebook and Amazon are provided in the user interface by default; however, the client ids for these providers are not valid.  Dummy values are provided in the ```federated``` object within index.js so that the user interface controls appear.  You can remove any of the controls by deleting the appropriate keys from the ```federated``` object.\n\nYou may also remove federated sign-in entirely by removing the 'federated={federated}' statement from the ReactDOM.render call in index.js. \n\nEnabling federated sign-in is a three step process:\n\n  1.  Register your application with the provider(s).  \n\n      The identity providers will request information about your application, and will supply you with an application ID and other keys that your application(s) will use for authentication.  Keep in mind that some providers may supply separate application IDs for multiple applications even when these applications are sharing AWS resources. \n\n  2.  Enable the provider for your application.\n\n      There are multiple ways of enabling a federated identity provider for your application.\n\n      *The AWS Mobile CLI* provides commands for enabling providers.\n\n      ```\n      $ awsmobile user-signin enable\n      $ awsmobile user-signin configure\n\n      If you select Facebook:\n      ? Facebook App ID xxxxxxx\n\n      If you select Google:\n      ? Google Web App Client ID xxxxxxx\n      ? Google Android Client ID xxxxxxx\n      ? Google iOS Client ID xxxxxxx\n\n\n      $awsmobile push\n      ```\n\n---\n\n      AWS Mobile Hub allows you to register an identity provider by accessing the User Sign-In section and selecting the provider under the Add sign-in Providers section.\n\n---\n\n      The AWS Cognito and IAM Consoles allow you to register identity providers as well.  Please see the respective documentation for these services.\n\n  3.  Once you have registered your application with your federated identity provider(s) and have enabled federated identity for your application, make sure to include your client ids in the ```federated``` object in index.js.\n\nLinks to additional information about federated identity providers [may be found here](https://aws.github.io/aws-amplify/media/federated_identity_setup).\n\n## Using the default Greetings Component\n\nThis application is using a custom nav with it's own logout button.  However, the **Authenticator** component can provide a default **Greetings** component which displays the username and a login/logout button.  You can enable this by removing the **Greetings** element from the **Authenticator's 'hide' array** in index.js. \n\n## Application walkthrough\n\n![Alt Text](/media/Mainpage.PNG)\n\n  1. Open a browser to `http://localhost:8080` and view the **Authenticator** component. Choose **Sign Up Now** and type in a username, password, email address and phone number. \n  \n  Alternatively, if you have enabled federated sign-in you can select the provider and skip to step 5.\n\n  2. You should recieve a 6-digit verification code via SMS. Type this into the screen and select **Validate**.\n\n  3. Now that you are registered you will be redirected to the Login page. Type in the username and password then select **Login**.\n\n  4. You will recieve another SMS verification code. This is the MFA flow upon user login. Enter the code into the screen and select **Validate**.\n\n  5. The application demonstrates both loading sample data into the database as well as listing data and navigation. As a first time user press **Insert Restaurants** to load sample restaurants into the application.\n\n  * _The sample data is stored inside the imported Lambda function (init.js). This demonstrates how Lambda code can be used with Express to insert records into DynamoDB. The request from the client to API Gateway is signed using [AWS Signature Version 4](http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html) with the credentials returned from Amazon Cognito when the user logged into the application. Refer to the advanced section of this document for more information on using this in your designs._\n\n  6. Now that data has been loaded select **List Restaurants** to display the list of restaurants that were added in the previous step. This also uses the signing process described above.\n\n  7. Click on the name of a restaurant to see a menu.\n\n  8. Press **Order** to place an order in the system. This will add an order entry to a DynamoDB table as well as store information in the local browser for tracking.\n\n  9. Press **Orders** in the navigation bar. You will see some information immediately from local storage and other information returned asynchronously from a call to API Gateway.\n\n  * _The navigation bar is optimized to work across desktop and mobile browsers. It will show either at the top of the page or in a collapsible bar on the left for mobile form factors_\n\n  10. Select **Logout** in the navigation bar to return the user to the home page.\n\n\n## Building and deploying \u003ca name=\"builddeploy\"\u003e\u003c/a\u003e\n\nThe following steps outline how you can build and deploy the application using the S3 and CloudFront resources created by the Import phase above:\n\n  1. Navigate to `./aws-mobile-react-sample/client` and build for production by running:\n\n      `$ awsmobile publish`\n\n  This will automatically run the `npm run-script build` command, upload your application to Amazon S3 and Amazon CloudFront, and open your default web browser to the Amazon S3 static web hosting page.\n\n### Automating Build \u0026 Deploy\n\nIf you are using a CI/CD process you may choose to automate this process. The following shows how to use [a webpack plugin](https://github.com/MikaAK/s3-plugin-webpack) with AWS Credentials to automate deployment to S3:\n\n1. Navigate to `./aws-mobile-react-sample/client/` directory and edit webpack.config.js file. Add the following to the top of the file:\n\n  ```js\n  const S3Plugin = require('webpack-s3-plugin');\n  ```\n\n2. Add the following as an entry to the `plugins:[]` section towards the bottom:\n\n```js\nnew S3Plugin({\n  // Only upload css and js\n  include: /.*\\.(css|js)/,\n  // s3Options are required\n  s3Options: {\n    accessKeyId: AWS_ACCESS_KEY_ID,\n    secretAccessKey: AWS_SECRET_ACCESS_KEY,\n  },\n  s3UploadOptions: {\n    Bucket: 'MyBucket'\n  }\n})\n```\n\n**NOTE:** Replace the `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` and `MyBucket` with appropriate values such as your account keys for automation and the S3 bucket created during the import process.\n\n3. Save the file and run the following command to install the plugin dependency:\n\n```\nnpm install --save webpack-s3-plugin\n```\n\n4. Run the following command to build and deploy to S3:\n\n```\n$ awsmobile publish\n```\n\n\n# Advanced Usage\n\n## Using the Registration and Login components in your application \u003ca name=\"reglogin\"\u003e\u003c/a\u003e\n\nThe Registration and Login components leverage AWS Amplify to make calls to Amazon Cognito User Pools and Amazon Cognito Federated Identities . As an example of using it in your own application first create a React application with [Create React App](https://github.com/facebookincubator/create-react-app):\n\n```\nnpm install -g create-react-app\ncreate-react-app my-app\ncd my-app/\nnpm start\n```\n\nIf the application runs successfully, copy the `Auth`, `configuration` and `css` folders from `./aws-mobile-react-sample/client/src` to `./my-app/src` that was created by Create React App. Next copy `index.js` and `Main.jsx` from `./aws-mobile-react-sample/client/src` to `./my-app/src`. Edit the copied `Main.jsx` so that the `return()` function matches the below code:\n\n\n```jsx\nreturn (\n  \u003cdiv\u003e\n    {\n      !logOut \u0026\u0026 (\n        \u003cBrowserRouter\u003e\n          \u003cdiv\u003e\n            \u003cNavbar className='nav-bar' brand='WebApp' right\u003e\n              \u003cNavItem onClick={this.signOut}\u003eLogout\u003c/NavItem\u003e\n            \u003c/Navbar\u003e\n            \u003cApp/\u003e\n          \u003c/div\u003e\n        \u003c/BrowserRouter\u003e\n      )\n    }\n    {\n      logOut \u0026\u0026 (\u003cAppRoute authStatus={false}/\u003e)\n    }\n  \u003c/div\u003e\n);\n```\n\nNext, from your `./my-app` directory, run:\n\n```\n$npm install --save aws-amplify react-router-dom react-materialize react-transition-group@^1.1.3 semantic-ui-react css-loader\n```\n\nEdit `Main.jsx and comment out the following:`\n\n```js\n//import Home from './Home';\n//import Menu from './API/Menu';\n//import Orders from './API/Order';\n```\n\nAlso add `import App from './App';` to the top of `Main.jsx` and save the file.\n\nEdit `index.js` and replace the `require('file-loader....')` statement towards the top with:\n\n```js\nrequire('file-loader?name=[name].[ext]./index.html');\n```\n\nFinally to add the styling to the page edit `./my-app/public/index.html` and add the following to the head:\n\n```html\n\u003clink rel=\"stylesheet\" href=\"http://fonts.googleapis.com/icon?family=Material+Icons\"\u003e\n\u003clink rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/css/materialize.min.css\"\u003e\n\u003clink rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.2/semantic.min.css\"\u003e\n```\n\nAnd add the following to the body:\n\n```html\n\u003cscript src=\"https://code.jquery.com/jquery-2.1.1.min.js\"\u003e\u003c/script\u003e\n\u003cscript src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/js/materialize.min.js\"\u003e\u003c/script\u003e\n```\n\nYou can now run your application created with Create React App with a new login page added:\n\n```\nnpm start\n```\n\nThe application should start and allow you to register users and login taking you to the normal page created with Create React App.\n\n\n### Using AWS Amplify to communicate with API Gateway \u003ca name=\"restclient\"\u003e\u003c/a\u003e\n\nThe sample application uses API Gateway and Lambda to run an Express application which reads and writes to a DynamoDB table. Included in the sample is a helper function for making signed requests to API Gateway. We'll show how to use this helper for making unauthenticated requests to API Gateway below and you can use the Login example above to get authenticated credentials which this sample would use.\n\nAs with the previous section first create a React application with [Create React App](https://github.com/facebookincubator/create-react-app):\n\n```\nnpm install -g create-react-app\ncreate-react-app my-app\ncd my-app/\nnpm start\n```\n\nIf you didn't do the previous section, copy `configuration` from `./aws-mobile-react-sample/client/src` to `./my-app/src`.\n\nEdit `./my-app/src/App.js` with the following imports at the top:\n\n```js\nimport Link from 'link-react';\nimport { Table } from 'semantic-ui-react';\nimport awsmobile from './configuration/aws-exports';\nimport Amplify,{API} from 'aws-amplify';\n\nAmplify.configure(awsmobile);\n```\n** NOTE: To make calls to API Gateway through AWS Amplify, you need your IdentityPoolID in aws-exports.js. For further documentation, refer to [AWS Amplify](https://github.com/aws/aws-amplify/blob/master/media/api_guide.md)\nModify the `App` component like so **(NOTE: you are NOT modifying the render function YET)**:\n\n```jsx\nclass App extends Component {\n  state = {\n    data: []\n  }\n\n  fetch = async () =\u003e {\n    this.setState(() =\u003e {\n      return {\n        loading: true\n      }\n    });\n\n    API.get('ReactSample','/items/restaurants')\n        .then(resp =\u003e {\n          this.setState({\n            data: resp\n          });\n          console.log(\"response is : \", resp);\n        })\n        .catch (err =\u003e console.log(err))\n  }\n}\n\n//render logic below\nrender()....more code\n```\n\nNow, change the `render()` function like so:\n\n```jsx\nrender() {\n    return (\n      \u003cdiv className=\"App\"\u003e\n        \u003cLink onClick={this.fetch}\u003e\n          List restaurants\n        \u003c/Link\u003e\n        \u003cdiv\u003e\n          \u003cdiv\u003e\n        {(\n      \u003cTable\u003e\n          \u003cTable.Header\u003e\n          \u003cTable.Row\u003e\n            \u003cTable.HeaderCell\u003eName\u003c/Table.HeaderCell\u003e\n            \u003cTable.HeaderCell\u003eAddress\u003c/Table.HeaderCell\u003e\n            \u003cTable.HeaderCell\u003eContact\u003c/Table.HeaderCell\u003e\n            \u003cTable.HeaderCell\u003eRating\u003c/Table.HeaderCell\u003e\n          \u003c/Table.Row\u003e\n        \u003c/Table.Header\u003e\n        \u003cTable.Body\u003e\n          {this.state.data.map((data, idx) =\u003e\n            \u003cTable.Row key={idx}\u003e\n              \u003cTable.Cell\u003e{data.name}\u003c/Table.Cell\u003e\n              \u003cTable.Cell\u003e{data.address}\u003c/Table.Cell\u003e\n              \u003cTable.Cell\u003e{data.phone}\u003c/Table.Cell\u003e\n              \u003cTable.Cell\u003e{data.rating}\u003c/Table.Cell\u003e\n            \u003c/Table.Row\u003e\n          )}\n        \u003c/Table.Body\u003e\n      \u003c/Table\u003e\n    )}\n    \u003c/div\u003e\n        \u003c/div\u003e\n      \u003c/div\u003e\n    );\n  }\n}\n\nexport default App;\n```\n\nSave the file. Finally install the dependencies:\n\n```\nnpm install --save link-react semantic-ui-react\n```\n\nDepending on if you want to do Authenticated or UnAuthenticated requests to API Gateway, you will need the following modification:\n\n**Authenticated Requests**\n\n  Note: If you are doing an authenticated, signed request you'll also need to perform a couple more steps. First install `querystring-browser`\n\n```\nnpm install --save querystring-browser@^1.0.4\n```\n\nNext you will need to configure this as a webpack alias:\n\n```js\nresolve: {\n  extensions: ['.js', '.jsx'],\n  alias: {\n    querystring: 'querystring-browser'\n  }\n}\n```\n\nFor our Create React App sample you will need to modify either `webpack.config.dev.js` or `webpack.config.prod.js` in the `./my-app/node_modules/react-scripts/config` directory. Look for the `resolve:` field inside `module.exports` and add the `querystring: 'querystring-browser'` entry under the `alias` field.\n\n**UnAuthenticated Requests**\n\nNavigate to the API Gateway console, click on the ReactSample-MobileHub API and select **Resources** on the left hand side of the page. Under the **/items** node select **ANY** and then click on **Method Request** in the right hand side of the console. Click the dropdown labeled **Authorization** and select **NONE**. Press the **Update** tick box to save your changes.\n\nIn the same part of the console, select the **/items/{proxy +}** node followed and click **ANY** and then **Method Request**. Repeat the process of setting **Authorization** to **NONE** and saving your change.\n\nNext deploy your changes by select **Actions** at the top of the page, then **Deploy API** and select **Development** as the _Deployment stage_. Click **Deploy**.\n\nAdditionally you will need to make an alteration to the `./my-app/src/App.js` by changing the `this.setState()` function from:\n\n```js\nthis.setState({\n  data: resp\n});\n```\n\nTo:\n\n```js\nthis.setState({\n  data: resp.data\n});\n```\n\n#### Run your application\n\nFinally, after making your modifications for either the Authenticated or UnAuthenticated request run the following command to launch your Create React App again:\n\n```\nnpm start\n```\n\nClick **List restaurants** at the top of the page to use the AWS Amplify API component.\n\n\n## Modifying Express routes in Lambda \u003ca name=\"lambdamodify\"\u003e\u003c/a\u003e\n\nThe sample application invokes a Lambda function running Express which will make CRUD operations to DynamoDB depending on the route which is passed from the client application. You may wish to modify this backend behavior for your own needs. The steps outline how you could add functionality to _\"create a Restaurant\"_ by showing what modifications would be needed in the Lambda function and the corresponding client modifications to make the request.\n\n1. Add the following function into app.js before the section that says  `* Restaurant methods *`\n\n```js\nvar putCallback = function(err, data) {\n    if (err) {\n        console.log(err)\n    }\n}\n\nfunction createMenu(restaurant_id) {\n    var item1 = {}\n    item1.id = uuid.v1()\n    item1.restaurant_id = restaurant_id\n    item1.name = \"Golden Ratio Bacon Skewers\"\n    item1.description = \"Fibonacci on a stick! Who doesn’t like bacon on a stick that keeps going?\"\n    item1.photos = []\n    dynamoDb.put({\n        Item: item1,\n        TableName: MENU_TABLE_NAME\n    }, putCallback)\n    var item2 = {}\n    item2.id = uuid.v1()\n    item2.restaurant_id = restaurant_id\n    item2.name = \"Abelian Cucumber Salad\"\n    item2.description = \"A cool and refreshing salad for any hot summer day.\"\n    item2.photos = []\n    dynamoDb.put({\n        Item: item2,\n        TableName: MENU_TABLE_NAME\n    }, putCallback)\n    var item3 = {}\n    item3.id = uuid.v1()\n    item3.restaurant_id = restaurant_id\n    item3.name = \"Chili-Cucumber orientable Corn\"\n    item3.description = \"Feel like you’re connected to nature with corn that wraps around your belly.\"\n    item3.photos = []\n    dynamoDb.put({\n        Item: item3,\n        TableName: MENU_TABLE_NAME\n    }, putCallback)\n    var item4 = {}\n    item4.id = uuid.v1()\n    item4.restaurant_id = restaurant_id\n    item4.name = \"Finite Short-Rib Fields\"\n    item4.description = \"No utensils! BBQ is finger food!\"\n    item4.photos = []\n    dynamoDb.put({\n        Item: item4,\n        TableName: MENU_TABLE_NAME\n    }, putCallback)\n    var item5 = {}\n    item5.id = uuid.v1()\n    item5.restaurant_id = restaurant_id\n    item5.name = \"Easy Fractal Salad\"\n    item5.description = \"This symmetric pasta salad features feta, artichoke hearts, and kale.\"\n    item5.photos = []\n    dynamoDb.put({\n        Item: item5,\n        TableName: MENU_TABLE_NAME\n    }, putCallback)\n}\n```\n\n2. Now in the routes section (under the ` * Restaurant methods *` comment) add in a new POST route:\n\n```js\napp.post('/items/restaurants/new', function(req, res){\n    var restaurant = {}\n    restaurant.id = uuid.v1()\n    restaurant.name = req.body.name\n    restaurant.description = req.body.description\n    restaurant.address = req.body.address\n    restaurant.phone = req.body.phone\n    restaurant.rating =req.body.rating\n    dynamoDb.put({\n        Item: restaurant,\n        TableName: RESTAURANTS_TABLE_NAME\n    }, function(err,data){\n        if (err){\n            res.json({ message: err })\n        }else {\n            res.json({\n                message: \"New Restaurant added!\"\n            })\n        }\n    })\n    createMenu(restaurant.id)\n})\n```\n\n3. Save the file and in the Mobile Hub console for your project click the **Cloud Logic** card. Expand the **View resource details** section and note the name of the **Lambda function** in the list for the next step.\n\n4. In a terminal navigate to `./aws-mobile-react-sample/backend/lambda` and run:\n\n```\nzip -r lambda-archive.zip .\naws lambda update-function-code --function-name FUNCTION_NAME --zip-file fileb://lambda-archive.zip\n```\n\n**REPLACE the FUNCTION_NAME with your Lambda function name from the previous step.**\n\nAlternatively you could click the Lambda function resource in the Mobile Hub console which opens the Lambda console and press the **Upload** button on that page to upload the **lambda-archive.zip** file.\n\n5. In the `./aws-mobile-react-sample/client/src` directory edit `Home.jsx` with the following code **BEFORE** the **render()** method:\n\n```js\nnewRestaurant = () =\u003e {\n  let body = JSON.stringify({\n    'name': 'New Name',\n    'description': 'New description',\n    'address': 'New address',\n    'phone': 'New phone',\n    'rating': 'New rating'\n  });\n\n  let requestParams = {\n    method: 'POST',\n    url: apiRestarauntUri + '/new',\n    headers: {'content-type': 'application/json'},\n    body\n  }\n\n  this.restResponse = restRequest(requestParams)\n    .then(data =\u003e {\n      sessionStorage.setItem('latestOrder', data.id);\n      console.log(data);\n      alert('Added successfully');\n    })\n    .catch (function(error){\n      console.log(error);\n    });\n}\n```\n\nNote that `url: apiRestarauntUri + '/new'` matches the path you made for the Express route in the Lambda function you uploaded.\n\n6. In the `return` statement of the `render` method add in a new button next to the others:\n\n```jsx\n\u003cButton primary onClick={this.newRestaurant}\u003e\n  New Restaurant\n\u003c/Button\u003e\n```\n\nSave your changes and run your application again with `npm start`. You should have a new button after logging in. Press **New Restaurant** and then **List Restaurants** to see the new entry in the system.\n\n\n### Security Information\n\n#### Storage locations\n\nThe website hosting location for this sample uses an S3 bucket as the CloudFront origin. The S3 bucket is by default configured as publicly accessable for testing purposes. To learn more about restricting this access further, see [Amazon S3 Security Considerations](http://docs.aws.amazon.com/mobile-hub/latest/developerguide/s3-security.html) and [Amazon CloudFront Security Considerations](http://docs.aws.amazon.com/mobile-hub/latest/developerguide/cloudfront-security.html).\n\n#### sessionStorage\n\nThis sample app uses [sessionStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) to persist user tokens (`accessKeyId`, `secretAccessKey` and `sessionToken`). They are deleted when the browser is closed and not available when new tabs are opened. You can take further actions to secure these tokens by encrypting them.\n\n#### API Handler Table Permissions\n\nThe Lambda function in this sample will read and write to DynamoDB and it's role will be granted the appropriate permissions to perform such actions. If you wish to modify the sample to perform a more restricted set of actions see [Authentication and Access Control for Amazon DynamoDB](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/authentication-and-access-control.html).\n","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Famazon-archives%2Faws-mobile-react-sample","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Famazon-archives%2Faws-mobile-react-sample","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Famazon-archives%2Faws-mobile-react-sample/lists"}