<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yann on Medium]]></title>
        <description><![CDATA[Stories by Yann on Medium]]></description>
        <link>https://medium.com/@yanndnz?source=rss-fab552672798------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*oKgZG4cPBBtergeojfRXIg.jpeg</url>
            <title>Stories by Yann on Medium</title>
            <link>https://medium.com/@yanndnz?source=rss-fab552672798------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:09:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yanndnz/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Add artificial intelligence to your React app with AWS Rekognition -picture analysis (Part 10)]]></title>
            <link>https://medium.com/develop-and-deploy-a-complex-serverless-web-app/add-artificial-intelligence-to-your-react-app-with-aws-rekognition-picture-analysis-part-10-13df0ea14a24?source=rss-fab552672798------2</link>
            <guid isPermaLink="false">https://medium.com/p/13df0ea14a24</guid>
            <category><![CDATA[image-annotation]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[rekognition]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Yann]]></dc:creator>
            <pubDate>Fri, 26 Jun 2020 15:56:39 GMT</pubDate>
            <atom:updated>2020-06-26T15:56:39.647Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kD-O3-wSxOzPMvOYupwjzw.png" /><figcaption>Photo by <a href="https://unsplash.com/@pericakalimerica?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Pero Kalimero</a> on <a href="https://unsplash.com/s/photos/cloud?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Use AWS Rekognition to extract text from images (Part 10)</h3><p>This story is part of a series about how to build and deploy a complex cloud based application using Amplify and artificial intelligence (AWS Rekognition), with a final result <a href="https://do93zxpqjd34l.cloudfront.net/">looking like this</a> (work in progress). In the <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/use-s3-trigger-to-create-a-dynamodb-entry-when-uploading-images-to-s3-part-9-4d7489a4584b">previous story</a>, we created a a Lambda S3 trigger in order to add a new DynamoDb entry when a new picture is uploaded.</p><p>Great, we already built a pretty complex React application with various features. But you are probably impatient to get to the point of this whole series: use artificial intelligence to extract text from pictures with AWS. Good news, this is the topic of this tutorial!</p><h3>Prerequisite</h3><p>If you are not following the <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/develop-ai-web-apps-aws-reactjs-define-the-project-part-1-5aa14db8fa97">complete tutorial</a>, you should be ok reading only this one. You will just need a ReactJs project with Aws Amplify, a DynamoDb table and a S3 already setup with a upload trigger to a Lambda function.</p><p>I also assume that you are familiar with npm, react and javascript in general.</p><h3>A word about AWS Rekognition</h3><p>AWS Rekognition has been introduced in 2016 to offer pre-trained models that can be used through a simple API request. Its power is far from being limited to text detection, but also includes labeling, content moderation, face detection, facial verification, celebrity recognition and even path detection from video files.</p><p>You can access AI and ML services directly though Amplify using the <a href="https://docs.amplify.aws/lib/predictions/intro/q/platform/js">predictions</a> library. But I am not going to do that. Why that? Because Rekognition <a href="https://aws.amazon.com/rekognition/pricing/">price is not that low</a> ($1/1000 analysis), so I don’t want the end user to be able to trigger a analysis by himself, don’t forget that your React code is executed client side. For a public application, I would rather have the analysis done server side in a Lambda so I can add securities if I want it in the future (check for a payment for instance).</p><p>That being said, lets start coding!</p><h3>The S3 trigger</h3><p>From the previous tutorial, you should already have a Lambda looking like this:</p><pre>var AWS = require(&#39;aws-sdk&#39;);<br>var s3 = new AWS.S3();<br>var ddb = new AWS.DynamoDB();</pre><pre>...</pre><pre>exports.handler = async function (event, context, callback) {<br>  ...</pre><pre>if (eventName === &quot;ObjectCreated:Put&quot;) {<br>    ...<br>      await putImageDB(key);<br>};</pre><pre>function removeImageS3(key, bucket) {<br>  ...<br>}</pre><pre>function putImageDB(key) {<br>  ...<br>}</pre><p>First import Rekognition:</p><pre>var rekognition = new AWS.Rekognition();</pre><p>And simply implement this function :</p><pre>function launchRecognition(key, bucket) {<br>  let params = {<br>    Image: {<br>      S3Object: {<br>        Bucket: bucket,<br>        Name: key<br>      }<br>    }<br>  };</pre><pre>return rekognition.detectText(params).promise()<br>}</pre><p>Super easy right? It is basically all you need to call Rekognition from Lambda!</p><p>Call your new function before adding the picture info to DynamoDb:</p><pre>exports.handler = async function (event, context, callback) {<br>  ...<br>    else {<br>      <strong>// Analyse the image<br>      let rekognitionResult = await launchRecognition(key, bucket)<br>      console.log(rekognitionResult)</strong><br>      await putImageDB(key);<br>    }<br>  }<br>};</pre><p>Now we want to add this result to our Db entry. I choose to save the raw data directly so I don’t have to rerun Rekognition if the user decides after the upload that he/she want to change the text extraction criteria.</p><pre>      let rekognitionResult = await launchRecognition(key, bucket)<br>      console.log(rekognitionResult)<br>      await putImageDB(key,<strong> analysisResult</strong>);<br>...</pre><pre>function putImageDB(key, <strong>analysisResult</strong>) {<br>  let owner = key.split(&#39;/&#39;)[2];<br>  let name = key.split(&#39;/&#39;).pop();<br>  <strong>let isAnalyse = analysisResult ? true : false;</strong><br>  let online = &#39;public&#39;;<br>  let date = new Date().toISOString();<br>  var params = {<br>    TableName: imageTable,<br>    Item: {<br>      key: { S: key },<br>      owner: { S: owner },<br>      name: { S: name },<br>      <strong>isAnalyse: { BOOL: isAnalyse },<br>      analysisResult: { S: JSON.stringify(analysisResult) },</strong><br>      online: { S: online },<br>      date: { S: date },<br>    }<br>  };</pre><pre>...</pre><p>Last thing to do is to add permission to our lambda to get S3 object and to use Rekognition. In the cloudformation-tempate.json in your Lambda folder:</p><pre>&quot;PolicyDocument&quot;: {<br> &quot;Version&quot;: &quot;2012-10-17&quot;,<br> &quot;Statement&quot;: [<br>   ...<br>  {<br>   &quot;Effect&quot;: &quot;Allow&quot;,<br>   &quot;Action&quot;: [<br>    &quot;dynamodb:PutItem&quot;,<br>    &quot;dynamodb:DeleteItem&quot;,<br>    &quot;dynamodb:Scan&quot;,<br>    &quot;dynamodb:Query&quot;,<br>    &quot;dynamodb:UpdateItem&quot;<br>   ],<br>   &quot;Resource&quot;: &quot;arn:aws:dynamodb:*:*:table/*&quot;<br>  },<br>  <strong>{<br>   &quot;Effect&quot;: &quot;Allow&quot;,<br>   &quot;Action&quot;: &quot;rekognition:DetectText&quot;,<br>   &quot;Resource&quot;: &quot;*&quot;<br>  },<br>  {<br>   &quot;Effect&quot;: &quot;Allow&quot;,<br>   &quot;Action&quot;: &quot;s3:GetObject&quot;,<br>   &quot;Resource&quot;: &quot;arn:aws:s3:::*/*&quot;<br>  }</strong><br> ]<br>}</pre><h3>Time to test!</h3><p>Run amplify push to push your updates to lambda and npm start to start your frontend.</p><p>Upload a picture with some text and go to cloud front.</p><p>You should be able to find the event and debug information you printed in your code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2kcHrmknFCpI9xfn1waHpQ.png" /><figcaption>Cloudfront output after picture update</figcaption></figure><p>Everything seems to happened as expected, now go to DynamoDb to ensure that the information you wanted is stored in your DB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*mjWlCJ5LjZBmI39wRmG7Dg.png" /></figure><p>And the analysis field should contain a json looking like something like that:</p><pre>{ TextDetections:<br>   [ { DetectedText: &#39;4047.&#39;,<br>       Type: &#39;WORD&#39;,<br>       Id: 8,<br>       ParentId: 3,<br>       Confidence: 91.50900268554688,<br>       Geometry: [Object] },<br>     { DetectedText: &#39;GRENOBLEALPESMETROPOLE&#39;,<br>       Type: &#39;WORD&#39;,<br>       Id: 12,<br>       ParentId: 4,<br>       Confidence: 98.33341979980469,<br>       Geometry: [Object] },</pre><pre>      ...<br>    ],<br>  TextModelVersion: &#39;3.0&#39; }</pre><p>Congratulation! You now have all the information a you need to create a filter based on the text contained in the picture. And you extracted that data using pre-trained artificial intelligence model with AWS Rekognition!</p><p>In the next tutorial, we will try to use all that raw data in order to make something usable for our end user. Follow to be updated when it is out!</p><p>If you like this series or this tutorial and would like to support my work, you can <a href="https://www.buymeacoffee.com/ZYwAO7g">buy me a coffee</a> 😘</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13df0ea14a24" width="1" height="1" alt=""><hr><p><a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/add-artificial-intelligence-to-your-react-app-with-aws-rekognition-picture-analysis-part-10-13df0ea14a24">Add artificial intelligence to your React app with AWS Rekognition -picture analysis (Part 10)</a> was originally published in <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app">Develop and deploy a complex serverless web app using AWS, ReactJs and AI (Rekognition)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use S3 Trigger to create a DynamoDb entry when uploading images to S3 (Part 9)]]></title>
            <link>https://medium.com/develop-and-deploy-a-complex-serverless-web-app/use-s3-trigger-to-create-a-dynamodb-entry-when-uploading-images-to-s3-part-9-4d7489a4584b?source=rss-fab552672798------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d7489a4584b</guid>
            <category><![CDATA[aws-dynamodb]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[image]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws-amplify]]></category>
            <dc:creator><![CDATA[Yann]]></dc:creator>
            <pubDate>Fri, 27 Mar 2020 16:10:55 GMT</pubDate>
            <atom:updated>2020-06-26T15:58:29.942Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kD-O3-wSxOzPMvOYupwjzw.png" /><figcaption>Photo by <a href="https://unsplash.com/@pericakalimerica?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Pero Kalimero</a> on <a href="https://unsplash.com/s/photos/cloud?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This story is part of a series about how to build and deploy a complex cloud based application using Amplify and artificial intelligence (AWS Rekognition), with a final result <a href="https://do93zxpqjd34l.cloudfront.net/">looking like this</a> (work in progress). In the <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/upload-and-resize-images-to-the-cloud-with-aws-s3-amplify-and-react-part-8-705a7dc49680">previous story</a>, we created an upload button to resize and push our pictures to S3. For one picture, we uploaded a good definition (1000px max) and a thumbnail (100px max).</p><p>In order to create our gallery, we need DynamoDb to store the key and other information about the picture. To do so we are going to use a S3 trigger to launch a Lambda in order to make the update in our database.</p><h3>Prerequisite</h3><p>If you are not following the <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/develop-ai-web-apps-aws-reactjs-define-the-project-part-1-5aa14db8fa97">complete tutorial</a>, you should be ok by reading only this one. You will just need a ReactJs project with Aws Amplify, a DynamoDb table and a S3 already setup.</p><p>I also assume that you are familiar with npm, react and javascript in general.</p><h3>Setup our S3 trigger using Amplify</h3><p>First we need to create the trigger, go on your terminal and update the Storage part of your project:</p><pre>amplify update storage</pre><p>Leave everything as is already set until the question: <em>Do you want to add a Lambda Trigger for your S3 Bucket.</em></p><p>Answer yes and <em>Create a new function</em>. And press enter until the end.</p><p>A new folder called S3Trigger***** should have been created in your <em>amplify/backend/function</em>. Go to src/ and open index.js. This file contains the handler that will be trigger when something happens in your S3.</p><p>Make the handler async so you can use await and add callback in the arguments:</p><pre>// eslint-disable-next-line<br>exports.handler = async<strong> </strong>function(event, context, <strong>callback</strong>) {<br>  console.log(&#39;Received S3 event:&#39;, JSON.stringify(event, null, 2));<br>  // Get the object from the event and show its content type<br>  const bucket = event.Records[0].s3.bucket.name; //eslint-disable-line<br>  const key = event.Records[0].s3.object.key; //eslint-disable-line<br>  console.log(`Bucket: ${bucket}`, `Key: ${key}`);<br>  context.done(null, &#39;Successfully processed S3 event&#39;); // SUCCESS with message<br>};</pre><p>push your backend</p><pre>amplify push</pre><p>Test that your function is working by uploading a file. Go to your aws console, lambda, find your S3 trigger, monitoring and open in cloudwatch. Here you should see a new entry with your picture information (one for the main picture and one for the thumbnail):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1rpuiQx9ct-hGpMfpVIRaQ.png" /><figcaption>S3 trigger logs in cloudwatch</figcaption></figure><p>Good that seems to be working!</p><h3>Toggle DynamoDb table based on environment</h3><p>If you use two different environment for your master and for you development (and you should), you will need to toggle from one table to the other.</p><p>The environment name is store in process.env.ENV so you can add this code before your handler:</p><pre>let imageTable = &quot;Image-***-dev&quot;;<br>if (process.env.ENV === &#39;master&#39;) {<br>  console.log(&quot;Prod env&quot;)<br>  imageTable = &quot;Image-***-master&quot;;<br>}</pre><h3>Declare some useful variables</h3><p>In our handler, we can start by declaring some variables we are going to need:</p><ol><li>eventName: the name of the event that triggered the lambda, we are only interested in put event but you can also detect delete event for instance.</li><li>bucket: the name of the bucket the put happened</li><li>key: the key of the uploaded object. This is the full path in the bucket not only the filename.</li><li>imgSize: the size of the uploaded object</li><li>maxSize: the maximum size we are willing to permit in our bucket</li><li>filename: the filename without the extension (to know if this image is a thumbnail or not)</li></ol><p>Let’s implement that:</p><pre>exports.handler = async function(event, context, callback) {<br>  console.log(&#39;Received S3 event:&#39;, JSON.stringify(event, null, 2));<br>  const eventName = event.Records[0].eventName;<br>  const bucket = event.Records[0].s3.bucket.name; //eslint-disable-line<br>  let key = event.Records[0].s3.object.key.replace(&#39;%3A&#39;, &#39;:&#39;); //eslint-disable-line<br>  const imgSize = event.Records[0].s3.object.size;<br>  const maxSize = 5000000; // More that 5Mb images would be rejected<br>  const filename = key.split(&#39;.&#39;).slice(0, -1).join(&#39;.&#39;);<br>  <br>};</pre><h3>Check that we are in a put event</h3><p>Next thing to do is to check if the lambda was triggered by an event we are interested in. We only want to detect put event so:</p><pre>if (eventName === &quot;ObjectCreated:Put&quot;) {<br> console.log(&quot;This is a put event&quot;)<br>}</pre><h3>Perform some checks</h3><p>We have two reason not adding an DynamoDb entry. First it is a thumbnail, we only want to create one entry by pictures but the lambda will be triggered twice, so if the filename end with “-thumbnail” we are going to stop the lambda here. Second if the image size is too big we are not going to add an entry and we will remove the object from the S3.</p><pre>// We don&#39;t want to add DB entry for thumbnails <br>if (filename.endsWith(&#39;-thumbnail&#39;)) {<br> console.log(&#39;Image is a thumbnail&#39;)<br> callback(null, &quot;Image is a thumbnail&quot;)<br> return<br>}<br>// Remove image if too big and return <br>else if (imgSize &gt; maxSize) {<br> removeImageS3(key, bucket); // To be implemented<br> callback(Error(&quot;Fail: image too big&quot;))<br> return<br>}</pre><p>After the handler implement the removeImageS3 function, for this function you will need to import AWS sdk and s3 object to interact with s3:</p><pre>var AWS = require(&#39;aws-sdk&#39;);<br>var s3 = new AWS.S3();</pre><pre>...</pre><pre>function removeImageS3(key, bucket) {<br>  let params = { Bucket: bucket, Key: key };<br>  s3.deleteObject(params, function (err, data) {<br>    if (err) {<br>      console.log(err, err.stack);<br>      return false<br>    }<br>    else {<br>      console.log(&quot;Image deleted from s3&quot;)<br>      return true<br>    }<br>  });<br>}</pre><h3>Put the image information to the DB</h3><p>Now that we are sure that the image is the main one and is not too big, we can put our new entry in the db.</p><pre>else if (imgSize &gt; maxSize) {<br> removeImageS3(key, bucket); // To be implemented<br> callback(Error(&quot;Fail: image too big&quot;))<br> return<br>}<br>else {<br> await putImageDB(key);<br>}</pre><p>Implement the putImageDB(), I am using the model we define in the previous tutorial but you can easily adapt it to your own model. Don’t forget to import AWS.DynamoDb to be able to interact with your table:</p><pre>var ddb = new AWS.DynamoDB();</pre><pre>...</pre><pre>function putImageDB(key) {<br>  let owner = key.split(&#39;/&#39;)[2]; // We put it here in the previous tutorial<br>  let name = key.split(&#39;/&#39;).pop();<br>  let online = &#39;public&#39;;<br>  let date = new Date().toISOString();<br>  var params = {<br>    TableName: imageTable,<br>    Item: {<br>      key: { S: key },<br>      owner: { S: owner },<br>      name: { S: name },<br>      online: { S: online },<br>      date: { S: date },<br>    }<br>  };</pre><pre>  // Call DynamoDB to add the item to the table<br>  return ddb.putItem(params, function (err, data) {<br>    if (err) {<br>      console.log(&quot;Error&quot;, err);<br>    } else {<br>      console.log(&quot;Success&quot;, data);<br>    }<br>  }).promise();<br>}</pre><p>That should be enough for the handler.</p><h3>Add permission to lambda</h3><p>If you run your code like that, you will run into an authorization error. This is pretty normal as you never specify your lambda role to be allowed to manipulate DynamoDb table. To to so find the cloudformation template for your function in <em>amplify/backend/function/S3trigger</em> and update as follow:</p><pre>&quot;PolicyDocument&quot;: {<br> &quot;Version&quot;: &quot;2012-10-17&quot;,<br> &quot;Statement&quot;: [<br>  {<br>   &quot;Effect&quot;: &quot;Allow&quot;,<br>   &quot;Action&quot;: [<br>    &quot;logs:CreateLogGroup&quot;,<br>    &quot;logs:CreateLogStream&quot;,<br>    &quot;logs:PutLogEvents&quot;<br>   ],<br>   &quot;Resource&quot;: {<br>    &quot;Fn::Sub&quot;: [<br>     &quot;arn:aws:logs:${region}:${account}:log-group:/aws/lambda/${lambda}:log-stream:*&quot;,<br>     {<br>      &quot;region&quot;: {<br>       &quot;Ref&quot;: &quot;AWS::Region&quot;<br>      },<br>      &quot;account&quot;: {<br>       &quot;Ref&quot;: &quot;AWS::AccountId&quot;<br>      },<br>      &quot;lambda&quot;: {<br>       &quot;Ref&quot;: &quot;LambdaFunction&quot;<br>      }<br>     }<br>    ]<br>   }<br>  },<br>  <strong>{<br>   &quot;Effect&quot;: &quot;Allow&quot;,<br>   &quot;Action&quot;: [<br>    &quot;dynamodb:PutItem&quot;,<br>    &quot;dynamodb:DeleteItem&quot;,<br>    &quot;dynamodb:Scan&quot;,<br>    &quot;dynamodb:Query&quot;,<br>    &quot;dynamodb:UpdateItem&quot;<br>   ],<br>   &quot;Resource&quot;: &quot;arn:aws:dynamodb:*:*:table/*&quot;<br>  }</strong><br> ]<br>}</pre><p>I am not very precise here, allowing to manipulate all tables, but that will be fine for the example.</p><p>Save and push the result:</p><pre>amplify push</pre><h3>Test it</h3><p>We are done here!</p><p>Try to upload a image, you should be able to see a log in cloudwatch and a new entry in DynamoDb with the correct image information:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A7EZ-cleSshISAAFGhf77Q.png" /><figcaption>At upload you can see a new entry in DynamoDb</figcaption></figure><p>That is all for this tutorial. In the next one, we are going to <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/add-artificial-intelligence-to-your-react-app-with-aws-rekognition-picture-analysis-part-10-13df0ea14a24">update this trigger to get Rekognition to analyse our picture and save the result to DynamoDb</a> . Follow to be updated when it is out!</p><p>If you like this series or this tutorial and would like to support my work, you can <a href="https://www.buymeacoffee.com/ZYwAO7g">buy me a coffee</a> 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d7489a4584b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/use-s3-trigger-to-create-a-dynamodb-entry-when-uploading-images-to-s3-part-9-4d7489a4584b">Use S3 Trigger to create a DynamoDb entry when uploading images to S3 (Part 9)</a> was originally published in <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app">Develop and deploy a complex serverless web app using AWS, ReactJs and AI (Rekognition)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upload and resize images to the cloud with Aws S3, Amplify and React (Part 8)]]></title>
            <link>https://medium.com/develop-and-deploy-a-complex-serverless-web-app/upload-and-resize-images-to-the-cloud-with-aws-s3-amplify-and-react-part-8-705a7dc49680?source=rss-fab552672798------2</link>
            <guid isPermaLink="false">https://medium.com/p/705a7dc49680</guid>
            <category><![CDATA[multiple-image-upload]]></category>
            <category><![CDATA[amplify]]></category>
            <category><![CDATA[resize-images]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Yann]]></dc:creator>
            <pubDate>Tue, 24 Mar 2020 14:33:33 GMT</pubDate>
            <atom:updated>2020-03-27T16:11:30.479Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kD-O3-wSxOzPMvOYupwjzw.png" /><figcaption>Photo by <a href="https://unsplash.com/@pericakalimerica?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Pero Kalimero</a> on <a href="https://unsplash.com/s/photos/cloud?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This story is part of a series about how to build and deploy a complex cloud based application using Amplify and artificial intelligence (aws Rekognition), with a final result <a href="https://do93zxpqjd34l.cloudfront.net/">looking like this</a> (work in progress). In the<a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/define-your-model-requirements-and-setup-your-graphql-api-to-dynamodb-with-aws-amplify-part-7-2e627defc318"> previous story</a>, we created our model and graphql api using aws amplify.</p><p>Now we want to let our user add some images on his album. The images will be stored to S3 after being resized and a thumbnail will be created.</p><h3>Prerequisite</h3><p>If you are not following the <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/develop-ai-web-apps-aws-reactjs-define-the-project-part-1-5aa14db8fa97">complete tutorial</a>, you should be ok by reading only this one. You will just need a ReactJs project with Aws Amplify already setup.</p><p>I also assume that you are familiar with npm, react and javascript in general.</p><h3>Add storage to our project</h3><p>First thing first, we need to update our project to add S3. Hopefully we are using Amplify so this part will be pretty straightforward. Run:</p><pre>amplify add storage</pre><p>And answer ass follow:</p><pre>? Please select from one of the below mentioned services: <strong>Content (Images, audio, video, etc.)</strong><br>? Please provide a friendly name for your resource that will be used to label this category in the project: t****<br>? Please provide bucket name: t*******<br>? Who should have access: <strong>Auth and guest users</strong><br>? What kind of access do you want for Authenticated users? <strong>create/update, read, delete</strong><br>? What kind of access do you want for Guest users? <strong>read</strong><br>? Do you want to add a Lambda Trigger for your S3 Bucket? <strong>No</strong></pre><p>As we will see later this setup will not do exactly what we want, but that is good for now. Push your new resource to AWS:</p><pre>amplify push</pre><h3>Create the button</h3><p>Create a components folder to add our AddButton.js component like this: <strong>./src/Components/AddButton/AddButton.js</strong> and initiate it with an empty component:</p><pre>import React, { Component } from &#39;react&#39;;<br>import { Box } from &#39;<a href="http://twitter.com/material">@material</a>-ui/core&#39;;</pre><pre>class AddButton extends Component {<br>    render() {<br>        return (<br>            &lt;Box&gt;<br>                Button<br>            &lt;/Box&gt;<br>        );<br>    }<br>}<br>export default AddButton</pre><p>Then go back in the Projects component (if you follow the otheres tutorial) to display this new component:</p><pre>import React, { Component } from &#39;react&#39;;<br>import { Container, Typography } from &#39;<a href="http://twitter.com/material">@material</a>-ui/core&#39;;<br>import { withAuthenticator } from &#39;aws-amplify-react&#39;;<br>import AuthTheme from &#39;../../Config/AuthTheme&#39;;<br>import { signUpConfig } from &#39;../../Config/AuthConfig&#39;;<br>import AddButton from &#39;../../Components/AddButton/AddButton&#39;;</pre><pre>class Projects extends Component {<br>    render() {<br>        return (<br>            <strong>&lt;Container maxWidth=&#39;md&#39; style={{backgroundColor: &quot;#fefefe&quot;, padding: 20}}&gt;<br>                &lt;Typography variant=&#39;h3&#39;&gt;Album&lt;/Typography&gt;<br>                &lt;AddButton /&gt;<br>            &lt;/Container&gt;</strong><br>        );<br>    }<br>}<br>export default withAuthenticator(Projects, false, [], null, AuthTheme, signUpConfig);</pre><p>Back in the AddButton component, we can add an input to let the user select some images:</p><pre>...</pre><pre>return (<br>    &lt;Box&gt;<br>        <strong>&lt;input<br>            accept=&quot;image/*&quot;<br>            id=&quot;button-add-picture&quot;<br>            multiple<br>            type=&quot;file&quot;<br>            onChange={this.handleAdd}<br>        /&gt;</strong><br>    &lt;/Box&gt;<br>);</pre><pre>...</pre><p>You can run <em>npm start </em>in order to see what your new component looks like. You should have something like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bo99-dK6owIbXO1KRvs6Rw.png" /><figcaption>The AddButton component let you select several images</figcaption></figure><p>We could let the button like that, but let’s be honest the default styling is not super nice. We are using <a href="https://material-ui.com/">Material-Ui </a>since the beginning of the tutorial so we are going to use their button instead by pushing the input html in their component:</p><pre>import { Box, <strong>Button</strong> } from &#39;@material-ui/core&#39;;<br><strong>import AddAPhotoIcon from &#39;@material-ui/icons/AddAPhoto&#39;;</strong></pre><pre>...</pre><pre>&lt;Box&gt;<br> &lt;input<br>     accept=&quot;image/*&quot;<br>     id=&quot;button-add-picture&quot;<br>     multiple<br>     type=&quot;file&quot;<br>     onChange={this.handleAdd}<br>     <strong>style={{ display: &#39;none&#39; }}</strong><br> /&gt;<br> <strong>&lt;label htmlFor=&quot;button-add-picture&quot;&gt;<br>     &lt;Button variant=&quot;contained&quot;<br>             size=&quot;large&quot;<br>             color=&quot;secondary&quot;<br>             component=&quot;span&quot;<br>     &gt;<br>        &lt;AddAPhotoIcon /&gt;<br>     &lt;/Button&gt;<br> &lt;/label&gt;</strong><br>&lt;/Box&gt;</pre><pre>...</pre><p>Save your change, you should see something like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0mq6BysTKC9NliaCUetgWg.png" /><figcaption>Input with material ui design</figcaption></figure><p>Looks better right?</p><h3>Implement S3 upload</h3><p>Aws Amplify provide a very simple interface to push data to S3. If you need more details about that you can<a href="https://aws-amplify.github.io/docs/js/storage"> have a look on the doc here</a>.</p><p>The implementation is pretty straightforward, we define a filename, a file and the protection level. The protected level will let users see the images but only the owner can update them:</p><pre>import { Storage } from &#39;aws-amplify&#39;;</pre><pre>...</pre><pre>async pushImgToS3(uri, filename) {<br> if (uri === null) return<br> await Storage.put(filename, uri, {<br>     level: &#39;protected&#39;,<br>     contentType: &#39;image/*&#39;<br> })<br>     .then(result =&gt; console.log(result.key))<br>     .catch(err =&gt; console.log(err));<br>}</pre><pre>...</pre><p>Now we can implement the handler that will be triggered when the user select some images. We are going to use the uuid library to help us provide a unique image id, so run:</p><pre>npm install uuid</pre><p>In our handler, we will simply loop through the selected files, generate a name for our file (adding a uuid to make sure the name is unique) and run our pushImgToS3() method. It looks like this:</p><pre>import uuid from &#39;uuid/v4&#39;;</pre><pre>...</pre><pre>constructor() {<br> super()<br> this.handleAdd = this.handleAdd.bind(this)<br>}</pre><pre>handleAdd = async (event) =&gt; {<br> event.persist();</pre><pre> // Check there is some files to upload<br> if (!event || !event.target || !event.target.files) return</pre><pre>const filesLength = event.target.files.length;</pre><pre> // Loop through all selected files <br> for (let i = 0; i &lt; filesLength; i++) {<br>  const file = event.target.files[i];<br>  const filename = file.name.toLowerCase().replace(/ /g, &#39;-&#39;).replace(/[^\w-]+/g, &#39;&#39;);<br>  const fileExtension = file.name.split(&#39;.&#39;).pop();</pre><pre>  // Define the image name<br>  let mainImgName = filename + &#39;-&#39; + uuid() + &#39;.&#39; + fileExtension;</pre><pre>  // Push the image to S3<br>  await this.pushImgToS3(file, mainImgName)<br> }<br>}</pre><p>Save your change and test to import some files. Go to your AWS console and find the bucket you are playing with, the new images should now appears!</p><p>That is all you need to implement a basic S3 uplaod with Amplify. But basic will not be enough here, we also want to resize the image to be sure that the user does not upload 10mo files and push thumbnail to save us some bandwidth when we display the gallery.</p><h3>Resize the image</h3><p>Do do that we need to add some complexity to our code. At the moment it was pretty straightforward , we have a file we push it with no check or manipulation. Now we want to resize the image, that means that we need to actually open the file.</p><p>Basically we need to:</p><ol><li>Read the file</li><li>Load the image</li><li>Create a canvas the size we want for the final image</li><li>Create a new file that fit our initial image to the canvas</li></ol><p>And finally we can upload the new file to S3 as we did before.</p><p>Reading files and manipulate it is an async process, but we want to process one image after the other to be able to keep tracks on who many images have been already uploaded. To do so we can encapsulate our async actions to create a Promise, so in our handler we will be able to use await to ensure that we do every action in the right order. So add the following method to your component:</p><pre>readFileAsync(file) {<br> return new Promise((resolve, reject) =&gt; {<br>  let reader = new FileReader();<br>  reader.onload = () =&gt; {<br>   resolve(reader.result);<br>  };<br>  reader.onerror = reject;<br>  reader.readAsDataURL(file);<br> })<br>}</pre><pre>loadImgAsync(imgSrc) {<br> return new Promise((resolve, reject) =&gt; {<br>  let img = new Image();<br>  img.onload = () =&gt; {<br>   resolve(img);<br>  };<br>  img.onerror = reject;<br>  img.src = imgSrc;<br> })<br>}</pre><pre>imgToBlobAsync(img, canvas) {<br> return new Promise((resolve, reject) =&gt; {<br>  const ctxMain = canvas.getContext(&#39;2d&#39;);<br>  ctxMain.drawImage(img, 0, 0, canvas.width, canvas.height);<br>  ctxMain.canvas.toBlob(async (blob) =&gt; {<br>   resolve(blob)<br>  }, &#39;image/*&#39;);<br> })<br>}</pre><p>And modify your handler to use them:</p><pre>...</pre><pre>// Loop through all selected files <br>for (let i = 0; i &lt; filesLength; i++) {<br>    const file = event.target.files[i];<br>    const filename = file.name.toLowerCase().replace(/ /g, &#39;-&#39;).replace(/[^\w-]+/g, &#39;&#39;);<br>    const fileExtension = file.name.split(&#39;.&#39;).pop();</pre><pre>    // Define the image name<br>    let mainImgName = filename + &#39;-&#39; + uuid() + &#39;.&#39; + fileExtension;</pre><pre><strong>    // Read the image<br>    const imgSrc = await this.readFileAsync(file);<br>    const img = await this.loadImgAsync(imgSrc)</strong></pre><pre><strong>    // From the image and a canvas (for the resize), <br>    // generate a blob to be uploaded<br>    const canvas = document.createElement(&#39;canvas&#39;);<br>    const imgBlob = await this.imgToBlobAsync(img, canvas)<br>    <br>    // Create a file from the blob<br>    const fileMain = new File([imgBlob], filename, {<br>        type: &#39;image/*&#39;,<br>       lastModified: Date.now()<br>    });</strong></pre><pre>    // Push the image to S3<br>    await this.pushImgToS3(<strong>fileMain</strong>, mainImgName)<br>}</pre><pre>...</pre><p>Good, the flow is correct and if you try to upload images it should still be functional but as we didn’t setup the canvas size we don’t really know the size of the images uploaded in the end, in my case it was a 300px*150px.</p><p>For the main image we can say that we want to limit the width and the height to 1000px but of course we want to keep the original aspect ratio. A 2000*1000 image should become a 1000*500 and a 600*3000 a 200*1000.</p><pre>// From the image and a canvas (for the resize),<br>// generate a blob to be uploaded<br><strong>const canvas = this.createCanvas(img, 1000)<br></strong>const imgBlob = await this.imgToBlobAsync(img, canvas)</pre><pre>...</pre><pre>createCanvas(img, maxSize) {<br> const canvas = document.createElement(&#39;canvas&#39;);<br> if (img.width &gt; img.height) {<br>  const widthMain = maxSize;<br>  const scaleFactorMain = widthMain / img.width;<br>  canvas.width = widthMain;<br>  canvas.height = img.height * scaleFactorMain;<br> } else {<br>  const heightMain = maxSize;<br>  const scaleFactorMain = heightMain / img.height;<br>  canvas.width = img.width * scaleFactorMain;<br>  canvas.height = heightMain;<br> }<br> return canvas<br>}</pre><pre>...</pre><p>Perfect! You are now resizing the input image to another with a maximum 1000px sides while keeping the aspect ratio. It you try it you will notice that this resize method is pretty slow, so that could be an issue if you want to upload a lot of images at the same time. Maybe I ll do another tutorial to explain a bit how you can speed up the upload time but we still have work here!</p><h3>Generate and upload the thumbnail</h3><p>This part will be short has we are going to reuse most of the code above to create images with a maximum 100px side. The thumbnail name will be the same as the main with only “-thumbnail” add at the end. We are also adding the username in the file name, this will help us in the next tutorial:</p><pre>import { Storage, <strong>Auth</strong> } from &#39;aws-amplify&#39;;</pre><pre>...</pre><pre><strong>const username = await this.getCurrentUsername();</strong></pre><pre>for (let i = 0; i &lt; filesLength; i++) {<br>    const file = event.target.files[i];<br>    const filename = file.name.toLowerCase().replace(/ /g, &#39;-&#39;).replace(/[^\w-]+/g, &#39;&#39;);<br>    const fileExtension = file.name.split(&#39;.&#39;).pop();</pre><pre>// Define the image name<br>    const rootName = <strong>username + &#39;/&#39; + </strong>filename + &#39;-&#39; + uuid();<br>    let mainImgName = rootName + &#39;.&#39; + fileExtension;<br><strong>    let thumbnailImgName = rootName + &#39;-thumbnail.&#39; + fileExtension;</strong></pre><pre>    // Read the image<br>    const imgSrc = await this.readFileAsync(file);<br>    const img = await this.loadImgAsync(imgSrc)</pre><pre>    // From the image and a canvas (for the resize), <br>    // generate a blob to be uploaded<br>    const canvas = this.createCanvas(img, 1000)<br>    const imgBlob = await this.imgToBlobAsync(img, canvas)<br>    <br>    <strong>// Same with the thumbnail<br>    const canvasThumb = this.createCanvas(img, 100)<br>    const imgBlobThumb = await this.imgToBlobAsync(img, canvasThumb)</strong></pre><pre>    // Create a file from the blob for the mail and thumbnail<br>    const fileMain = new File([imgBlob], filename, {<br>        type: &#39;image/*&#39;,<br>       lastModified: Date.now()<br>    });</pre><pre>    <strong>const fileThumb = new File([imgBlobThumb], filename, {<br>        type: &#39;image/*&#39;,<br>       lastModified: Date.now()<br>    });</strong></pre><pre>    // Push the image to S3<br><strong>    await this.pushImgToS3(fileThumb, thumbnailImgName)<br></strong>    await this.pushImgToS3(fileMain, mainImgName)<br>}</pre><pre>...</pre><pre><strong>getCurrentUsername() {<br> return new Promise((resolve, reject) =&gt; {<br>     Auth.currentAuthenticatedUser()<br>  .then(user =&gt; {<br>      if (user.username) {<br>          resolve(user.username)<br>      } else {<br>          resolve(null)<br>      }<br>  })<br>  .catch(err =&gt; {<br>      console.log(err)<br>      resolve(null)<br>  });<br> })<br>}</strong></pre><p>Ok now we are done! Try to upload a picture and go check on your S3:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cruDdiX9WugRAUvLnH6c6A.png" /><figcaption>The main and thumbnail image are uploaded</figcaption></figure><p>As you can see above, I obtain a main image about slightly less than 1mo and a 13kb thumbnail, we cannot check our images for now but it seems that it is working!</p><h3>Add a counter</h3><p>Last small thing I want to add before considering this tutorial done, a small counter to know if we are uploading. First add some states:</p><pre>state = {<br> uploading: false,<br> imgToUpload: 0,<br> imgUploaded: 0,<br>}</pre><p>Initiate it in the handler and increment it at each loop:</p><pre>...</pre><pre>const filesLength = event.target.files.length;</pre><pre><strong>this.setState({<br>    uploading: true,<br>    imgToUpload: filesLength,<br>})</strong></pre><pre>// Loop through all selected files <br>for (let i = 0; i &lt; filesLength; i++) {<br>   <strong>this.setState({ imgUploaded: i })</strong><br>   <br>   ...</pre><p>Reset it after all images have been uploaded:</p><pre>...</pre><pre>this.setState({<br>    uploading: false,<br>    imgToUpload: 0,<br>    imgUploaded: 0,<br>})</pre><pre>...</pre><p>Display these information:</p><pre><strong>const { uploading, imgToUpload, imgUploaded } = this.state;</strong></pre><pre>&lt;label htmlFor=&quot;button-add-picture&quot;&gt;<br>    &lt;Button variant=&quot;contained&quot;<br>        size=&quot;large&quot;<br>        color=&quot;secondary&quot;<br>        component=&quot;span&quot;<br>        <strong>disabled={uploading}</strong><br>    &gt;<br>        &lt;AddAPhotoIcon /&gt;<br>    &lt;/Button&gt;<br>&lt;/label&gt;<br><strong>{<br>    uploading ?<br>        &lt;Box paddingLeft={1} component=&#39;span&#39;&gt;<br>            &lt;Typography component=&#39;span&#39;&gt;<br>                {imgUploaded}/{imgToUpload}<br>            &lt;/Typography&gt;<br>        &lt;/Box&gt; :<br>        null<br>}</strong></pre><p>Final result looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OiV9BQEXYKiNCOJ-jbSTCg.png" /><figcaption>Our final upload button</figcaption></figure><p>I think we are done!</p><p>That is all for this tutorial. In the next one of the series, we are going to <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/use-s3-trigger-to-create-a-dynamodb-entry-when-uploading-images-to-s3-part-9-4d7489a4584b">add a trigger to our S3 in order to add an entry to our DynamoDb</a> every time a new image is pushed to our bucket. Follow to be updated when it is out!</p><p>If you like this series or this tutorial and would like to support my work, you can <a href="https://www.buymeacoffee.com/ZYwAO7g">buy me a coffee</a> 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=705a7dc49680" width="1" height="1" alt=""><hr><p><a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/upload-and-resize-images-to-the-cloud-with-aws-s3-amplify-and-react-part-8-705a7dc49680">Upload and resize images to the cloud with Aws S3, Amplify and React (Part 8)</a> was originally published in <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app">Develop and deploy a complex serverless web app using AWS, ReactJs and AI (Rekognition)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Define your model requirements and setup your GraphQL API to DynamoDB with AWS Amplify (Part 7)]]></title>
            <link>https://medium.com/develop-and-deploy-a-complex-serverless-web-app/define-your-model-requirements-and-setup-your-graphql-api-to-dynamodb-with-aws-amplify-part-7-2e627defc318?source=rss-fab552672798------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e627defc318</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[amplify]]></category>
            <dc:creator><![CDATA[Yann]]></dc:creator>
            <pubDate>Mon, 23 Mar 2020 15:41:55 GMT</pubDate>
            <atom:updated>2020-03-24T14:34:35.099Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kD-O3-wSxOzPMvOYupwjzw.png" /><figcaption>Photo by <a href="https://unsplash.com/@pericakalimerica?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Pero Kalimero</a> on <a href="https://unsplash.com/s/photos/cloud?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This story is part of a series about how to build and deploy a complex cloud based application using Amplify and artificial intelligence, with a final result <a href="https://do93zxpqjd34l.cloudfront.net/">looking like this</a> (work in progress). In the <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/create-a-logout-button-listening-to-authentication-updates-within-your-aws-amplify-react-82685537bb4a">previous story</a>, we completed our authentication flow with Aws Amplify Auth.</p><p>The next step now is to define our data model and generate an API to manipulate it. We are going to use Aws Amplify to do that and in the end of this tutorial you should have an up and running graphQl Api you can easily use in your React application!</p><h3>Prerequisite</h3><p>If you are not following the <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/develop-ai-web-apps-aws-reactjs-define-the-project-part-1-5aa14db8fa97">complete tutorial</a>, you should be ok by reading only this one. You will just need a ReactJs project with Aws Amplify already setup.</p><p>I also assume that you are familiar with npm, react and javascript in general.</p><h3>First, define our requirements</h3><p>If you follow the full tutorial, you know that the full project contains a payments part. But in order to keep this story short, we will let this part aside.</p><p>What we are going to do is:</p><ol><li>A user log in</li><li>He/she can upload pictures</li><li>Pictures are analysed to find a text pattern so the gallery can be searchable based on images content</li></ol><p>For now, only the owner of a gallery can see it (I will detail how to do the public on a next tutorial).</p><p>Based on this requirements, it seems that we only need two tables. “Image”, to store the S3 keys of the image and the result of the analysis, and “Match” to store which images are matching the text pattern</p><h3>Add the API to Amplify</h3><p>First, lets create the API using Amplify. In a terminal run:</p><pre>amplify add api</pre><p>You will be asked few question:</p><pre>Scanning for plugins...<br>Plugin scan successful<br>? Please select from one of the below mentioned services: <strong>GraphQL</strong><br>? Provide API name: ******<br>? Choose the default authorization type for the API <strong>Amazon Cognito User Pool</strong><br>Use a Cognito user pool configured as a part of this project.<br>? Do you want to configure advanced settings for the GraphQL API <strong>No, I am done.</strong><br>? Do you have an annotated GraphQL schema? <strong>No</strong><br>? Do you want a guided schema creation? <strong>Yes</strong><br>? What best describes your project: <strong>Single object with fields (e.g., “Todo” with ID, name, description)</strong><br>? Do you want to edit the schema now? <strong>No</strong></pre><p>Here we want a GraphQL Api as it will let us interact in a very smooth way directly from our application. If you are not familiar with GraphQl, you can have a look <a href="https://graphql.org/">on their website</a>.</p><p>Using authorization based on Cognito will let you have a good control on <a href="https://aws-amplify.github.io/docs/cli-toolchain/graphql">who can do what on your model</a> and you can manage your user using the Cognito interface.</p><p>The rest is the default config. After you press enter, a new file containing your model should be available at <strong>./src/backend/api/schema.graphql </strong>and should contain a basic todo model:</p><pre>type Todo <a href="http://twitter.com/model">@model</a> {<br>  id: ID!<br>  name: String!<br>  description: String<br>}</pre><p>You can delete this lines as we will replace them with our own model.</p><h3>First the Image</h3><p>So let’s define our Image table:</p><pre>type Image<br>@model<br>{<br> key: ID!<br> owner: ID!<br> name: String!<br> online: OnlineStatus!<br> date: AWSDateTime!<br> analysisResult: String<br>}</pre><pre>enum OnlineStatus { public private }</pre><p>The <strong>key</strong> is the path to the S3 bucket the image is stored.</p><p>The <strong>owner</strong> field is the id of the user uploading the image. This field can be use to limit the object access.</p><p><strong>Name</strong>, is the name of the uploaded image. I want it in order to order my images as the time the a picture is taken is often present in the name.</p><p><strong>Online</strong>, for the moment I am not going to use it but I want to let the user not displaying certain pictures though the public Api without having to remove them for good. So this flag could be useful for this future feature.</p><p><strong>Date</strong>, when the image is uploaded.</p><p><strong>analysisResult</strong>, is the result provided by Aws Rekognition.</p><h4>@key transform</h4><p>That’s good for our fields, now let’s add some @key (if you are not familiar with the @key transform, please <a href="https://aws-amplify.github.io/docs/cli-toolchain/graphql">have a look here</a>) so we can run queries on this table. If I know the precise key of the picture I am looking for, I want to be able to run a get to have its information, so the primary key will be key. I also want to be able to query all the images with the same owner, ordered by name.</p><p>You can add the following lines to your schema:</p><pre>type Image<br> @model<br> <strong>@key(fields: [“key”])<br> @key(name: “ByOwner”, fields: [“owner”, “name”], queryField: “imagesByOwner”)</strong><br>{<br> key: ID!<br> owner: ID!<br> name: String!<br> online: OnlineStatus!<br> date: AWSDateTime!<br> analysisResult: String<br>}</pre><pre>enum OnlineStatus { public private }</pre><h4>@auth transform</h4><p>The image object creation will be triggered by the user pushing a new image to the S3. The user himself is not allowed to manipulate it. The only user allowed to read an object from the table, is the owner of this object. So the schema can be updated like this:</p><pre>type Image<br> @model<br> @key(fields: [“key”])<br> <strong>@key(name: “ByOwner”, fields: [“owner”, “name”], queryField: “imagesByOwner”)<br> @auth(rules: [{ allow: groups, groups: [“Admin”], operations: [read, create, update, delete] },<br> { allow: owner, operations: [read] }])</strong> {<br> key: ID!<br> owner: ID!<br> name: String!<br> online: OnlineStatus!<br> date: AWSDateTime!<br> analysisResult: String<br>}</pre><pre>enum OnlineStatus { public private }</pre><h4>Handle subscription</h4><p>That is already good, the access to the Image table is now protected and we can get the information the way we need it.</p><p>But there is still an issue here. We need some mechanism to be updated when an image is uploaded and/or when the analysis result has been push. This mechanism is called subscription and it is present by default when you push your graphQl schema like the one above using Amplify.</p><p>However, we are not really happy with the default behavior. If you leave it like this and subscribe to the update event, you are going to be informed that an update occurs on <strong>any</strong> object of the table! This will eventually be blocked by the check on authorization (it use to be a issue on this feature though), but it could be an issue if you want to let you users have separate albums.</p><p>We would prefer to let our users subscribe to event with some filters, here the owner. Luckily this is pretty easy to do, we need to remove the default subscription and create our own with an argument to specify the owner:</p><pre>type Image<br>  @model<strong>(subscriptions: null)</strong><br>  @key(fields: [&quot;key&quot;])<br>  @key(name: &quot;ByOwner&quot;, fields: [&quot;owner&quot;, &quot;name&quot;], queryField: &quot;imagesByOwner&quot;)<br>  @auth(rules: [{ allow: groups, groups: [&quot;Admin&quot;], operations: [read, create, update, delete] },<br>                { allow: owner, operations: [read] }]) {<br>    key: ID!<br>    owner: ID!<br>    name: String!<br>    online: OnlineStatus!<br>    date: AWSDateTime!<br>    analysisResult: String<br>}</pre><pre>enum OnlineStatus { public private }</pre><pre><strong>type Subscription {<br>  onCreateImage(owner: ID): Image </strong><a href="http://twitter.com/aws_subscribe"><strong>@aws_subscribe</strong></a><strong>(mutations: [&quot;createImage&quot;])<br>  onUpdateImage(owner: ID): Image </strong><a href="http://twitter.com/aws_subscribe"><strong>@aws_subscribe</strong></a><strong>(mutations: [&quot;updateImage&quot;])<br>  onDeleteImage(owner: ID): Image </strong><a href="http://twitter.com/aws_subscribe"><strong>@aws_subscribe</strong></a><strong>(mutations: [&quot;deleteImage&quot;])<br>}</strong></pre><p>Ok now we are done for the Image table.</p><h3><strong>The Match table</strong></h3><p>In the image table, we store the full result of Rekognition. We could send the full information to the end user and make a script searching though all the results when he/she is looking for a text. But that would not be efficient and we want to be able to limit the search to certain text pattern, for instance if we now that our bib is a series of 5 numbers, there is no need to send all texts found by Rekognition.</p><p>We are going to do that by creating another table. This table will store text found in a picture when it matches the pattern. This mean that we can have several entry for the same picture in this table.</p><p>Following the same steps than above, we can implement this table by adding the following code in our schema:</p><pre>type Match<br>  @model<br>  @key(fields: [&quot;id&quot;])<br>  @key(name: &quot;ByImageKey&quot;, fields: [&quot;key&quot;, &quot;name&quot;], queryField: &quot;matchByImageKey&quot;)<br>  @key(name: &quot;ByMatch&quot;, fields: [&quot;owner&quot;, &quot;online&quot;, &quot;match&quot;, &quot;name&quot;], queryField: &quot;imagesByMatch&quot;)<br>  @auth(rules: [{ allow: groups, groups: [&quot;Admin&quot;], operations: [read, create, update, delete] },<br>                { allow: owner, operations: [read, create, update, delete] }]) {<br>    id: ID!<br>    key: ID!<br>    owner: ID!<br>    name: String!<br>    match: String!<br>    online: OnlineStatus!<br>    date: AWSDateTime!<br>}</pre><p>Nice, this schema should be enough for our application let’s push it to AWS:</p><pre>amplify push</pre><p>And we are done! If you go to your Aws console, you should be able to see the newly created tables in DynamoDb and your new Api in ApiGateway.</p><p>That is all for this tutorial. In the next one of the series, we are going to <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/upload-and-resize-images-to-the-cloud-with-aws-s3-amplify-and-react-part-8-705a7dc49680">implement an upload component to push our pictures to S3</a>. Follow to be updated when it is out!</p><p>If you like this series or this tutorial and would like to support my work, you can <a href="https://www.buymeacoffee.com/ZYwAO7g">buy me a coffee</a> 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e627defc318" width="1" height="1" alt=""><hr><p><a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/define-your-model-requirements-and-setup-your-graphql-api-to-dynamodb-with-aws-amplify-part-7-2e627defc318">Define your model requirements and setup your GraphQL API to DynamoDB with AWS Amplify (Part 7)</a> was originally published in <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app">Develop and deploy a complex serverless web app using AWS, ReactJs and AI (Rekognition)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a logout button listening to authentication updates within your AWS Amplify React…]]></title>
            <link>https://medium.com/develop-and-deploy-a-complex-serverless-web-app/create-a-logout-button-listening-to-authentication-updates-within-your-aws-amplify-react-82685537bb4a?source=rss-fab552672798------2</link>
            <guid isPermaLink="false">https://medium.com/p/82685537bb4a</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[cloud-services]]></category>
            <category><![CDATA[amplify]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Yann]]></dc:creator>
            <pubDate>Sat, 21 Mar 2020 16:40:24 GMT</pubDate>
            <atom:updated>2020-03-23T15:43:39.046Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kD-O3-wSxOzPMvOYupwjzw.png" /><figcaption>Photo by <a href="https://unsplash.com/@pericakalimerica?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Pero Kalimero</a> on <a href="https://unsplash.com/s/photos/cloud?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Create a logout button listening to authentication updates within your AWS Amplify React application (Part 6)</h3><p>This story is part of a series about how to build and deploy a complex cloud based application using Amplify and artificial intelligence, with a final result <a href="https://do93zxpqjd34l.cloudfront.net/">looking like this</a> (work in progress). In the <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/add-authentication-to-your-reactjs-project-using-amplify-auth-part-5-aad47ec737e3">previous story</a>, we added an authentication flow with Aws Amplify Auth. Now we can sign in and log in, but once it is done, there is no way to log out. In this tutorial we will add an authentication listener to display a log out button whenever the user is log in.</p><h3>Prerequisite</h3><p>If you didn’t follow the <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/add-authentication-to-your-reactjs-project-using-amplify-auth-part-5-aad47ec737e3">previous</a> tutorial and are interested only in this one, you will need a <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/initialize-a-reactjs-git-amplify-project-with-test-and-prod-backend-environment-part-2-de2a285fa268">ReactJs project already setup</a>, <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/add-authentication-to-your-reactjs-project-using-amplify-auth-part-5-aad47ec737e3">Aws Amplify already configured</a> with a login portal. If you need guidance to have everything setup, I suggest you go through my previous tutorials.</p><p>I also assume that you are familiar with npm, react and javascript in general.</p><p>For now we have this page where we need to log in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-etXrTK6SZH35C_vlH_E4w.png" /><figcaption>When you try to go to “projects” you need to log in</figcaption></figure><p>And when you log in you can see the project component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xUgk1gnGF6oHTvQRkLtbXQ.png" /><figcaption>Once you are logged in you see your (empty) page</figcaption></figure><h3>What do we want</h3><p>We want to add a logout button whenever the visitor is connected. To do so we first need to received a signal when the user status is updated. Luckily Amplify provide us with Hub which do exactly that.</p><h3>Create the logout button</h3><p>Go in your navigation component, if you follow the tutorial, it should be called <strong>Layout.js.</strong></p><p>First we need to create a state that will determined if the logout button should be displayed, we will call it “<em>sLogged </em>and will be default to <em>false</em>:</p><pre>...<br>class Layout extends Component {<br>    state = {<br>        mobileOpen: false,<br>        <strong>isLogged: false,</strong><br>    };<br>...</pre><p>Add an item to the navigation only displayed if <em>isLogged</em> is true:</p><pre>...</pre><pre><strong>import ExitToAppIcon from &#39;@material-ui/icons/ExitToApp&#39;;</strong></pre><pre>...</pre><pre>const { mobileOpen, <strong>isLogged</strong> } = this.state;</pre><pre>...</pre><pre>&lt;/ListItem&gt;<br>&lt;Divider /&gt;<br><strong>{<br> isLogged ?<br> &lt;List&gt;<br>  &lt;ListItem&gt;<br>   &lt;ListItemIcon&gt;<br>    &lt;ExitToAppIcon className={classes.icon} /&gt;<br>   &lt;/ListItemIcon&gt;<br>   &lt;ListItemText primary=&quot;Log out&quot; /&gt;<br>  &lt;/ListItem&gt;<br> &lt;/List&gt;<br> :<br> null<br>}</strong></pre><pre>...</pre><p>You can check that everything work as expected by turning <em>isLogged</em> default value from false to true, your logout button should be displayed.</p><p>That is nice but this is not a very useful button at the moment, we need to add some code to make it an actual log out button:</p><pre><strong>import { Auth } from &#39;aws-amplify&#39;;</strong></pre><pre>...</pre><pre><strong>async onSignOutClick() {<br> await Auth.signOut()<br>     .then(data =&gt; console.log(data))<br>     .catch(err =&gt; console.log(err));<br>}</strong></pre><pre>render() {</pre><pre>...</pre><pre>&lt;ListItem<strong> button onClick={this.onSignOutClick}</strong>&gt;<br> &lt;ListItemIcon&gt;<br>  &lt;ExitToAppIcon className={classes.icon} /&gt;<br>  &lt;/ListItemIcon&gt;<br> &lt;ListItemText primary=&quot;Log out&quot; /&gt;<br>&lt;/ListItem&gt;</pre><p>Better, now we can actually log out, but the button is still not link to the current user status.</p><h3>Get the current user status</h3><p>So now we need a method to know if a user is logged in or not. The amplify hub can listen a change in the user status but we also need to have this information when the component is loaded. So let’s create a method returning the current username if user is logged and null if not. To be able to wait for a response, it will be a Promise:</p><pre><strong>import { Auth } from &#39;aws-amplify&#39;;</strong></pre><pre>...</pre><pre>class Layout extends Component {</pre><pre>...</pre><pre><strong>getCurrentUsername() {<br> return new Promise((resolve, reject) =&gt; {<br>  Auth.currentAuthenticatedUser()<br>   .then(user =&gt; {<br>    if (user.username) {<br>     console.log(user.username)<br>     resolve(user.username)<br>    } else {<br>     console.log(user)<br>     resolve(null)<br>    }<br>   })<br>   .catch(err =&gt; {<br>    console.log(err)<br>    resolve(null)<br>   });<br> })<br>}</strong></pre><pre>...</pre><p>Now that we are able to check at any time if the user is logged, we can create another method to update our component state:</p><pre>...</pre><pre>constructor() {<br> super();<br> this.updateLoggedStatus = this.updateLoggedStatus.bind(this)<br>}</pre><pre>async updateLoggedStatus() {<br> const username = await this.getCurrentUsername()<br> let newLoggedStatus = false;<br> if (username) newLoggedStatus = true;<br> this.setState({ isLogged: newLoggedStatus });<br>}</pre><pre>...</pre><p>Nice, we can trig this check when the component is mount using the componentDidMount() method:</p><pre>...</pre><pre>componentDidMount() {<br> this.updateLoggedStatus();<br>}</pre><pre>...</pre><p>If you reload you project at this point, the log in button should be correctly displayed based on the current user status. If you are log in, the logout button is displayed and if you click it, your protected page is not displayed anymore. But the log out button is still displayed after you logged out, which is normal as we are not detecting user status update yet.</p><p>To do so we are going to use <a href="https://aws-amplify.github.io/docs/js/hub">Amplify Hub</a>. This Hub let you listen what is happening on the amplify side, here we are interested in the <strong>auth</strong> channel. It would be slightly easier to just toggle the <em>isLogged</em> state when the log out button is pressed, but I want to be able to detect the event if the log out comes from anywhere (another button for example). Let’s simply add the listener in the <strong>componentDidMount()</strong> and remove it in the <strong>componentWillUnmount()</strong>:</p><pre>import { Auth, <strong>Hub</strong> } from &#39;aws-amplify&#39;;</pre><pre>...</pre><pre>componentDidMount() {<br> this.updateLoggedStatus();<br><strong> Hub.listen(&#39;auth&#39;, this.updateLoggedStatus);<br></strong>}</pre><pre><strong>componentWillUnmount() {<br> Hub.remove(&#39;auth&#39;);<br>}</strong></pre><pre>...</pre><p>Now everything should be working as expected. The final code we added looks like something like this:</p><pre>...</pre><pre>constructor() {<br> super();<br> this.updateLoggedStatus = this.updateLoggedStatus.bind(this)<br>}</pre><pre>componentDidMount() {<br> this.updateLoggedStatus();<br> Hub.listen(&#39;auth&#39;, this.updateLoggedStatus);<br>}</pre><pre>componentWillUnmount() {<br> Hub.remove(&#39;auth&#39;);<br>}</pre><pre>async updateLoggedStatus() {<br> const username = await this.getCurrentUsername()<br> let newLoggedStatus = false;<br> if (username) newLoggedStatus = true;<br> this.setState({ isLogged: newLoggedStatus });<br>}</pre><pre>getCurrentUsername() {<br> return new Promise((resolve, reject) =&gt; {<br> Auth.currentAuthenticatedUser()<br>  .then(user =&gt; {<br>      if (user.username) {<br>   console.log(user.username)<br>   resolve(user.username)<br>      } else {<br>   console.log(user)<br>   resolve(null)<br>      }<br>  })<br>  .catch(err =&gt; {<br>      console.log(err)<br>      resolve(null)<br>  });<br> })<br>}</pre><pre>async onSignOutClick() {<br> await Auth.signOut()<br>     .then(data =&gt; console.log(data))<br>     .catch(err =&gt; console.log(err));<br>}</pre><pre>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MKYlofIxQCSGgQQnM3_HlA.png" /><figcaption>Before you log in</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wHqtJvIRGmcheyirio8uqg.png" /><figcaption>After you log in</figcaption></figure><p>Ok I think that is all for this tutorial, the authentication workflow is now completed! Your can now protect certain part of your application that need the user to log in. A user can create an account, login, log out and the app should always be nicely displayed 😊</p><p>The next step will be a big one, we are going to define our <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/define-your-model-requirements-and-setup-your-graphql-api-to-dynamodb-with-aws-amplify-part-7-2e627defc318">application data model and create the corresponding API using Amplify and GraphQl</a>.</p><p>If you like this series or this tutorial and would like to support my work, you can <a href="https://www.buymeacoffee.com/ZYwAO7g">buy me a coffee</a> 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82685537bb4a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/create-a-logout-button-listening-to-authentication-updates-within-your-aws-amplify-react-82685537bb4a">Create a logout button listening to authentication updates within your AWS Amplify React…</a> was originally published in <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app">Develop and deploy a complex serverless web app using AWS, ReactJs and AI (Rekognition)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add and customize Amplify Authentication component in your ReactJs project (Part 5)]]></title>
            <link>https://medium.com/develop-and-deploy-a-complex-serverless-web-app/add-authentication-to-your-reactjs-project-using-amplify-auth-part-5-aad47ec737e3?source=rss-fab552672798------2</link>
            <guid isPermaLink="false">https://medium.com/p/aad47ec737e3</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[cognito]]></category>
            <category><![CDATA[serverless-apps]]></category>
            <category><![CDATA[amplify]]></category>
            <dc:creator><![CDATA[Yann]]></dc:creator>
            <pubDate>Sat, 21 Mar 2020 11:38:37 GMT</pubDate>
            <atom:updated>2020-03-23T08:42:25.773Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kD-O3-wSxOzPMvOYupwjzw.png" /><figcaption>Photo by <a href="https://unsplash.com/@pericakalimerica?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Pero Kalimero</a> on <a href="https://unsplash.com/s/photos/cloud?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This story is part of a series about how to build and deploy a complex cloud based application using Amplify and artificial intelligence, with a final result <a href="https://do93zxpqjd34l.cloudfront.net/">looking like this</a> (work in progress). In the previous <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/add-react-router-dom-to-a-reactjs-with-material-ui-project-part-4-f8d7e02f041a">story</a>, we added React Router Dom to our project so our user can now navigate though our application. But some of our pages have to be limited to members only, we have to add a login feature that protect them. This will be done using AWS Amplify that will setup Cognito for us.</p><h3>Prerequisite</h3><p>If you didn’t follow the previous tutorial and are interested only in this one, you will just need a ReactJs project already setup with Aws Amplify already configured. If you need guidance to configure it, have a look on <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/initialize-a-reactjs-git-amplify-project-with-test-and-prod-backend-environment-part-2-de2a285fa268">the corresponding tutorial</a>.</p><p>I also assume that you are familiar with npm, react and javascript in general.</p><h3>Configure Auth with Amplify client</h3><p>First you need to add Amplify library to the project, to do so run:</p><pre>npm add aws-amplify aws-amplify-react</pre><p>Then you need to configure Amplify in the project, you can do that in the App.js by adding the following lines:</p><pre>import Amplify from &#39;aws-amplify&#39;;<br>import awsconfig from &#39;./aws-exports&#39;;</pre><pre>Amplify.configure(awsconfig);</pre><p>Now that Amplify is configured we can add Auth:</p><pre>amplify add auth</pre><p>For now we can keep it simple, the user log with an email and we let the default configuration, but keep in mind that you can custom the auth flow as you want, check <a href="https://aws-amplify.github.io/docs/js/authentication">the doc</a> for more info. Answer as follow:</p><pre>Do you want to use the default authentication and security configuration? Default configuration<br> Warning: you will not be able to edit these selections. <br> How do you want users to be able to sign in? Email<br> Do you want to configure advanced settings? No, I am done.</pre><p>And finally, push your changes so Amplify creates everything on AWS side:</p><pre>amplify push</pre><p>And that’s all! That is why Amplify is an amazing tool, it literately take 1 or 2 min to have Cognito setup and linked with your frontend. But we are not done yet, Auth is configured but our app is not secured yet.</p><h3>Protect a page</h3><p>Here you have different solution depending on what you want to do. The basic example would be to protect the whole application by protecting directly the App.js. But in our case we don’t want our whole app to need user to log in, a visitor can still open it and see the <strong>home</strong> page.</p><p>If you follow the series you should have the following structure:</p><p><strong>App.js</strong> contains <strong>Layout.js</strong> displaying one page between <strong>Home.js</strong> and <strong>Projects.js</strong> based on the path.</p><p>We want visitor to be able to see <strong>Home.js</strong> but to be asked to login to see <strong>Projects.js</strong>. We are going to achieve that with the <a href="https://aws-amplify.github.io/docs/js/authentication"><strong>withAuthenticator</strong>() Amplify HOC</a>. Open your Projects component and apply the following modification:</p><pre>import React, { Component } from &#39;react&#39;;<br>import { Box } from &#39;<a href="http://twitter.com/material">@material</a>-ui/core&#39;;<br><strong>import { withAuthenticator } from &#39;aws-amplify-react&#39;;</strong></pre><pre>class Projects extends Component {<br>    render() {<br>        return (<br>            &lt;Box&gt;<br>                Projects<br>            &lt;/Box&gt;<br>        );<br>    }<br>}</pre><pre><strong>export default withAuthenticator(Projects, true);</strong></pre><p>That all, the Projects component is not exported through the amplify authentication and will be displayed only id the user is connected.</p><p>Run npm start to see the result and visit the Project page. If you are following the whole tutorial you should have something like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fjY9fBZzg8Z61NeO84iwTQ.png" /><figcaption>Projects page is now protected by Amplify Auth</figcaption></figure><p>Ok our page is now protected. But there are still two issue we have to patch before we can consider it is done. First texts displayed is not correct, the user is ask for a username but I want them to log in with their email. When the user want to create an account, the form asks for username, email, password and phone number. I don’t want all this information but only email and password. Second the styling is definitely not matching the rest of my app so I would like to update it a bit.</p><h3>Updating the text in Amplify Auth</h3><p>Let’s start with our first issue. Create a folder call <strong>Config</strong> with two files in it: <strong>AuthConfig.js </strong>and <strong>AuthTheme.js</strong>.</p><p>In <strong>AuthConfig.js</strong>, export a signUpConfig constant like that:</p><pre>export const signUpConfig = {};</pre><p>The <strong>withAuthenticator() </strong>definition is the following:</p><pre>withAuthenticator(Comp: any, includeGreetings?: boolean, authenticatorComponents?: any[], federated?: any, theme?: any, signUpConfig?: {})</pre><p>with:</p><ol><li>Comp: The component we want to protect</li><li>includeGreetings: If true, a welcome {username} will be displayed at the tom of our protected component, we don’t want that.</li><li>authenticatorComponents: You can override here some of the default component of the Auth workflow. As we are pretty happy with the default workflow we are going to pass an empty array.</li><li>federated: If you use federation (login with social media), you need to add some config. As we are not we simply set it to null.</li><li>them: that is where we are going to put our custom theme.</li><li>signUpConfig: That is where we are going to specify what the user is supposed to see or not.</li></ol><p>Ok, now that we know what all options are about, let go back to <strong>Project.js</strong> and import <strong>AuthTheme</strong> and <strong>signUpConfig</strong> and add arguments to<strong> withAuthenticator().</strong></p><pre>import React, { Component } from &#39;react&#39;;<br>import { Box } from &#39;<a href="http://twitter.com/material">@material</a>-ui/core&#39;;<br>import { withAuthenticator } from &#39;aws-amplify-react&#39;;<br><strong>import AuthTheme from &#39;../../Config/AuthTheme&#39;;<br>import { signUpConfig } from &#39;../../Config/AuthConfig&#39;;</strong></pre><pre>class Projects extends Component {<br>    render() {<br>        return (<br>            &lt;Box&gt;<br>                Projects<br>            &lt;/Box&gt;<br>        );<br>    }<br>}<br><strong>export default withAuthenticator(Projects, false, [], null, AuthTheme, signUpConfig);</strong></pre><p>We are now ready to make some changes. First we want to hide the phone number and the email fields in the sign in configuration. The tricky thing here is that the field username will actually contained the user email as we asked the email to be the way user log in in our application.</p><pre>export const signUpConfig = {<br>    hiddenDefaults: [<br>        &#39;phone_number&#39;,<br>        &#39;email&#39;<br>    ],<br>};</pre><p>If you try now to display the sign in form, only username and password fields are displayed.</p><p>So that is functional but the user will not realize that he/she is supposed to enter an email in the username field, for that we can update the text displayed. To do so we have to use <a href="https://www.npmjs.com/package/i18n">I18n</a>, that Amplify is using to display texts. Basically each sentence is store as a key and a value to display. By default the key equal the value so the key ‘Username’ will return ‘Username’ as a value. But you can overwrite it to display whatever you want, or even translate all the workflow if you are not developing an English application. So in the <strong>AuthConfig.js </strong>do the following:</p><pre><strong>import { I18n } from &#39;aws-amplify&#39;;</strong></pre><pre>export const signUpConfig = {<br>    hiddenDefaults: [<br>        &#39;phone_number&#39;,<br>        &#39;email&#39;<br>    ],<br>};</pre><pre><strong>const authScreenLabels = {<br>    en: {<br>        &#39;Sign in to your account&#39;: &#39;Protected page, please log in&#39;,<br>        &#39;Enter your username&#39;: &#39;Enter your email&#39;,<br>        &#39;Username&#39;: &#39;Email&#39;,<br>    }<br>};</strong></pre><pre><strong>I18n.setLanguage(&#39;en&#39;);<br>I18n.putVocabularies(authScreenLabels);</strong></pre><p>That’s it! Now all texts should be correct. But we still have this AWS orange theme… let’s change that.</p><h3>Updating AWS Amplify theme</h3><p>The theme can be customized with a lot of details, but here we are simply going to change the links and buttons color which will be enough to have a style matching our application. I ll probably make another tutorial to explain in more detail all the parameters you can customize. For now, update <strong>AuthTheme.js </strong>like this:</p><pre>export const Button = {&#39;backgroundColor&#39;: &#39;#17252A&#39;};<br>export const A = {&#39;color&#39;: &#39;#17252A&#39;};</pre><pre>const AuthTheme = {<br>  button: Button,<br>  a: A,<br>};</pre><pre>export default AuthTheme;</pre><p>Perfect, we finally get ride of the orange! Our authentication workflow is now ready and nice looking, if you follow the full tutorial you should obtain something like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-etXrTK6SZH35C_vlH_E4w.png" /><figcaption>Authentication with custom theme and texts</figcaption></figure><p>Try to sign up by clicking “create an account”, fill everything, get the confirmation code by email and log in. Your hidden component should now be displayed correctly.</p><p>We used a lot the default parameters, but you can also customize the email address sending you the verification code and the texts displayed. But that will be for another tutorial.</p><p>For now, we have a bigger problem with our current application. We cannot log out!</p><p>But I feel this chapter is long enough, so I ll show you how to add auth listener in your layout to <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/create-a-logout-button-listening-to-authentication-updates-within-your-aws-amplify-react-82685537bb4a">display a log out button in the next tutorial</a>.</p><p>If you like this series or this tutorial and would like to support my work, you can <a href="https://www.buymeacoffee.com/ZYwAO7g">buy me a coffee</a> 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aad47ec737e3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/add-authentication-to-your-reactjs-project-using-amplify-auth-part-5-aad47ec737e3">Add and customize Amplify Authentication component in your ReactJs project (Part 5)</a> was originally published in <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app">Develop and deploy a complex serverless web app using AWS, ReactJs and AI (Rekognition)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add React Router Dom to a ReactJs with Material UI project (Part 4)]]></title>
            <link>https://medium.com/develop-and-deploy-a-complex-serverless-web-app/add-react-router-dom-to-a-reactjs-with-material-ui-project-part-4-f8d7e02f041a?source=rss-fab552672798------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8d7e02f041a</guid>
            <category><![CDATA[react-router]]></category>
            <category><![CDATA[material-ui]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-router-dom]]></category>
            <dc:creator><![CDATA[Yann]]></dc:creator>
            <pubDate>Fri, 20 Mar 2020 15:33:07 GMT</pubDate>
            <atom:updated>2020-03-23T08:42:42.054Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kD-O3-wSxOzPMvOYupwjzw.png" /><figcaption>Photo by <a href="https://unsplash.com/@pericakalimerica?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Pero Kalimero</a> on <a href="https://unsplash.com/s/photos/cloud?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This story is part of a series about how to build and deploy a complex cloud based application using Amplify and artificial intelligence, with a final result <a href="https://do93zxpqjd34l.cloudfront.net/">looking like this</a> (work in progress). In the previous <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/make-a-beautiful-and-mobile-friendly-vertical-navigation-with-reactjs-and-material-ui-part-3-b91b442a2230">story</a>, we made a nice looking layout with a left navigation and mobile friendly. Now that we have a navigation bar, it is time to let our users actually navigate through pages. To do that we are going to use <a href="https://reacttraining.com/react-router/">React Router Dom</a> that will handle the hard work for us.</p><h3>Prerequisite</h3><p>If you didn’t follow the previous tutorial and are interested only in this one, you will just need a ReactJs project already setup. A common layout containing every pages would also be a good thing but it is not mandatory.</p><p>I also assume that you are familiar with npm, react and javascript in general.</p><h3>Install React Router</h3><p>To install react router, simply get it from npm:</p><pre>npm install react-router-dom</pre><p>Now this package should appear in your package.json</p><h3>Create needed files</h3><p>First of all, we are going to create the pages we would like to display: <strong>Home</strong> and <strong>Projects.</strong></p><p>Create a new folder <strong>Pages</strong> in <strong>src</strong> and add two files: <strong>src/Pages/Home/Home.js</strong> and <strong>src/Pages/Projects/Projects.js.</strong></p><p>Create a empty component in those files like this for :</p><pre>import React, { Component } from &#39;react&#39;;<br>import { Box } from &#39;<a href="http://twitter.com/material">@material</a>-ui/core&#39;;</pre><pre>class Home extends Component {<br>    render() {<br>        return (<br>            &lt;Box&gt;<br>                Home<br>            &lt;/Box&gt;<br>        );<br>    }<br>}<br>export default Home</pre><p>If you are using the layout from the previous tutorial, update it slightly so the main content of the layout is the children component:</p><pre>&lt;main className={classes.content}&gt;<br> &lt;Hidden mdUp implementation=&quot;css&quot;&gt;<br>  &lt;div className={classes.toolbar} /&gt;<br> &lt;/Hidden&gt;<br> &lt;Box width=&quot;100%&quot; className=&quot;mainContent&quot;&gt;<br>  <strong>{this.props.children}</strong><br> &lt;/Box&gt;<br>&lt;/main&gt;</pre><h3>Create a router file</h3><p>In order to have a clean code, create a router component in the src: <strong>src/Routing.js</strong></p><pre>import React from &#39;react&#39;;</pre><pre>import { Route } from &quot;react-router-dom&quot;;<br>import { withRouter } from &#39;react-router-dom&#39;;</pre><pre>import Home from &#39;./Pages/Home/Home&#39;<br>import Projects from &#39;./Pages/Projects/Projects&#39;<br>import Layout from &#39;./Layout/Layout&#39;;</pre><pre>export const HomeRoute = &quot;/&quot;;<br>export const ProjectsRoute = &quot;/projects/&quot;;</pre><pre>class Routing extends React.Component {<br>    render() {<br>        return (<br>            &lt;Layout&gt;<br>                &lt;Route path={HomeRoute} exact component={Home} /&gt;<br>                &lt;Route path={ProjectsRoute} component={Projects} /&gt;<br>            &lt;/Layout &gt;<br>        );<br>    }<br>}</pre><pre>export default withRouter(Routing);</pre><p>In this file we can see that we import the two previously created component <strong>Home</strong> and <strong>Projects</strong>. We also define a <strong>paths</strong> (<strong>HomeRoute</strong> and <strong>ProjectsRoute</strong>) that React Router should recognize in order to decide which <strong>Route</strong> component it has to displayed. Those paths are exported so we will be able to use them from other pages in order to create link. Finally both routes are wrapped into our <strong>Layout</strong>. <strong>withRouter </strong>will add props to your component to give you information about the navigation, history… we are not using it for now but if you follow the series to the end you will see a use for it.</p><h3><strong>Update App.js</strong></h3><p>The last thing you will need to do in order to have your router functional is to update your App.js to point to your router component:</p><pre>import React from &#39;react&#39;;<br>import &#39;./App.css&#39;;<br><strong>import { BrowserRouter as Router } from &quot;react-router-dom&quot;;<br>import Routing from &#39;./Routing.js&#39;;</strong></pre><pre>function App() {<br>  return (<br>    <strong>&lt;Router&gt;&lt;Routing /&gt;&lt;/Router&gt;</strong><br>  );<br>}</pre><pre>export default App;</pre><p>Perfect! Your router is now functional.</p><p>You can test it by running npm start. When it starts, the path will be <strong>localhost:300</strong>, so react router will match it with <strong>HomeRoute</strong> and your <strong>Home</strong> component will be displayed. If you change manually the address by <strong>localhost:300/projects</strong>, now react router will match with <strong>ProjectsRoute</strong> and display the <strong>Projects</strong> component.</p><h3>Create some links</h3><p>Ok that is good, but you don’t want your user to navigate by changing the address manually right? So we need to create some links in our navigation drawer.</p><p>React Router provides a &lt;Link /&gt; component, but we were using Material UI and we would prefer to continue that way. Luckily it is very easy to ask our &lt;ListItem /&gt; component to integrate the React Router component directly!</p><p>Go back to your Layout.js and apply the following changes:</p><pre>import { Box, List, Divider, ListItem, ListItemIcon, ListItemText, Hidden, Drawer, Typography, AppBar, Toolbar, IconButton } from &#39;<a href="http://twitter.com/material">@material</a>-ui/core&#39;;<br>import PersonIcon from &#39;<a href="http://twitter.com/material">@material</a>-ui/icons/Person&#39;;</pre><pre>import Help from &#39;<a href="http://twitter.com/material">@material</a>-ui/icons/Help&#39;;<br>import MenuIcon from &#39;<a href="http://twitter.com/material">@material</a>-ui/icons/Menu&#39;;</pre><pre><strong>import { ProjectsRoute, HomeRoute } from &#39;../Routing&#39;;<br>import { Link } from &quot;react-router-dom&quot;;</strong></pre><pre>&lt;List&gt;<br>    &lt;ListItem <strong>button component={Link} to={HomeRoute}</strong><br>  onClick={mobileOpen ? this.handleDrawerToggle : null}&gt;<br>        &lt;ListItemIcon&gt;<br>            &lt;Help className={classes.icon} /&gt;<br>        &lt;/ListItemIcon&gt;<br>        &lt;ListItemText primary=&quot;Home&quot; /&gt;<br>    &lt;/ListItem&gt;<br>    &lt;Divider /&gt;<br>    &lt;ListItem <strong>button component={Link} to={ProjectsRoute</strong>}<br>  onClick={mobileOpen ? this.handleDrawerToggle : null}&gt;<br>        &lt;ListItemIcon&gt;<br>            &lt;PersonIcon className={classes.icon} /&gt;<br>        &lt;/ListItemIcon&gt;<br>        &lt;ListItemText primary=&quot;Projects&quot; /&gt;<br>    &lt;/ListItem&gt;<br>    &lt;Divider /&gt;</pre><p>Save your changes, and everything should be working perfectly now! When you click on the Home or Projects button in your drawer, the correct component should be displayed 😊</p><p>The next step for this series will be to <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/add-authentication-to-your-reactjs-project-using-amplify-auth-part-5-aad47ec737e3">add authentication capabilities to our application using Amplify Auth</a>.</p><p>If you like this series or this tutorial and would like to support my work, you can <a href="https://www.buymeacoffee.com/ZYwAO7g">buy me a coffee</a> 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8d7e02f041a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/add-react-router-dom-to-a-reactjs-with-material-ui-project-part-4-f8d7e02f041a">Add React Router Dom to a ReactJs with Material UI project (Part 4)</a> was originally published in <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app">Develop and deploy a complex serverless web app using AWS, ReactJs and AI (Rekognition)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make a beautiful and mobile friendly vertical navigation with ReactJs and Material UI (Part 3)]]></title>
            <link>https://medium.com/develop-and-deploy-a-complex-serverless-web-app/make-a-beautiful-and-mobile-friendly-vertical-navigation-with-reactjs-and-material-ui-part-3-b91b442a2230?source=rss-fab552672798------2</link>
            <guid isPermaLink="false">https://medium.com/p/b91b442a2230</guid>
            <category><![CDATA[material-ui]]></category>
            <category><![CDATA[navigation-drawer]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[sass]]></category>
            <category><![CDATA[material-design]]></category>
            <dc:creator><![CDATA[Yann]]></dc:creator>
            <pubDate>Fri, 20 Mar 2020 13:53:26 GMT</pubDate>
            <atom:updated>2020-03-23T08:42:57.119Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kD-O3-wSxOzPMvOYupwjzw.png" /><figcaption>Photo by <a href="https://unsplash.com/@pericakalimerica?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Pero Kalimero</a> on <a href="https://unsplash.com/s/photos/cloud?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This story is part of a series about how to build and deploy a complex cloud based application using Amplify, with a final result <a href="https://do93zxpqjd34l.cloudfront.net/">looking like this</a> (work in progress). In the previous <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/initialize-a-reactjs-git-amplify-project-with-test-and-prod-backend-environment-part-2-de2a285fa268">story</a>, we initialized our project with React and Amplify and we defined a clean workflow with Git and Amplify env. Here, we are going to make a nice looking and mobile friendly interface using <a href="https://material-ui.com/">Material UI</a>.</p><h3>Prerequisite</h3><p>If you didn’t follow the previous tutorial and are interested only in this one, you will only need a ReactJs project already setup.</p><p>I also assume that you are familiar with npm, react and javascript in general.</p><h3>Get Material UI</h3><p><a href="https://material-ui.com/">Material UI</a> is a React component library helping you to create easily interface without reinventing the wheel every time. It is based on <a href="https://material.io/design/">Material Design</a> which is the rules edited by Google about how to style you application.</p><p>So first you need to install material ui and icons:</p><pre>npm install @material-ui/core<br>npm install @material-ui/icons</pre><p>Perfect, you can now use material ui components and icons directly in your own code.</p><h3>Get SASS</h3><p><a href="https://sass-lang.com/">Sass</a> is a css extension that let you create .scss files. It adds interesting features to make your life easier like nested class (I know you can do it with css, but you have to admit that the syntax is not super user friendly) or variables. When you run or build your application Sass will transpile your code to standard css.</p><p>To install it you can simply do:</p><pre>npm install node-sass</pre><h3>What do we want</h3><p>It is always a good idea to define a bit what you want before you actually start coding. Here we want:</p><ol><li>A navigation drawer on the left of the screen</li><li>The drawer is fix for large screen</li><li>On mobile, we want a retractable drawer and a navbar</li><li>We also want to show our logo on the top of the drawer</li></ol><p>You can find below the final result you should be able to obtain after this tutorial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LdreP7TkCVc_v2r-zViVYw.png" /><figcaption>That is what we want our drawer to looks like on large screen</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*4QBsXhzuJyvo9CBJr429AA.png" /><figcaption>And here is the mobile version of the drawer</figcaption></figure><h3>Let’s start!</h3><p>Now that we know where we are going, it is time to go to it!</p><p>First create a layout component in your src folder like this: src/Layout/Layout.js</p><p>also create a .scss file: src/Layout/Layout.scss</p><p>In Layout.js start a empty component:</p><pre>import React, { Component } from &#39;react&#39;;<br>import &#39;./Layout.scss&#39;;<br>import { Box } from &#39;<a href="http://twitter.com/material">@material</a>-ui/core&#39;;</pre><pre>class Layout extends Component {<br>    render() {<br>        return (<br>            &lt;Box&gt;<br>                Layout<br>         &lt;/ Box&gt;<br>        );<br>    }<br>}<br>export default Layout</pre><p>Go to your App.js and display your new component</p><pre>function App() {<br>   return (<br>      &lt;Layout/&gt;<br>   );<br>}</pre><p>Run npm start to check that you have your component displayed as expected.</p><p>Now go back to Layout.js and create the drawer in the <em>render()</em> function, for now we only put two button and they are not doing anything, we are just trying to obtain a nice looking result:</p><pre>const drawer = (<br>    &lt;div id=&quot;drawer-container&quot;&gt;<br>        &lt;div className=&quot;logo-drawer&quot; /&gt;<br>        &lt;List&gt;<br>            &lt;ListItem&gt;<br>                &lt;ListItemIcon&gt;<br>                    &lt;Help /&gt;<br>                &lt;/ListItemIcon&gt;<br>                &lt;ListItemText primary=&quot;About&quot; /&gt;<br>            &lt;/ListItem&gt;<br>            &lt;Divider /&gt;<br>            &lt;ListItem&gt;<br>                &lt;ListItemIcon&gt;<br>                    &lt;PersonIcon /&gt;<br>                &lt;/ListItemIcon&gt;<br>                &lt;ListItemText primary=&quot;Log in&quot; /&gt;<br>            &lt;/ListItem&gt;<br>        &lt;/List&gt;<br>    &lt;/div&gt;<br>);</pre><p>Don’t forget to import all new components</p><pre>import { Box, List, Divider, ListItem, ListItemIcon, ListItemText } from &#39;@material-ui/core&#39;;<br>import PersonIcon from &#39;@material-ui/icons/Person&#39;;<br>import Help from &#39;@material-ui/icons/Help&#39;;</pre><p>Display your new drawer</p><pre>return (<br>    &lt;div&gt;<br>        &lt;div id=&quot;main-background&quot; /&gt;<br>        &lt;div id=&quot;main-layout&quot;&gt;<br>            &lt;div &gt;<br>                &lt;nav&gt;<br>                    &lt;Hidden smDown implementation=&quot;css&quot;&gt;<br>                        &lt;Drawer<br>                            variant=&quot;permanent&quot;<br>                            open<br>                        &gt;<br>                            {drawer}<br>                        &lt;/Drawer&gt;<br>                    &lt;/Hidden&gt;<br>                &lt;/nav&gt;<br>                &lt;main&gt;<br>                    &lt;Box width=&quot;100%&quot; className=&quot;mainContent&quot;&gt;<br>                       &lt;Typography variant=&#39;h1&#39;&gt;Hello&lt;/Typography<br>                    &lt;/Box&gt;<br>                &lt;/main&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>);</pre><p>Import the new component Hidden and Drawer and display the result. Pretty ugly for now but you have a left navigation running.</p><p>Let’s add a some styling and theme using material ui libraries. First import the following:</p><pre>import { withStyles, MuiThemeProvider, createMuiTheme } from &#39;<a href="http://twitter.com/material">@material</a>-ui/core/styles&#39;;</pre><p>Now create few classes at the top of the document:</p><pre>const drawerWidth = 250;</pre><pre>const theme = createMuiTheme({<br>    palette: {<br>        primary: {<br>            main: &#39;#fefefe&#39;,<br>        },<br>        secondary: {<br>            main: &#39;#3e4f6a&#39;,<br>        },<br>    },<br>});</pre><pre>const styles = theme =&gt; ({<br>    root: {<br>        display: &#39;flex&#39;,<br>    },<br>    drawer: {<br>        width: drawerWidth,<br>        flexShrink: 0,<br>    },<br>    drawerPaper: {<br>        width: drawerWidth,<br>        backgroundColor: &quot;rgba(23, 37, 42, 1)&quot;,<br>        color: &quot;#fefefe&quot;,<br>        border: &quot;none&quot;,<br>    },<br>    content: {<br>        flexGrow: 1,<br>        minHeight: &quot;100vh&quot;,<br>    },<br>    icon: {<br>        color: &quot;#fefefe&quot;,<br>    }<br>});</pre><p>And apply the newly created style to the component:</p><pre>export default withStyles(styles)(Layout)</pre><p>Set your new style by updating the following lines:</p><pre>render() {<br>const { classes } = this.props;<br>…<br>&lt;Help className={classes.icon} /&gt;<br>…<br>&lt;PersonIcon className={classes.icon} /&gt;<br>…</pre><pre>&lt;div id=&quot;main-layout&quot;&gt;<br>&lt;MuiThemeProvider theme={theme}&gt;<br>&lt;div className={classes.root} &gt;<br>&lt;nav className={classes.drawer}&gt;<br>&lt;Hidden smDown implementation=”css”&gt;<br>&lt;Drawer<br> classes={{<br> paper: classes.drawerPaper,<br> }}<br> variant=”permanent”<br> open<br>&gt;<br>…<br>&lt;main className={classes.content}&gt;<br>…<br>&lt;/MuiThemeProvider&gt;<br>&lt;/div&gt;<br>&lt;/div&gt;<br>);</pre><p>Reload the page, now it should be a bit better with a black drawer and a with content, correct icons color and the “Hello” should not be displayed under the drawer anymore.</p><p>But if you switch to mobile display, nothing is working anymore! So let’s add some code to take that into account:</p><h4>Add an appbar when display on small screen</h4><p>First add the appbar that will be hidden when the screen is large enough (don’t forget to add the new components):</p><pre>...<br>&lt;div className={classes.root} &gt;<br>    &lt;Hidden mdUp implementation=&quot;css&quot;&gt;<br>        &lt;AppBar position=&quot;fixed&quot; color=&quot;secondary&quot; className={classes.appBar}&gt;<br>            &lt;Toolbar&gt;<br>                &lt;IconButton<br>                    color=&quot;inherit&quot;<br>                    aria-label=&quot;Open drawer&quot;<br>                    onClick={this.handleDrawerToggle}<br>                    className={classes.menuButton}<br>                &gt;<br>                    &lt;MenuIcon /&gt;<br>                &lt;/IconButton&gt;<br>                &lt;Typography variant=&quot;h6&quot; color=&quot;inherit&quot; className={classes.title}&gt;<br>                    New app<br>            &lt;/Typography&gt;<br>            &lt;/Toolbar&gt;<br>        &lt;/AppBar&gt;<br>    &lt;/Hidden&gt;<br>    &lt;nav className={classes.drawer}&gt;<br>...</pre><p>If you display the page with a mobile screen size, you can see that the appbar is now displayed but that the text is shown under it. To correct this behavior, we need to add a component the size of the appbar only displayed when the screen size is small.</p><p>Add a “tooblar” style:</p><pre>...<br>icon: {<br>   color: &quot;#fefefe&quot;,<br>},<br>toolbar: theme.mixins.toolbar,<br>...</pre><p>And display it:</p><pre>&lt;Hidden mdUp implementation=&quot;css&quot;&gt;&lt;div className={classes.toolbar} /&gt;&lt;/Hidden&gt;</pre><p>Perfect, we can now see the text under the appbar as expected.</p><p>But there is another issue, the text is translated by the drawer size even if no drawer is displayed. We want the main content to fill the whole place and the drawer to be displayed on top of it when toogle. To do so we need to add breakpoint to the drawer styling. Replace the following:</p><pre>drawer: {<br> [theme.breakpoints.up(&#39;md&#39;)]: {<br>     width: drawerWidth,<br>     flexShrink: 0,<br> },<br>},</pre><p>That better. You can try to toogle from a laptop to a mobile screen, the content and the appbar should be displayed correctly.</p><p>Now let’s add the drawer for mobile devices:</p><pre>...<br>&lt;nav className={classes.drawer}&gt;<br> <strong>&lt;Hidden mdUp implementation=&quot;css&quot;&gt;<br>     &lt;Drawer<br>  color=&quot;primary&quot;<br>  className={classes.drawer}<br>  variant=&quot;temporary&quot;<br>  open={mobileOpen}<br>  onClose={this.handleDrawerToggle}<br>  classes={{<br>      paper: classes.drawerPaper,<br>  }}<br>  anchor=&quot;left&quot;<br>     &gt;<br>  {drawer}<br>     &lt;/Drawer&gt;<br> &lt;/Hidden&gt;</strong><br> &lt;Hidden smDown implementation=&quot;css&quot;&gt;<br>...</pre><p>Thsi drawer will be displayed only when the <strong>mobileOpen</strong> variable will be true (this will be a state), and the <strong>handleDrawerToggle </strong>function will toogle this state for us.</p><p>So add this state and the handleDrawerToogle function:</p><pre>class Layout extends Component {<br><strong>state = {<br>   mobileOpen: false,<br>};</strong></pre><pre><strong>handleDrawerToggle = () =&gt; {<br>   this.setState(state =&gt; ({ mobileOpen: !state.mobileOpen }));<br>};</strong></pre><pre>...</pre><pre>const { classes } = this.props;<br><strong>const { mobileOpen } = this.state;</strong></pre><pre>const drawer = (</pre><p>That start to do what we are expecting! If the screen is small, the appbar is display with a menu icon, when this icon is clicked the drawer is displayed and if you click outside of the drawer, it is closed again. You can add a onClick on drawer button to automatically close it when you navigate, but only to close the drawer, like this:</p><pre>&lt;ListItem <strong>onClick={mobileOpen ? this.handleDrawerToggle : null}</strong>&gt;</pre><p>Good, your layout should be pretty functional now. We are done with Layout.js, here is what the full file should looks like (I ll make it available on github as soon as possible):</p><pre>import React, { Component } from &#39;react&#39;;<br>import &#39;./Layout.scss&#39;;<br>import { Box, List, Divider, ListItem, ListItemIcon, ListItemText, Hidden, Drawer, Typography, AppBar, Toolbar, IconButton } from &#39;<a href="http://twitter.com/material">@material</a>-ui/core&#39;;<br>import PersonIcon from &#39;<a href="http://twitter.com/material">@material</a>-ui/icons/Person&#39;;<br>import Help from &#39;<a href="http://twitter.com/material">@material</a>-ui/icons/Help&#39;;<br>import MenuIcon from &#39;<a href="http://twitter.com/material">@material</a>-ui/icons/Menu&#39;;</pre><pre>import { withStyles } from &#39;<a href="http://twitter.com/material">@material</a>-ui/core/styles&#39;;<br>import { MuiThemeProvider, createMuiTheme } from &#39;<a href="http://twitter.com/material">@material</a>-ui/core/styles&#39;;</pre><pre>const drawerWidth = 250;</pre><pre>const theme = createMuiTheme({</pre><pre>palette: {<br>        primary: {<br>            main: &#39;#fefefe&#39;,<br>        },<br>        secondary: {<br>            main: &#39;#3e4f6a&#39;,<br>        },<br>    },<br>});</pre><pre>const styles = theme =&gt; ({<br>    root: {<br>        display: &#39;flex&#39;,<br>    },<br>    drawer: {<br>        [theme.breakpoints.up(&#39;md&#39;)]: {<br>            width: drawerWidth,<br>            flexShrink: 0,<br>        },<br>    },<br>    drawerPaper: {<br>        width: drawerWidth,<br>        backgroundColor: &quot;rgba(23, 37, 42, 1)&quot;,<br>        color: &quot;#fefefe&quot;,<br>        border: &quot;none&quot;,<br>    },<br>    content: {<br>        flexGrow: 1,<br>        minHeight: &quot;100vh&quot;,<br>    },<br>    icon: {<br>        color: &quot;#fefefe&quot;,<br>    },<br>    toolbar: theme.mixins.toolbar,<br>});</pre><pre>class Layout extends Component {<br>    state = {<br>        mobileOpen: false,<br>    };</pre><pre>handleDrawerToggle = () =&gt; {<br>        this.setState(state =&gt; ({ mobileOpen: !state.mobileOpen }));<br>    };<br>    render() {<br>        const { classes } = this.props;<br>        const { mobileOpen } = this.state;</pre><pre>const drawer = (<br>            &lt;div id=&quot;drawer-container&quot;&gt;<br>                &lt;div className=&quot;logo-drawer&quot; /&gt;<br>                &lt;List&gt;<br>                    &lt;ListItem onClick={mobileOpen ? this.handleDrawerToggle : null}&gt;<br>                        &lt;ListItemIcon&gt;<br>                            &lt;Help className={classes.icon} /&gt;<br>                        &lt;/ListItemIcon&gt;<br>                        &lt;ListItemText primary=&quot;About&quot; /&gt;<br>                    &lt;/ListItem&gt;<br>                    &lt;Divider /&gt;<br>                    &lt;ListItem onClick={mobileOpen ? this.handleDrawerToggle : null}&gt;<br>                        &lt;ListItemIcon&gt;<br>                            &lt;PersonIcon className={classes.icon} /&gt;<br>                        &lt;/ListItemIcon&gt;<br>                        &lt;ListItemText primary=&quot;Log in&quot; /&gt;<br>                    &lt;/ListItem&gt;<br>                &lt;/List&gt;<br>            &lt;/div&gt;<br>        );<br>        return (<br>            &lt;div&gt;<br>                &lt;div id=&quot;main-background&quot; /&gt;<br>                &lt;div id=&quot;main-layout&quot;&gt;<br>                    &lt;MuiThemeProvider theme={theme}&gt;<br>                        &lt;div className={classes.root} &gt;<br>                            &lt;Hidden mdUp implementation=&quot;css&quot;&gt;<br>                                &lt;AppBar position=&quot;fixed&quot; color=&quot;secondary&quot;&gt;<br>                                    &lt;Toolbar&gt;<br>                                        &lt;IconButton<br>                                            color=&quot;inherit&quot;<br>                                            aria-label=&quot;Open drawer&quot;<br>                                            onClick={this.handleDrawerToggle}<br>                                            className={classes.menuButton}<br>                                        &gt;<br>                                            &lt;MenuIcon /&gt;<br>                                        &lt;/IconButton&gt;<br>                                        &lt;Typography variant=&quot;h6&quot; color=&quot;inherit&quot; className={classes.title}&gt;<br>                                            New app<br>                                    &lt;/Typography&gt;<br>                                    &lt;/Toolbar&gt;<br>                                &lt;/AppBar&gt;<br>                            &lt;/Hidden&gt;<br>                            &lt;nav className={classes.drawer}&gt;<br>                                &lt;Hidden mdUp implementation=&quot;css&quot;&gt;<br>                                    &lt;Drawer<br>                                        color=&quot;primary&quot;<br>                                        className={classes.drawer}<br>                                        variant=&quot;temporary&quot;<br>                                        open={mobileOpen}<br>                                        onClose={this.handleDrawerToggle}<br>                                        classes={{<br>                                            paper: classes.drawerPaper,<br>                                        }}<br>                                        anchor=&quot;left&quot;<br>                                    &gt;<br>                                        {drawer}<br>                                    &lt;/Drawer&gt;<br>                                &lt;/Hidden&gt;<br>                                &lt;Hidden smDown implementation=&quot;css&quot;&gt;<br>                                    &lt;Drawer<br>                                        classes={{<br>                                            paper: classes.drawerPaper,<br>                                        }}<br>                                        variant=&quot;permanent&quot;<br>                                        open<br>                                    &gt;<br>                                        {drawer}<br>                                    &lt;/Drawer&gt;<br>                                &lt;/Hidden&gt;<br>                            &lt;/nav&gt;<br>                            &lt;main className={classes.content}&gt;<br>                                &lt;Hidden mdUp implementation=&quot;css&quot;&gt;&lt;div className={classes.toolbar} /&gt;&lt;/Hidden&gt;<br>                                &lt;Box width=&quot;100%&quot; className=&quot;mainContent&quot;&gt;&lt;Typography variant=&#39;h1&#39;&gt;Hello&lt;/Typography&gt;&lt;/Box&gt;<br>                            &lt;/main&gt;<br>                        &lt;/div&gt;<br>                    &lt;/MuiThemeProvider&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        );<br>    }<br>}</pre><pre>export default withStyles(styles)(Layout)</pre><p>Let’s simply complete a bit our styling using our Layout.scss file to add a background and a logo. It is pretty classical css so I am not going to explain it in deep details:</p><pre>#main-background {<br>  display: block;<br>  position: fixed;<br>  left: 0;<br>  top: 0;<br>  width: 100%;<br>  height: 100%;<br>  z-index: -100;<br>  background: url(https://medium.com/assets/img/background.jpg) no-repeat center center;<br>  -webkit-background-size: cover;<br>  -moz-background-size: cover;<br>  -o-background-size: cover;<br>  background-size: cover;<br>}</pre><pre>#main-layout {<br>  .mainContent {<br>    margin: 0;<br>    padding: 0;<br>    margin-top: 3em;<br>    margin-bottom: 3em;<br>  }<br>}<br>#drawer-container {<br>  padding-top: 1em;<br>  .logo-drawer {<br>    width: 100%;<br>    height: 250px;<br>    margin-bottom: 2em;</pre><pre>background: url(https://medium.com/assets/img/logo.png) no-repeat center center;<br>    -webkit-background-size: cover;<br>    -moz-background-size: cover;<br>    -o-background-size: cover;<br>    background-size: cover;<br>  }<br>}</pre><p>You are done! The result should be now pretty closed from what we defined at the beginning 😊 The next step will be <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/add-react-router-dom-to-a-reactjs-with-material-ui-project-part-4-f8d7e02f041a">to add React-Router-Dom to navigate between pages</a>, follow if you want to be informed when it comes out!</p><p>If you like this series or this tutorial and would like to support my work, you can <a href="https://www.buymeacoffee.com/ZYwAO7g">buy me a coffee</a> 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b91b442a2230" width="1" height="1" alt=""><hr><p><a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/make-a-beautiful-and-mobile-friendly-vertical-navigation-with-reactjs-and-material-ui-part-3-b91b442a2230">Make a beautiful and mobile friendly vertical navigation with ReactJs and Material UI (Part 3)</a> was originally published in <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app">Develop and deploy a complex serverless web app using AWS, ReactJs and AI (Rekognition)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Initialize a ReactJs + Git + Amplify project with test and prod backend environment (Part 2)]]></title>
            <link>https://medium.com/develop-and-deploy-a-complex-serverless-web-app/initialize-a-reactjs-git-amplify-project-with-test-and-prod-backend-environment-part-2-de2a285fa268?source=rss-fab552672798------2</link>
            <guid isPermaLink="false">https://medium.com/p/de2a285fa268</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[amplify]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Yann]]></dc:creator>
            <pubDate>Thu, 19 Mar 2020 15:02:34 GMT</pubDate>
            <atom:updated>2020-03-20T13:55:14.102Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kD-O3-wSxOzPMvOYupwjzw.png" /><figcaption>Photo by <a href="https://unsplash.com/@pericakalimerica?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Pero Kalimero</a> on <a href="https://unsplash.com/s/photos/cloud?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>It is now time to get to work and start our new application. This story is part of a <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app">series on how to build and deploy a complex cloud based application using Amplify.</a></p><h3>Start a new ReactJs application</h3><p>You first need to have <a href="https://nodejs.org/en/">node</a> and <a href="https://www.npmjs.com/">npm</a> install on your machine. This will let you run your code locally and manage your packages.</p><p>If you don’t have them, both will be installed while installing node (<a href="https://nodejs.org/en/download/">here</a>). After it is done you will be able to run:</p><pre>node -v</pre><p>and</p><pre>npm -v</pre><p>to obtain your current node and npm version. At the time I am writing those lines, I am using npm 6.13.7 and node 12.14.1.</p><p>Once it is done, create your <a href="https://reactjs.org/">react</a> app using the very practical <a href="https://create-react-app.dev/docs/getting-started/">create-react-app</a>, I ll use recognimage as project name but you can name it as you want:</p><pre>npx create-react-app recognimage</pre><pre>cd recognimage</pre><pre>npm start</pre><p>Congrats, your new app is now running locally and should automatically be launched at “<a href="http://localhost:3000/">http://localhost:3000/</a>”. But obviously it is not a super useful app for now, we ll get to it.</p><h3>Install Amplify</h3><p>From <a href="https://aws.amazon.com/amplify/">AWS website</a>:</p><blockquote>AWS Amplify is a development platform for building secure, scalable mobile and web applications. It makes it easy for you to authenticate users, securely store data and user metadata, authorize selective access to data, integrate machine learning, analyze application metrics, and execute server-side code.</blockquote><p>To say it another way, Amplify will help you develop and deploy your app by taking care of your API, your Authentication or your Db. Instead of creating and managing each AWS services independently, you can do everything in one place while developing your frontend, a huge time saver!</p><p>To follow from here, you’ll need an AWS account. You’ll pay only for the services you consume and you can expect the following tutorial to use so few resources that it should be free. Go <a href="https://portal.aws.amazon.com/billing/signup?#/start">there</a> to create your account if you don’t have one.</p><p>Once it is done you can install and configure amplify client:</p><pre>npm install -g @aws-amplify/cli<br>amplify configure</pre><p>Amplify provides a complete <a href="https://aws-amplify.github.io/docs/">walkthrough</a> video for the configuration. Basically here what will happened:</p><ol><li>You will need to log in to the console</li><li>Specify the region you want to use for you project</li><li>Set the name of the programmatic IAM user that Amplify will use to interact with your resources</li><li>Accept everything and copy your accessKeyId and secretAccessKey to the console</li><li>If you want, you can save this credential as profile so you can use the same IAM user for you next project</li></ol><p>Perfect, your amplify client is now ready.</p><h3>Create git and amplify environment</h3><p>It is always good to try to keep things clean. So keeping your development environment away from your production environment should be done even for a small project. Here I ll show you how to initialize a project with two git branches and two distinct backends, one for the development and one for the production.</p><p>From now on you ll need to have git. If you are not familiar with git, you <a href="https://git-scm.com/">should start by reading a bit about it</a> as it is the most used version control system used out there. To install it (ubuntu), run:</p><pre>sudo apt update<br>sudo apt install git</pre><p>Navigate to your project root if you are not already there, initialize your repository and push it to your favorite tool, I personally use BitBucket but you can use github, gitlab or any other, this will not change anything for the rest of the tutorial. You should have something like that to do to push it online:</p><pre>git remote add origin <a href="https://dzolo38@bitbucket.org/dzolo38/test.git">https://****@bitbucket.org/*****.git</a><br>git push -u origin master</pre><p>Now you have a master branch initialized, let’s set up our master backend with amplify:</p><pre>amplify init</pre><p>Answer the few question and name your environment “master”, a new “amplify” folder should be created. This folder contains all the information about your backend, for now it is probably not super interesting but it will be populated after adding an api/function/auth and so on.</p><p>Push the new generated code to master</p><pre>git add .<br>git commit -m &quot;Initialize amplify master&quot;<br>git push</pre><p>Perfect, now you can create another branch call “dev” and initialize amplify in it with “dev” as environment name:</p><pre>git checkout -b dev<br>amplify init</pre><p>You are done! Now we will work from the development environment, and whenever we want to push it to the master one we will simply run:</p><pre>git chekout master<br>amplify env checkout master<br>git merge dev<br>amplify push</pre><p>Doing so all your development and environment update will be merge and push to your master.</p><p>Ok I think that’s it for this first part, we now have everything setup to work with a clean workflow and separated environment!</p><p>I hope you enjoyed it, next we will start to add some code to our app by making <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/make-a-beautiful-and-mobile-friendly-vertical-navigation-with-reactjs-and-material-ui-part-3-b91b442a2230">a nice and mobile friendly navigation drawer</a> :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de2a285fa268" width="1" height="1" alt=""><hr><p><a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/initialize-a-reactjs-git-amplify-project-with-test-and-prod-backend-environment-part-2-de2a285fa268">Initialize a ReactJs + Git + Amplify project with test and prod backend environment (Part 2)</a> was originally published in <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app">Develop and deploy a complex serverless web app using AWS, ReactJs and AI (Rekognition)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Develop AI web apps (AWS, ReactJs): Define the project (part 1)]]></title>
            <link>https://medium.com/develop-and-deploy-a-complex-serverless-web-app/develop-ai-web-apps-aws-reactjs-define-the-project-part-1-5aa14db8fa97?source=rss-fab552672798------2</link>
            <guid isPermaLink="false">https://medium.com/p/5aa14db8fa97</guid>
            <category><![CDATA[rekognition]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[amplify]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Yann]]></dc:creator>
            <pubDate>Thu, 19 Mar 2020 11:18:34 GMT</pubDate>
            <atom:updated>2020-06-26T15:57:54.403Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kD-O3-wSxOzPMvOYupwjzw.png" /><figcaption>Photo by <a href="https://unsplash.com/@pericakalimerica?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Pero Kalimero</a> on <a href="https://unsplash.com/s/photos/cloud?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Welcome to this new series where we are going to build a complex artificial intelligence web app. A lot of tutorials provide valuable information on a particular topic, but it is very hard to find one letting you know the full story. The idea here is to let you follow my journey from the idea of an app, through the full development and up to the final deployment. Hope you ll enjoy!</p><h3>Why this app</h3><p>Few weeks ago, I was looking to build an app to learn a bit more about the AWS service “Rekognition”. If you are not familiar with this service you can have a look on their <a href="https://aws.amazon.com/rekognition/">official page</a>, but in a nutshell, this service is supposed to do all the hard work for you when it comes to Artificial intelligence, from text detection to segmentation, so you only have to use a simple API request to obtain state of the art results. Sounds too good to be true right? So now you know why I wanted to try it by myself.</p><h3>What are we building</h3><p>Now that you are familiar with the “why” let’s figure out the “what”. I wanted to build a easy to use interface for sorting and storing running pictures so you easily can find yours based on your bib number.</p><p>Basically the user can:</p><ol><li>Login</li><li>Create a folder</li><li>Add some pictures</li><li>Rekognition finds and analyses all bibs</li><li>All information are store in DynamoDb</li><li>All pictures are store in S3</li><li>With all the data above, a public page is generated allowing anyone to search the pictures to find a certain text</li></ol><p>A payment service will also be needed in order to be able to create more folders for user needing to upload more pictures.</p><h4>Some screenshot</h4><p>It is easier to understand what we are going to build with some screenshot so here there are. But I am building the app while writing this tutorial so it is work in progress:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*78c-n41n_P6euKZ2clFRnQ.png" /><figcaption>Welcome page layout</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*4QBsXhzuJyvo9CBJr429AA.png" /><figcaption>Mobile friendly layout</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aDST1421NDJPWYzUoTifLQ.png" /><figcaption>Login page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*geqlmIVlx2tQzyJS6FD5SQ.png" /><figcaption>List of projects</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*04dTE8RJWA2SA2ixigSoXQ.png" /><figcaption>Here you can upload your pictures</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T4qqtAdwkqBhJ_vrAGPjOw.png" /><figcaption>Once upload you can specify what you are looking for (here is the easy mode but you can use regex)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YMzkvXYAEjpKQ0V3fgceYg.png" /><figcaption>You can test on your album the search option and you have a public link</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PNiUPeHFqL2uytR2LIcPBg.png" /><figcaption>The public link have a minimal layout and don’t need any login</figcaption></figure><p>You can find <a href="https://do93zxpqjd34l.cloudfront.net/">the current result here</a>. The public link a user can share <a href="https://do93zxpqjd34l.cloudfront.net/display/1426961f-b74d-494e-9e09-822e7c1fb871/true/">will look like this</a>. I am developing it while writing the tutorial so keep in mind it is still a work in progress.</p><p>When login, you should be granted a test folder with 100 uploads for free. I would like to let this test folder free but keep in mind I have to pay for it in the end so be reasonable and try just a few pics ;) If you want to support my job, you can either get a premium plan or<a href="https://www.buymeacoffee.com/ZYwAO7g"> buy me a coffee</a> 😃</p><h3>The technologies used</h3><p>To develop this service, I ll be using <a href="https://aws-amplify.github.io/">AWS Amplify</a> to easily setup and deployed our backend (Cognito, Lambda, DynamoDb, CloudFront, ApiGateway). The frontend will use <a href="https://reactjs.org/">ReactJs</a> and <a href="https://material-ui.com/">material ui</a> components so we are not reinventing the wheel on every button. And of course AWS Rekognition for the AI part.</p><p>You may ask why I don’t use Rekognition through Amplify as this option is available. Well I ll explained that in the relevant part, but in a nutshell it is because I don’t want the user to be able to trig Rekognition directly without beckend verification as this service is not really cheap.</p><h3>Prerequisite</h3><p>You can see that I ll be using a lot of AWS services, so you ll need to open an account to follow this series. I am not going through the whole environment setup to have programmatic access to your console, a lot of tutorial exist, you should be fine. I am also considering that you are familiar with ReactJs, npm and AWS services in general.</p><p>Disclaimer: I am not link or paid by Amazon in any way. I use AWS services because it is very convenient but you can try to use this tutorial to your favorite cloud service.</p><h3>All parts</h3><p>To be easier to read and to let you to find specific information if you are not interested in the whole project, this article will be broke down as follow:</p><ol><li>Define the project</li><li><a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/initialize-a-reactjs-git-amplify-project-with-test-and-prod-backend-environment-part-2-de2a285fa268">Initialize a ReactJs + Amplify project with test and prod environment</a></li><li><a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/make-a-beautiful-and-mobile-friendly-vertical-navigation-with-reactjs-and-material-ui-part-3-b91b442a2230">Make a beautiful vertical navigation with ReactJs and Material UI</a></li><li><a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/add-react-router-dom-to-a-reactjs-with-material-ui-project-part-4-f8d7e02f041a">Add React Dom Router to a ReactJs project</a></li><li><a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/add-authentication-to-your-reactjs-project-using-amplify-auth-part-5-aad47ec737e3">Add Authentication to your ReactJs project using Amplify Auth</a></li><li><a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/create-a-logout-button-listening-to-authentication-updates-within-your-aws-amplify-react-82685537bb4a">Add logout button and a authentication listener to your Amplify React application</a></li><li><a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/define-your-model-requirements-and-setup-your-graphql-api-to-dynamodb-with-aws-amplify-part-7-2e627defc318">Define your model requirements and setup your GraphQL API to DynamoDB with AWS Amplify</a></li><li><a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/upload-and-resize-images-to-the-cloud-with-aws-s3-amplify-and-react-part-8-705a7dc49680">Upload and resize images to the cloud with Aws S3, Amplify and React</a></li><li><a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/use-s3-trigger-to-create-a-dynamodb-entry-when-uploading-images-to-s3-part-9-4d7489a4584b">Create a DynamoDb entry when uploading to S3 using Lamba and s3 triggers</a></li><li><a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/add-artificial-intelligence-to-your-react-app-with-aws-rekognition-picture-analysis-part-10-13df0ea14a24">Use AWS Rekognition to extract text from images</a></li><li>Create an beautiful React images gallery with thumbnail and asynchronous updates</li><li>Create a public searchable gallery with ReactJs and Amplify</li><li>Publish and setup your own domain with Cloudfront and Route53</li></ol><p>Bonus to add payment capabilities:</p><ol><li><a href="https://medium.com/dzolo38/https-medium-com-dzolo38-implement-the-new-stripe-checkout-workflow-with-a-react-amplify-project-serverless-78eccaac26e0">Implement the new Stripe checkout workflow within a React Amplify project (serverless and SCA compliant)</a></li><li><a href="https://medium.com/dzolo38/use-stripe-webhook-to-implement-your-business-logic-in-an-amplify-project-serverless-with-aws-f0c1bea52b25">Use Stripe Webhook to implement your business logic in an Amplify project (serverless with AWS Lambda)</a></li></ol><p>Ok that is already a pretty big list but I ll probably change it a bit as things progress. I will try to publish at least once a day and maybe more, so follow to be updated when the next part is around ;)</p><p>Ready? So let’s get to it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5aa14db8fa97" width="1" height="1" alt=""><hr><p><a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app/develop-ai-web-apps-aws-reactjs-define-the-project-part-1-5aa14db8fa97">Develop AI web apps (AWS, ReactJs): Define the project (part 1)</a> was originally published in <a href="https://medium.com/develop-and-deploy-a-complex-serverless-web-app">Develop and deploy a complex serverless web app using AWS, ReactJs and AI (Rekognition)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>