<?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 Sankha Rathnayake on Medium]]></title>
        <description><![CDATA[Stories by Sankha Rathnayake on Medium]]></description>
        <link>https://medium.com/@sankhar?source=rss-543f9aa50458------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aO66l3VDdIBRfVNg5IEjMA.jpeg</url>
            <title>Stories by Sankha Rathnayake on Medium</title>
            <link>https://medium.com/@sankhar?source=rss-543f9aa50458------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:43:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sankhar/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[Dockerizing a Next.js App and Configuring AWS infrastructure with Terraform]]></title>
            <link>https://javascript.plainenglish.io/dockerizing-a-next-js-app-and-configuring-aws-infrastructure-with-terraform-e69127c4e8b7?source=rss-543f9aa50458------2</link>
            <guid isPermaLink="false">https://medium.com/p/e69127c4e8b7</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Sankha Rathnayake]]></dc:creator>
            <pubDate>Fri, 20 Jan 2023 05:16:31 GMT</pubDate>
            <atom:updated>2023-01-20T05:16:31.100Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ooI6Hd8JL3GqgCH2154oXA.png" /><figcaption>Background Photo by <a href="https://unsplash.com/@angeloabear?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Angelo Abear</a> on <a href="https://unsplash.com/backgrounds/colors/red?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In this article, I’ll be talking about how we can dockerize a Next.js app and configure its deployment infrastructure in AWS using Terraform. This would be a continuation of my previous article which was about b<a href="https://medium.com/gitconnected/building-a-next-js-dynamodb-crud-app-4bb2afe0d2f6?source=your_stories_page-------------------------------------">uilding a Next.js DynamoDB CRUD App</a>. You can find the repository related to that project using <a href="https://github.com/sankharr/aws_crud">this link</a>.</p><ul><li>Dockerizing is the process of packing, deploying and running applications using docker containers. Dockerizing an app gives you many advantages such as cost saving, rapid deployment, security, able to deploy into multi-cloud platforms much easily etc.</li><li>We’ll be using a file called dockerfile when dockerizing an app. It’s a text file which contains all the commands that the user would call on the command line to assemble an image. It’s the same file which will be used to build the docker image.</li><li>Terraform is an open-source infrastructure as a code tool that helps you to safely and predictably create, change and improve infrastructure.</li></ul><h4>What is infrastructure as code?</h4><p>Creating, Managing and provisioning the infrastructure using the code is known as Infrastructure as code. It’s much easier to work on infrastructure with this than using manual processes. Terraform supports many platforms such as AWS, Azure, GCP, Kubernetes, Docker, etc.</p><p>Enough with the talks, let’s get on to the real business.</p><h3>Creating the Dockerfile</h3><p>I have prepared this dockerfile based on the concept of <strong>multi-stage builds. </strong>Multi-stage builds is a concept that allows you to break the steps in building a docker image into multiple stages</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6747d2edd46dc8bc7a50d5f2aebe0697/href">https://medium.com/media/6747d2edd46dc8bc7a50d5f2aebe0697/href</a></iframe><p>Let’s talk about some important factors regarding the above code.</p><ul><li>In this multi-stage dockerfile, there are three stages namely deps, builder, and runner. You are free to name these stages with any other words but these are some of the standard words that are in usage.</li><li>We use the alpine version of the node-16 image as the base image for each stage. The alpine version is based on the alpine Linux project. It is much smaller than other versions of the node image, which will help us to reduce the size of the final image to a greater extent</li><li>There can only be one CMD instruction in a docker file. If there are many CMD instructions, the last one would be the one that will get executed</li></ul><p>You may have noticed that we have created a user group and added a user into it in the dockerfile. And then we have set that newly created user as the active user. All that was done to improve the security of the dockerfile.</p><p>Now let’s find out why it&#39;s important to do that.</p><h3>Why it’s needed to improve security for dockerfile?</h3><p>If we don’t explicitly do any changes, docker containers usually run with root privileges. That gives the freedom to install any system packages, edit config file, bind privileged ports etc. Even if it’s useful for the development process, it’s not healthy to keep the containers in that way in a production environment. Because anyone who gets access to the containers will be able to execute malicious processes, commands and do modifications to the code.</p><p>Therefore configuring your containers to run with non-root privileges adds an extra layer of security for the container. It will limit the processes that can be executed and who can execute them.</p><h3>Creating the .dockerignore file</h3><p>The dockerignore file is a text file that contains the names of the files and directories that must be excluded when building a Docker image. This file should be kept in the same directory where the dockerfile is located</p><pre>//.dockerignore<br><br>Dockerfile<br>.dockerignore<br>node_modules<br>npm-debug.log<br>README.md<br>.next<br>.git<br>.env</pre><h3>Building and running the docker image</h3><p>Make sure your Docker Desktop is running before you proceed further.</p><p>You can build the image by running the below command</p><pre>docker build --tag aws_crud .</pre><ul><li>Make sure that you are in the same folder where the Dockerfile is located when you are executing the above command. Otherwise you will have to replace the dot at the end of that above command with the path to the folder where the Dockerfile is located.</li></ul><p>To run the image locally in a container, you need to execute the below command.</p><pre>docker run -p 3000:3000 --name aws_crud_container aws_crud</pre><ul><li>This command will map the container’s port 3000 to our machine’s port 3000. So that we can access the web app that is running in the container using <a href="http://localhost:3000/">http://localhost:3000</a> URL in our browser.</li><li>And also the name of the container is set to aws_crud_container. If we don’t specify a name using — name option, docker will set a random name to the container that will get created.</li></ul><h3>Configuring the AWS infrastructure with Terraform</h3><p>Before that, please make sure that you have installed Terraform on your computer (if not, please follow this <a href="https://developer.hashicorp.com/terraform/downloads">link</a>)</p><p>To authenticate Terraform with AWS, set your access key and secret key as environment variables.</p><pre>export AWS_ACCESS_KEY_ID=your_access_key<br>export AWS_SECRET_ACCESS_KEY=your_secret_key</pre><p>After that, create a folder named terraform and then create a file named main.tf inside that folder.</p><p>Let’s talk about every configuration code segment that we add to this file, one by one.</p><h4>terraform and provider blocks</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe0d9aa1a87aee0e03d9740a3ad7a6df/href">https://medium.com/media/fe0d9aa1a87aee0e03d9740a3ad7a6df/href</a></iframe><ul><li><strong>terraform block</strong> contains the main terraform settings. It let’s you to declare the provider that you are using and its version. If the provider’s version is not mentioned, it will download the latest version available during initialization.</li><li><strong>provider block</strong> lets you to configure the settings related to the provider (In this case AWS) that you will be using. Here we have mentioned the region of the AWS user account that we have configured our AWS CLI with.</li></ul><h4>Creating an ECR Repository</h4><p>Before we run our docker image in AWS, We need to store that image in a remote container registry. That’s when Amazon ECR comes into play. Following code segment will create an ECR repository to store our docker image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8abe5b884a83beff98b34be14a7708de/href">https://medium.com/media/8abe5b884a83beff98b34be14a7708de/href</a></iframe><h4>Creating an ECS Cluster</h4><p>We need to make our docker image run in AWS, in order to access our Next.js app. A docker image will run only in a container that is defined in an ECS task. An ECS service needs to be there to keep an ECS Task running. An ECS Cluster needs to be created to keep an ECS Service running. So from the below piece of code, we’ll be creating that needed ECS Cluster.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7614a3f2e413bf7ecd4f166b0a43f6f/href">https://medium.com/media/f7614a3f2e413bf7ecd4f166b0a43f6f/href</a></iframe><h4>Creating an IAM role to execute tasks</h4><p>We need to create a role to execute tasks on your behalf by making AWS API calls on Amazon ECS and Fargate.</p><ul><li>When we are creating such a role, we need to attach the necessary policies to that role. AmazonECSTaskExecutionRolePolicy is such a managed policy which contains several other policies like “ecr:GetAuthorizationToken”, “ecr:BatchCheckLayerAvailability”, “ecr:GetDownloadUrlForLayer”, “ecr:BatchGetImage”, “logs:CreateLogStream”, “logs:PutLogEvents”. So attaching AmazonECSTaskExecutionRolePolicy to the new role that we are creating is needed (That’s what we have done in the third code segment).</li><li>There’s another policy that we need to add. That is AssumeRole policy of AWS Security Token Service. In order to add such extra policies, we will have to create an IAM policy document. That’s what we have done in the first code segment.</li><li>In the second code segment, We have created the ecsTaskExecutionRole with the policy document that we created earlier</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a39cced2db5ad456757f7cba5c798d03/href">https://medium.com/media/a39cced2db5ad456757f7cba5c798d03/href</a></iframe><h4>Creating the task definition</h4><p>A task definition is a configuration that describes the container(s) that will be running in our ECS Service (We will create this service later in this article).</p><ul><li>We can describe up to ten containers in a single task definition.</li><li>Here we can specify separate memory and CPU values for the task and its containers. When assigning those values to the containers, make sure that the total memory and CPU that you assign to the containers are less than or equal to the memory and CPU values of the task definition.</li><li>We have imported the docker image using the previously configured ECR repository terraform resource.</li><li>The property ‘essential’ decides whether all other containers in this task definition should be running or not, if this container gets failed or gets stopped for some reason.</li><li>Since we are using the value ‘FARGATE’ for requires_compatibilities, The value for network_mode should also be ‘awsvpc’.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f667fd34230c49ff8ea67eeaac56d68/href">https://medium.com/media/5f667fd34230c49ff8ea67eeaac56d68/href</a></iframe><h4>Network Configurations</h4><p>When we configured the network_mode as <strong>awsvpc </strong>in the task definition, we must also use the task networking feature provided by that awsvpc network mode. Refer <a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-networking-awsvpc.html">this doc</a> to get to know about it more.</p><ul><li>This awsvpc network mode simplifies container networking and it increases the security of your containers by letting you to configure the security groups and network monitoring tools.</li><li>When we are running this terraform code, the cluster that we configured previously will get deployed to the default VPC of our user account.</li><li>So we need to make references to that default VPC and the default subnets to connect them with our other resources.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5993f2b1de0b5c41decc307b614e363/href">https://medium.com/media/f5993f2b1de0b5c41decc307b614e363/href</a></iframe><h4>Creating the load balancer</h4><p>We are planning to run our application on the containers hosted in all three default subnets that we referrenced earlier. When our web app is getting the incoming traffic, there should be a mechanism to distribute that traffic among all those containers. That’s when the <strong>Elastic Load Balancing</strong> comes into action.</p><ul><li>When we set load_balancer_type to application, it means that this load balancer will make routing decisions at the application layer (Layer 7 in OSI Model)</li><li>In order to increase the protection for our application, we have added a security group to the load balancer as well (It’s defined in the second code segment).</li><li>Inbound traffic specs of the security group<br>- Allows traffic from port 80<br>- Allows tcp protocol<br>- Allows traffic from all IPv4 addresses</li><li>Outbound traffic specs of the security group<br>- Allows traffic from any port<br>- Allows any outgoing protocols<br>- Allows traffic to all IPv4 addresses</li><li>Refer <a href="https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html#working-with-security-groups">this doc</a> to get to know more about security groups.</li><li>In the third code block, we have created a target group for the load balancer. Its prime task is to route requests to its registered targets. When you meet a rule condition in the listener (which is defined in the last code block here), the traffic is forwarded to the relevant target group. Refer <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-target-groups.html">this doc</a> to get to know more about target groups</li><li>The last code block defines a listener for the load balancer. It’s mandatory to add at least one listener when you start using an application load balancer. It’s a process that checks the requests it receives, and then it directs them to the corresponding target group based on the conditions defined. You can get to know more about listeners by reading <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-listeners.html">this doc</a>.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c0755ac3bdda3d8a42fad30ff2894ca/href">https://medium.com/media/4c0755ac3bdda3d8a42fad30ff2894ca/href</a></iframe><h4>Creating the service</h4><p>Amazon ECS services are something that is capable of running and maintaining a given number of instances of task definition concurrently in an Amazon ECS cluster. So here we have created the service and the security group needed for that service. You can get to know more about Amazon ECS services by referring <a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_services.html">this doc</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f13e3d5ff79bb239b0676314321e8501/href">https://medium.com/media/f13e3d5ff79bb239b0676314321e8501/href</a></iframe><h4>output block</h4><p>This block prints the DNS name of the load balancer to the console. We can use that URL to access the deployed app.</p><pre>output &quot;lb_dns&quot; {<br>  value       = aws_alb.aws-crud-lb.dns_name<br>  description = &quot;AWS load balancer DNS Name&quot;<br>}</pre><p>You can get the final completed terraform file using <a href="https://gist.github.com/sankharr/cf1a9a55ca911693aeeee17c0186cdbf">this link</a></p><h3>Generating the infrastructure based on the terraform file</h3><p>To create the infrastructure on AWS based on the terraform file, The user account that we have configured our AWS CLI with, needs to have the below set of permissions. So please make sure that you have added them to that user before moving forward.</p><pre>AmazonEC2ContainerRegistryFullAccess<br>AmazonECS_FullAccess<br>AmazonEC2FullAccess<br>AmazonECSTaskExecutionRolePolicy<br>IAMFullAccess</pre><p>Sometimes, even if you have added those permissions to the AWS CLI user account, you will still come across permission errors while applying the changes. In such a case, create a new IAM user account with the above policies and configure that account with your AWS CLI to solve the issue.</p><p>After adding those policies, run the below commands to initiate the settings locally and apply the infrastructure changes on AWS.</p><pre>terraform init<br>terraform apply -auto-approve</pre><p>This will automatically do everything based on the terraform file we just created.</p><p>After it completes its execution, log in to your AWS account and go to Elastic Container Registry service and find the repository that has got created there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Y_CTatvPBpImybsAYMfWQ.png" /><figcaption>ECR Repository that has got created</figcaption></figure><p>Click on the repository and get inside it. Then you will find a button named ‘View push commands’. Click that button.</p><p>Then it will open a dialog box like below which contains some instructions about pushing the docker image into the ECR Repository. Follow those instructions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7sES1cW8rFLgvwVAEgrVKQ.png" /><figcaption>Push commands for ECR Repository</figcaption></figure><p>If you have finished running the above commands without any issues, You have successfully finished deploying your Next.js app on ECS.</p><p>Go to the console and check the terraform output. You will be able to see something like the below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*T_HHgXFmxtSoz1NcQMGGHA.png" /></figure><p>The value of lb_dns is the URL that you can use to access your web app. Go to that link and see if the web app is working well.</p><p>It might not work if you open that link as soon as you finish pushing the image to the ECR repository. Because it will take a few minutes to process the image and initiate containers on all subnets. So if you face such an issue, try the same link again in aother few minutes</p><p>Also keep in mind that, when the ECS service is running, you will get billed for the time that it will be using memory and CPU. You can check your AWS bill by opening the AWS billing dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4SLDzPQCrBEwJjzyGCbECQ.png" /><figcaption>AWS charges by service</figcaption></figure><p>Therefore, if you deploy any service (for educational purposes or some other reason) to ECS which is not useful to you, you can remove all those infrastructure changes that you have done by running the below command.</p><pre>terraform destroy -auto-approve</pre><p>And now it’s time to wrap things up. I hope you have found something useful from this. If you have any doubts, please feel free to ask them in the comments section. Thank you for reading!</p><p>Here’s the link to the repository that is related to this article</p><p><a href="https://github.com/sankharr/aws_crud_docker">GitHub - sankharr/aws_crud_docker</a></p><h3>Resources</h3><ul><li><a href="https://docs.bitnami.com/tutorials/why-non-root-containers-are-important-for-security">Why non-root containers are important for security</a></li><li><a href="https://docs.docker.com/engine/security/">Security</a></li><li><a href="https://docs.docker.com/engine/reference/builder/">Dockerfile reference</a></li><li><a href="https://developer.hashicorp.com/terraform/language">Overview - Configuration Language | Terraform | HashiCorp Developer</a></li><li><a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-networking-awsvpc.html">Allocate a network interface for an Amazon ECS task</a></li><li><a href="https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html#working-with-security-groups">Control traffic to resources using security groups</a></li><li><a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_services.html">Amazon ECS services</a></li></ul><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><p><strong><em>Interested in scaling your software startup</em></strong><em>? Check out </em><a href="https://circuit.ooo/?utm=publication-post-cta"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e69127c4e8b7" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/dockerizing-a-next-js-app-and-configuring-aws-infrastructure-with-terraform-e69127c4e8b7">Dockerizing a Next.js App and Configuring AWS infrastructure with Terraform</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Next.js DynamoDB CRUD App]]></title>
            <link>https://levelup.gitconnected.com/building-a-next-js-dynamodb-crud-app-4bb2afe0d2f6?source=rss-543f9aa50458------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bb2afe0d2f6</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Sankha Rathnayake]]></dc:creator>
            <pubDate>Tue, 03 Jan 2023 13:44:09 GMT</pubDate>
            <atom:updated>2023-09-15T03:37:59.064Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JUbf1fCxvuJxiBlvgk8VuA.png" /><figcaption>Background Photo by <a href="https://unsplash.com/es/@alejandroortiz?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Alejandro Ortiz</a> on <a href="https://unsplash.com/backgrounds/art/abstract?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Next.js is an open-source javascript framework that facilitates to build React based applications with server-side rendering. DynamoDB is a NoSQL database service that is provided by AWS. In this article, we’ll be talking about how we can build a simple CRUD app using these two.</p><p>So let’s get things started. In case you already have an IAM user account, you can skip reading the below topic. But you need to make sure that you have already added ‘<strong>AmazonDynamoDBFullAccess</strong>” policy to the permissions of the IAM user that you are currently using.</p><h3>Creating a user in AWS IAM with permission to access DynamoDB</h3><ol><li>First, you need to log into your AWS account as a root user. If you don’t have an AWS account, follow <a href="https://aws.amazon.com/premiumsupport/knowledge-center/create-and-activate-aws-account/">this guide</a> to create an account.</li><li>Search for ‘IAM’ in the top search bar in Console Home. Click on IAM from the search results.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pzNUHUOeEZEIWTtXkzIl6w.png" /></figure><p>3. Click on ‘Users’ in Left Pane. Thereafter, click on the ‘Add Users’ button</p><p>4. Give a user name and the access type as ‘Programmatic Access’. After that, Click on ‘Next: Permissions’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7sX5IIYf967jAUYh33POiw.png" /></figure><p>5. Click on ‘Attach existing policies directly’ and then type ‘dynamo’ in the search bar. Check ‘AmazonDynamoDBFullAccess” policy.</p><p>7. Click “Next: Tags”. In tags section, you can add details (Email address, Job title etc.) related to the user as key-value pairs. After adding tags, Click ‘Next: Review’.</p><p>8. Review the configurations. Mine looks like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*l-boudNs9piKphJ1qqpbiw.png" /></figure><p>9. Once you are done with reviewing, Click ‘Create User’.</p><p>10. Copy the Access key ID and Secret access key value and paste it to a safe location.</p><p>11. To communicate with your AWS account via the terminal of your computer, you need to install AWS CLI on your computer. Follow <a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">this guide</a> to get it done.</p><h3>Configuring your computer with AWS Credentials</h3><ol><li>After installing AWS CLI in your machine, you need to open a new terminal and type aws configure to set up your machine with access to your AWS account.</li><li>The below guide is taken from AWS docs. You can follow that to complete the configuration.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bglxuJKOWI2qehgcVchtBg.png" /></figure><h3>Setting Up Next.js Project</h3><p>Now let’s get into the section that we truly love. That is, CODING!!</p><ol><li>Open the terminal and run npx create-next-app@latest command and provide answers to the questions as in the below screenshot.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*htcQBrFzVRwddjT0wlFN1A.png" /></figure><p>2. Install below AWS SDK dependencies. These libraries will contain the functions that will help us to do CRUD operations</p><p>npm i @aws-sdk/client-dynamodb</p><p>npm i @aws-sdk/lib-dynamodb</p><p>3. We’ll be using tailwind css for styling. So please follow <a href="https://tailwindcss.com/docs/guides/nextjs">this guide</a> to configure it for your project. Tailwind CSS is a framework that is based on <a href="https://css-tricks.com/lets-define-exactly-atomic-css/">atomic css</a> concept</p><p>4. Now let’s store the AWS credentials in the project. Create a file named .env (place it along with package.json), and mention below two lines in that file.</p><pre>NEXT_PUBLIC_AWS_ACCESS_KEY_ID=&quot;Your-access-key&quot;<br>NEXT_PUBLIC_AWS_SECRET_ACCESS_KEY=&quot;Your-secret-key&quot;</pre><p>5. Assign your AWS user’s access key into NEXT_PUBLIC_AWS_ACCESS_KEY_ID and secret key into NEXT_PUBLIC_AWS_SECRET_ACCESS_KEY. It’s important to have<em> </em><strong><em>NEXT_PUBLIC_</em></strong><em> </em>part at the beginning of each environment variable to make it accessible from the js files that we’ll create later in the project.<br>(<strong><em>Please note that exposing AWS credentials to the browser (client-side) like this is not recommended for production-grade websites. I have done that here only to simplify the process</em></strong>)</p><p>6. Create a folder named ‘config’ at the root of the project (along with package.json file). Create a file named dbconfig.js inside that folder and paste below code into that file.</p><pre>// Create service client module using ES6 syntax.<br>import { DynamoDBClient } from &quot;@aws-sdk/client-dynamodb&quot;;<br><br>// Set the AWS Region.<br>const REGION = &quot;us-east-1&quot;; //e.g. &quot;us-east-1&quot;<br>// Create an Amazon DynamoDB service client object.<br><br>const ddbClient = new DynamoDBClient({<br>  region: REGION,<br>  credentials: {<br>    accessKeyId: process.env.NEXT_PUBLIC_AWS_ACCESS_KEY_ID,<br>    secretAccessKey: process.env.NEXT_PUBLIC_AWS_SECRET_ACCESS_KEY,<br>  },<br>});<br><br>export { ddbClient };</pre><p>This dbconfig.js file will create a dynmodbclient with our credentials. So that we can use this client to access our dynamodb in AWS and do the needed operations (Create table, CRUD operations etc.)</p><p>7. Create a file named ‘ddbDocClient.js’ inside the same folder and paste below code into that file.</p><ul><li>This file will configure the marshalling and unmarshalling options.</li><li>Here marshalling means converting the javascript values to DynamoDB attribute values based on a defined schema. unmarshalling means doing it the other way around.</li></ul><pre><br>// Create a service client module using ES6 syntax.<br>import { DynamoDBDocumentClient } from &quot;@aws-sdk/lib-dynamodb&quot;;<br>import { ddbClient } from &quot;./dbconfig.js&quot;;<br><br>const marshallOptions = {<br>  // Whether to automatically convert empty strings, blobs, and sets to `null`.<br>  convertEmptyValues: false, // false, by default.<br>  // Whether to remove undefined values while marshalling.<br>  removeUndefinedValues: true, // false, by default.<br>  // Whether to convert typeof object to map attribute.<br>  convertClassInstanceToMap: false, // false, by default.<br>};<br><br>const unmarshallOptions = {<br>  // Whether to return numbers as a string instead of converting them to native JavaScript numbers.<br>  wrapNumbers: false, // false, by default.<br>};<br><br>// Create the DynamoDB document client.<br>const ddbDocClient = DynamoDBDocumentClient.from(ddbClient, {<br>  marshallOptions,<br>  unmarshallOptions,<br>});<br><br>export { ddbDocClient };<br><br></pre><h3>Creating a table programmatically in DynamoDB</h3><p>Create a file named ‘createTable.js’ in ‘pages’ folder and paste the below code into that file.</p><pre>// Import required AWS SDK clients and commands for Node.js<br>import { CreateTableCommand } from &quot;@aws-sdk/client-dynamodb&quot;;<br>import { ddbClient } from &quot;../config/dbconfig&quot;;<br><br>// Set the parameters<br>export const params = {<br>  // Add the partionkey and sort key(if needed) together with their types<br>  AttributeDefinitions: [<br>    {<br>      AttributeName: &quot;id&quot;, //Primary Key name<br>      AttributeType: &quot;N&quot;, //Type of the primary key<br>    },<br>    {<br>      AttributeName: &quot;dateAdded&quot;, //Sort key name<br>      AttributeType: &quot;S&quot;, //Type of the sort key<br>    },<br>  ],<br>  // Declaring which one is primary key and which one is sort key out of above defined attributes.<br>  // For Primary key -&gt; KeyType = HASH<br>  // For Sort key -&gt; KeyType = RANGE<br>  KeySchema: [<br>    {<br>      AttributeName: &quot;id&quot;, //Primary key name<br>      KeyType: &quot;HASH&quot;,<br>    },<br>    {<br>      AttributeName: &quot;dateAdded&quot;, //Sort key name<br>      KeyType: &quot;RANGE&quot;,<br>    },<br>  ],<br>  ProvisionedThroughput: {<br>    ReadCapacityUnits: 5,<br>    WriteCapacityUnits: 5,<br>  },<br>  TableName: &quot;Users&quot;, //TABLE_NAME<br>  StreamSpecification: {<br>    StreamEnabled: true,<br>    StreamViewType: &quot;KEYS_ONLY&quot;,<br>  },<br>};<br><br>const CreateTable = () =&gt; {<br>  const run = async () =&gt; {<br>    try {<br>      const data = await ddbClient.send(new CreateTableCommand(params));<br>      console.log(&quot;Table Created&quot;, data);<br>      alert(&quot;Table Created!&quot;)<br>      return data;<br>    } catch (err) {<br>      console.log(err);<br>    }<br>  };<br><br>  return (<br>    &lt;div className=&quot;flex flex-col justify-center items-center h-screen&quot;&gt;<br>      &lt;button<br>        className=&quot;px-6<br>    py-2.5<br>    bg-blue-600<br>    text-white<br>    font-medium<br>    text-xs<br>    leading-tight<br>    uppercase<br>    rounded<br>    shadow-md<br>    hover:bg-blue-700 hover:shadow-lg<br>    focus:bg-blue-700 focus:shadow-lg focus:outline-none focus:ring-0<br>    active:bg-blue-800 active:shadow-lg<br>    transition<br>    duration-150<br>    ease-in-out&quot;<br>        onClick={() =&gt; run()}<br>      &gt;<br>        Create Table<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default CreateTable;</pre><ul><li>There are two modes to process reads and writes capacity on DynamoDB tables. They are On-demand and Provisioned. So I will be using Provisioned mode which is eligible for free-tier. So in provisioned mode, we need to specify the number of reads and writes per second that we need for our application. That’s what we have done using ReadCapacityUnits and WriteCapacityUnits To learn more about both of these modes, please refer to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadWriteCapacityMode.html">this guide</a>.</li><li>DynamoDB Streams capture the changes that have been done to the items in the tables. It maintains this information in a log for up to 24 hours. We have enabled this feature by configuring StreamSpecification section in the above code. You can learn more about this by following <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html">this guide</a></li></ul><h3>Inserting Data into DynamoDB table</h3><p>Create a file named ‘adddata.js’ in ‘pages’ folder and paste the below code into that file.</p><p>In this small project, I will be creating a simple user data browser. Each item (record) in ‘Users’ table will have these attributes - id, dateAdded, dateModified, firstName, lastName, city, phoneNumber,</p><pre>import { PutCommand } from &quot;@aws-sdk/lib-dynamodb&quot;;<br>import { ddbDocClient } from &quot;../config/ddbDocClient&quot;;<br>import { useRouter } from &quot;next/router&quot;;<br><br>const styles = {<br>  inputField:<br>    &quot;form-control block w-full px-3 py-1.5 text-base font-normal text-gray-700 bg-white bg-clip-padding border border-solid border-gray-300 rounded transition ease-in-out m-0 focus:text-gray-700 focus:bg-white focus:border-blue-600 focus:outline-none&quot;,<br>};<br><br>const AddData = () =&gt; {<br>  const router = useRouter();<br><br>  const handleSubmit = async (event) =&gt; {<br>    // Stop the form from submitting and refreshing the page.<br>    event.preventDefault();<br><br>    // Get data from the form.<br>    const params = {<br>      TableName: &quot;Users&quot;,<br>      Item: {<br>        id: Math.floor(Math.random() * 10000),<br>        dateAdded: new Date().toLocaleString(),<br>        dateModified: &quot;&quot;,<br>        firstName: event.target.firstName.value,<br>        lastName: event.target.lastName.value,<br>        city: event.target.city.value,<br>        phoneNumber: event.target.phoneNumber.value,<br>      },<br>    };<br><br>    try {<br>      const data = await ddbDocClient.send(new PutCommand(params));<br>      console.log(&quot;Success - item added&quot;, data);<br>      alert(&quot;Data Added Successfully&quot;);<br>      router.push(&quot;/viewdata&quot;);<br>      document.getElementById(&quot;addData-form&quot;).reset();<br>    } catch (err) {<br>      console.log(&quot;Error&quot;, err.stack);<br>    }<br>  };<br>  return (<br>    &lt;&gt;<br>      &lt;div className=&quot;flex flex-col justify-center items-center h-screen&quot;&gt;<br>        &lt;p className=&quot;text-3xl mb-20&quot;&gt;Add Data&lt;/p&gt;<br>        &lt;div className=&quot;block p-6 rounded-lg shadow-lg bg-white w-1/3 justify-self-center&quot;&gt;<br>          &lt;form onSubmit={handleSubmit} id=&quot;addData-form&quot;&gt;<br>            &lt;div className=&quot;form-group mb-6&quot;&gt;<br>              &lt;label<br>                htmlFor=&quot;firstName&quot;<br>                className=&quot;form-label inline-block mb-2 text-gray-700&quot;<br>              &gt;<br>                First Name<br>              &lt;/label&gt;<br>              &lt;input type=&quot;text&quot; className={styles.inputField} id=&quot;firstName&quot; /&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&quot;form-group mb-6&quot;&gt;<br>              &lt;label<br>                htmlFor=&quot;lastName&quot;<br>                className=&quot;form-label inline-block mb-2 text-gray-700&quot;<br>              &gt;<br>                Last Name<br>              &lt;/label&gt;<br>              &lt;input type=&quot;text&quot; className={styles.inputField} id=&quot;lastName&quot; /&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&quot;form-group mb-6&quot;&gt;<br>              &lt;label<br>                htmlFor=&quot;exampleInputEmail1&quot;<br>                className=&quot;form-label inline-block mb-2 text-gray-700&quot;<br>              &gt;<br>                City<br>              &lt;/label&gt;<br>              &lt;input type=&quot;text&quot; className={styles.inputField} id=&quot;city&quot; /&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&quot;form-group mb-6&quot;&gt;<br>              &lt;label<br>                htmlFor=&quot;phoneNumber&quot;<br>                className=&quot;form-label inline-block mb-2 text-gray-700&quot;<br>              &gt;<br>                Phone Number<br>              &lt;/label&gt;<br>              &lt;input<br>                type=&quot;number&quot;<br>                className={styles.inputField}<br>                id=&quot;phoneNumber&quot;<br>              /&gt;<br>            &lt;/div&gt;<br><br>            &lt;button<br>              type=&quot;submit&quot;<br>              className=&quot;<br>    px-6<br>    py-2.5<br>    bg-blue-600<br>    text-white<br>    font-medium<br>    text-xs<br>    leading-tight<br>    uppercase<br>    rounded<br>    shadow-md<br>    hover:bg-blue-700 hover:shadow-lg<br>    focus:bg-blue-700 focus:shadow-lg focus:outline-none focus:ring-0<br>    active:bg-blue-800 active:shadow-lg<br>    transition<br>    duration-150<br>    ease-in-out&quot;<br>            &gt;<br>              Submit<br>            &lt;/button&gt;<br>          &lt;/form&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default AddData;</pre><h3>Reading and deleting data from DynamoDB table</h3><p>Create a file named ‘viewdata.js’ in ‘pages’ folder and paste the below code into that file.</p><pre>// Import required AWS SDK clients and commands for Node.js.<br>import { useEffect, useState } from &quot;react&quot;;<br>import { ddbDocClient } from &quot;../config/ddbDocClient.js&quot;;<br>import { ScanCommand } from &quot;@aws-sdk/lib-dynamodb&quot;;<br>import { DeleteCommand } from &quot;@aws-sdk/lib-dynamodb&quot;;<br>import Link from &quot;next/link.js&quot;;<br><br>const Styles = {<br>  tableHeadings:<br>    &quot;text-sm font-medium text-gray-900 px-6 py-4 text-left border-2&quot;,<br>  tableData: &quot;text-sm text-gray-900 font-light px-6 py-4 whitespace-nowrap&quot;,<br>};<br><br>const ViewData = () =&gt; {<br>  let data = [];<br>  const [tableData, setTableData] = useState([]);<br><br>  //   scanning the dynamodb table<br>  const scanTable = async () =&gt; {<br>    try {<br>      data = await ddbDocClient.send(new ScanCommand({ TableName: &quot;Users&quot; }));<br>      setTableData(data.Items);<br>      console.log(&quot;success&quot;, data.Items);<br>    } catch (err) {<br>      console.log(&quot;Error&quot;, err);<br>    }<br>  };<br><br>  //   deleting an item from the table<br>  const deleteItem = async (primaryKeyValue, sortKeyValue) =&gt; {<br>    try {<br>      await ddbDocClient.send(<br>        new DeleteCommand({<br>          TableName: &quot;Users&quot;,<br>          Key: {<br>            id: primaryKeyValue, // primarykeyName : primaryKeyValue<br>            dateAdded: sortKeyValue, // sortkeyName : sortkeyValue<br>          },<br>        })<br>      );<br>      console.log(&quot;Success - item deleted&quot;);<br>      scanTable();<br>    } catch (err) {<br>      console.log(&quot;Error&quot;, err);<br>    }<br>  };<br><br>  useEffect(() =&gt; {<br>    scanTable();<br>  }, []);<br><br>  return (<br>    &lt;div className=&quot;container mx-auto py-10 flex flex-col w-screen h-screen items-center&quot;&gt;<br>      &lt;div className=&quot;flex w-2/3 justify-end py-4&quot;&gt;<br>        &lt;Link<br>          href={{<br>            pathname: &quot;/adddata&quot;,<br>          }}<br>        &gt;<br>          &lt;button<br>            type=&quot;button&quot;<br>            className=&quot;inline-block px-6 py-2.5 mr-2 bg-blue-600 text-white font-medium text-xs leading-tight uppercase rounded shadow-md hover:bg-blue-700 hover:shadow-lg focus:bg-blue-700 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-blue-800 active:shadow-lg transition duration-150 ease-in-out&quot;<br>          &gt;<br>            Add Data<br>          &lt;/button&gt;<br>        &lt;/Link&gt;<br>      &lt;/div&gt;<br>      &lt;p className=&quot;text-3xl&quot;&gt;View Data&lt;/p&gt;<br>      &lt;div className=&quot;flex flex-col w-2/3 py-10&quot;&gt;<br>        &lt;div className=&quot;overflow-x-auto sm:-mx-6 lg:-mx-8&quot;&gt;<br>          &lt;div className=&quot;py-2 inline-block min-w-full sm:px-6 lg:px-8&quot;&gt;<br>            &lt;div className=&quot;overflow-hidden&quot;&gt;<br>              &lt;table className=&quot;min-w-full&quot;&gt;<br>                &lt;thead className=&quot;border-b&quot;&gt;<br>                  &lt;tr&gt;<br>                    &lt;th scope=&quot;col&quot; className={Styles.tableHeadings}&gt;<br>                      id<br>                    &lt;/th&gt;<br>                    &lt;th scope=&quot;col&quot; className={Styles.tableHeadings}&gt;<br>                      First Name<br>                    &lt;/th&gt;<br>                    &lt;th scope=&quot;col&quot; className={Styles.tableHeadings}&gt;<br>                      Last Name<br>                    &lt;/th&gt;<br>                    &lt;th scope=&quot;col&quot; className={Styles.tableHeadings}&gt;<br>                      City<br>                    &lt;/th&gt;<br>                    &lt;th scope=&quot;col&quot; className={Styles.tableHeadings}&gt;<br>                      Phone Number<br>                    &lt;/th&gt;<br>                    &lt;th<br>                      scope=&quot;col&quot;<br>                      className=&quot;text-sm font-medium text-gray-900 px-6 py-4 text-center border-2&quot;<br>                    &gt;<br>                      Action<br>                    &lt;/th&gt;<br>                  &lt;/tr&gt;<br>                &lt;/thead&gt;<br>                &lt;tbody&gt;<br>                  {tableData.map((item) =&gt; (<br>                    &lt;tr className=&quot;border-b&quot; key={item.id}&gt;<br>                      &lt;td className=&quot;px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900&quot;&gt;<br>                        {item.id}<br>                      &lt;/td&gt;<br>                      &lt;td className={Styles.tableData}&gt;{item.firstName}&lt;/td&gt;<br>                      &lt;td className={Styles.tableData}&gt;{item.lastName}&lt;/td&gt;<br>                      &lt;td className={Styles.tableData}&gt;{item.city}&lt;/td&gt;<br>                      &lt;td className={Styles.tableData}&gt;{item.phoneNumber}&lt;/td&gt;<br>                      &lt;td className=&quot;text-sm text-gray-900 font-light px-6 py-4 whitespace-nowrap text-center&quot;&gt;<br>                        &lt;Link<br>                          href={{<br>                            pathname: &quot;/updatedata&quot;,<br>                            query: {<br>                              id: item.id,<br>                              dateAdded: item.dateAdded,<br>                              firstName: item.firstName,<br>                              lastName: item.lastName,<br>                              city: item.city,<br>                              phoneNumber: item.phoneNumber,<br>                            },<br>                          }}<br>                        &gt;<br>                          &lt;button<br>                            type=&quot;button&quot;<br>                            className=&quot;inline-block px-6 py-2.5 mr-2 bg-blue-600 text-white font-medium text-xs leading-tight uppercase rounded shadow-md hover:bg-blue-700 hover:shadow-lg focus:bg-blue-700 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-blue-800 active:shadow-lg transition duration-150 ease-in-out&quot;<br>                          &gt;<br>                            Edit<br>                          &lt;/button&gt;<br>                        &lt;/Link&gt;<br>                        &lt;button<br>                          type=&quot;button&quot;<br>                          className=&quot;inline-block px-6 py-2.5 bg-red-600 text-white font-medium text-xs leading-tight uppercase rounded shadow-md hover:bg-red-700 hover:shadow-lg focus:bg-red-700 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-red-800 active:shadow-lg transition duration-150 ease-in-out&quot;<br>                          onClick={() =&gt; deleteItem(item.id, item.dateAdded)}<br>                        &gt;<br>                          Delete<br>                        &lt;/button&gt;<br>                      &lt;/td&gt;<br>                    &lt;/tr&gt;<br>                  ))}<br>                &lt;/tbody&gt;<br>              &lt;/table&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ViewData;</pre><h3>Updating Data in DynamoDB table</h3><p>Create a file named ‘updatedata.js’ in ‘pages’ folder and paste the below code into that file.</p><pre>import { ddbDocClient } from &quot;../config/ddbDocClient&quot;;<br>import { useRouter } from &quot;next/router&quot;;<br>import { UpdateCommand } from &quot;@aws-sdk/lib-dynamodb&quot;;<br><br>const styles = {<br>    inputField: &quot;form-control block w-full px-3 py-1.5 text-base font-normal text-gray-700 bg-white bg-clip-padding border border-solid border-gray-300 rounded transition ease-in-out m-0 focus:text-gray-700 focus:bg-white focus:border-blue-600 focus:outline-none&quot;<br>}<br><br><br>const UpdateData = () =&gt; {<br>  const router = useRouter();<br>  const data = router.query;<br>  <br>  const handleSubmit = async (event) =&gt; {<br>    // Stop the form from submitting and refreshing the page.<br>    event.preventDefault();<br><br>    // setting up the parameters for UpdateCommand<br>    const params = {<br>      TableName: &quot;Users&quot;,<br>      Key: {<br>        id: Number(data.id), //primaryKey<br>        dateAdded: data.dateAdded, //sortKey<br>      },<br>      UpdateExpression:<br>        &quot;set firstName = :p, lastName = :r, city = :q, phoneNumber = :z, dateModified = :k&quot;,<br>      ExpressionAttributeValues: {<br>        &quot;:p&quot;: event.target.firstName.value,<br>        &quot;:r&quot;: event.target.lastName.value,<br>        &quot;:q&quot;: event.target.city.value,<br>        &quot;:z&quot;: event.target.phoneNumber.value,<br>        &quot;:k&quot;: new Date().toLocaleString(),<br>      },<br>    };<br><br>    // updating the db<br>    try {<br>      const data = await ddbDocClient.send(new UpdateCommand(params));<br>      console.log(&quot;Success - updated&quot;, data);<br>      alert(&#39;Data Updated Successfully&#39;)<br>      router.push(&#39;/viewdata&#39;)<br>    } catch (err) {<br>      console.log(&quot;Error&quot;, err);<br>    }<br>  };<br>  <br>  return (<br>    &lt;&gt;<br>      &lt;div className=&quot;flex flex-col justify-center items-center h-screen&quot;&gt;<br>        &lt;p className=&quot;text-3xl mb-20&quot;&gt;Update Data&lt;/p&gt;<br>        &lt;div className=&quot;block p-6 rounded-lg shadow-lg bg-white w-1/3 justify-self-center&quot;&gt;<br>          &lt;form onSubmit={handleSubmit} id=&quot;addData-form&quot;&gt;<br>            &lt;div className=&quot;form-group mb-6&quot;&gt;<br>              &lt;label<br>                htmlFor=&quot;firstName&quot;<br>                className=&quot;form-label inline-block mb-2 text-gray-700&quot;<br>              &gt;<br>                First Name<br>              &lt;/label&gt;<br>              &lt;input<br>                type=&quot;text&quot;<br>                className={styles.inputField}<br>                id=&quot;firstName&quot;<br>                name=&quot;firstName&quot;<br>                defaultValue={data.firstName}<br>              /&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&quot;form-group mb-6&quot;&gt;<br>              &lt;label<br>                htmlFor=&quot;lastName&quot;<br>                className=&quot;form-label inline-block mb-2 text-gray-700&quot;<br>              &gt;<br>                Last Name<br>              &lt;/label&gt;<br>              &lt;input<br>                type=&quot;text&quot;<br>                className={styles.inputField}<br>                id=&quot;lastName&quot;<br>                name=&quot;lastName&quot;<br>                defaultValue={data.lastName}<br>              /&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&quot;form-group mb-6&quot;&gt;<br>              &lt;label<br>                htmlFor=&quot;exampleInputEmail1&quot;<br>                className=&quot;form-label inline-block mb-2 text-gray-700&quot;<br>              &gt;<br>                City<br>              &lt;/label&gt;<br>              &lt;input<br>                type=&quot;text&quot;<br>                className={styles.inputField}<br>                id=&quot;city&quot;<br>                name=&quot;city&quot;<br>                defaultValue={data.city}<br>              /&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&quot;form-group mb-6&quot;&gt;<br>              &lt;label<br>                htmlFor=&quot;phoneNumber&quot;<br>                className=&quot;form-label inline-block mb-2 text-gray-700&quot;<br>              &gt;<br>                Phone Number<br>              &lt;/label&gt;<br>              &lt;input<br>                type=&quot;number&quot;<br>                className={styles.inputField}<br>                id=&quot;phoneNumber&quot;<br>                name=&quot;phoneNumber&quot;<br>                defaultValue={data.phoneNumber}<br>              /&gt;<br>            &lt;/div&gt;<br><br>            &lt;button<br>              type=&quot;submit&quot;<br>              className=&quot;<br>    px-6<br>    py-2.5<br>    bg-blue-600<br>    text-white<br>    font-medium<br>    text-xs<br>    leading-tight<br>    uppercase<br>    rounded<br>    shadow-md<br>    hover:bg-blue-700 hover:shadow-lg<br>    focus:bg-blue-700 focus:shadow-lg focus:outline-none focus:ring-0<br>    active:bg-blue-800 active:shadow-lg<br>    transition<br>    duration-150<br>    ease-in-out&quot;<br>            &gt;<br>              Submit<br>            &lt;/button&gt;<br>          &lt;/form&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default UpdateData;</pre><h3>References</h3><ul><li><a href="https://tailwindcss.com/">Tailwind CSS - Rapidly build modern websites without ever leaving your HTML.</a></li><li><a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html">What is Amazon DynamoDB?</a></li><li><a href="https://css-tricks.com/lets-define-exactly-atomic-css/">Let&#39;s Define Exactly What Atomic CSS is | CSS-Tricks</a></li></ul><p>Github Repo for this tutorial — <a href="https://github.com/sankharr/aws_crud">https://github.com/sankharr/aws_crud</a></p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></li></ul><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bb2afe0d2f6" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/building-a-next-js-dynamodb-crud-app-4bb2afe0d2f6">Building a Next.js DynamoDB CRUD App</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pre-rendering in Next.js]]></title>
            <link>https://levelup.gitconnected.com/pre-rendering-in-next-js-90bbfc644cd2?source=rss-543f9aa50458------2</link>
            <guid isPermaLink="false">https://medium.com/p/90bbfc644cd2</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Sankha Rathnayake]]></dc:creator>
            <pubDate>Thu, 22 Dec 2022 03:35:17 GMT</pubDate>
            <atom:updated>2022-12-22T03:35:17.302Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uMrFmA-EqukbJ74ap_HEEQ.png" /><figcaption>Background Image by <a href="https://unsplash.com/@gradienta?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Gradienta</a> on <a href="https://unsplash.com/s/photos/abstract-background?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>What is pre-rendering?</h3><p>Pre-rendering means generating HTML for each page in advance, together with minimal javascript code needed for that page.</p><p>After the page gets loaded into the browser, Javascript code gets executed and makes the page fully interactive. This part of the process is known as <strong>hydration</strong>.</p><h3>Why pre-render?</h3><ol><li>Pre-rendering improves performance</li></ol><ul><li>In a typical react app, you need to wait until the javascript code gets loaded into the browser and gets executed. Because of that, it will take some more time to render the UI</li><li>With a pre-rendered page, the HTML is already generated and loads faster</li></ul><p>2. Pre-rendering helps with SEO</p><ul><li>If you are building a blog or e-commerce site, SEO is a concern.</li><li>If you examine the source code of a web app created using CRA(create-react-app), you will only see a div tag with id equal to root in its body. That’s because its content is getting rendered using client-side rendering. If a search engine hits a such page, the search engine won’t be able to see the content. Because of that, a typical react app created using CRA, is not SEO friendly.</li><li>If the search engine hits a pre-rendered page that is created using Next.js, all the content is present in the source code which will help to index that page.</li></ul><h3><strong>A test to check pre-rendering in an existing website</strong></h3><p>Let’s do a small test to check whether a given website is configured with pre-rendering.</p><ul><li>This page (<a href="https://next-learn-starter.vercel.app/">https://next-learn-starter.vercel.app/</a>) is a web app built using Next.js. Hence, it has pre-rendering. Let’s call it <strong>Shu’s page</strong> from here onwards.</li><li>This page (<a href="https://create-react-template.vercel.app/">https://create-react-template.vercel.app/</a>) is a web app built using Create React App. Which means it&#39;s not configured for pre-rendering. Let’s call it <strong>CRA page</strong> for reference purposes.</li></ul><ol><li>First, visit both of those pages and see if they are working.</li><li>Now you have to disable javascript in your browser. Pick the relevant guide for the browser that you are using, to disable javascript<br><a href="https://developer.chrome.com/docs/devtools/javascript/disable/">Chrome/Brave Guide</a><br><a href="https://www.lifewire.com/disable-javascript-in-firefox-446039">Firefox Guide</a><br><a href="https://www.lifewire.com/disable-javascript-in-safari-4103708">Safari Guide</a></li><li>After disabling javascript, you have to visit those two sites again using the same browser tab (which you disabled javascript) to check whether they are working.<br>You’ll notice that Shu’s page is working fine and the CRA page is showing a message saying that <em>‘You need to enable JavaScript to run this app.’ </em>You are seeing this message because the app is not pre-rendered into static HTML.</li></ol><ul><li>On Shu’s page, a pre-rendered HTML will be displayed during the initial load. After that, the javascript code gets loaded into the browser and then the app becomes interactive (This process is known as <strong>hydration).</strong></li><li>On CRA page, there’s nothing during the initial load because the javascript is not getting loaded during the initial load. Once the browser loads the javascript code, the whole page gets rendered and becomes interactive.</li></ul><h3>Forms of Pre-rendering</h3><p>There are two forms of pre-rendering in Next.js.</p><ol><li>Static Generation</li><li>Server-side rendering</li></ol><p>We can configure a page of a Next.js app to pre-render in either one of these forms. But ‘Static Generation’ is the form that is recommended by Next.js Team.</p><h3>Static Generation</h3><p>A page that uses <em>Static Generation</em> as its pre-rendering form, <strong>generates its HTML during the build time. <br></strong>In production, This process takes place only when you run next build command. But in development mode (when you run npm run dev), pages will get pre-rendered on every request.</p><p>The HTML that gets generated using this process can be <strong>reused on each request</strong> and also it can be cached by a CDN.</p><p>Static Generation will automatically happen when there’s no data that component needs to be fetched from an external source (External API, querying the database etc.)</p><p>But if you have to fetch some data from an external source, you will have to use getStaticProps function to fetch those data.</p><p>Static generation is advised to be used if the data in your page are not getting changed frequently (For example, blog posts, marketing pages, e-commerce product listing, help and documentation, etc.)</p><p>Below is a code of a Next.js component where it fetches a list of users from a free API. Here we have used getStaticProps to fetch data.</p><pre>// pages/sg/index.js<br><br>import styles from &quot;../../styles/Home.module.css&quot;;<br>import Link from &quot;next/link&quot;;<br><br>export default function Component({ users }) {<br>  return (<br>    &lt;&gt;<br>      &lt;main className={styles.main}&gt;<br>        &lt;h1&gt;Static Generation&lt;/h1&gt;<br>        &lt;div className={styles.description}&gt;<br>          &lt;ul&gt;<br>            {users.map((user) =&gt; (<br>              &lt;li key={user.email}&gt;&lt;Link href={`/sg/${user.id}`}&gt;{user.name}&lt;/Link&gt;&lt;/li&gt;<br>            ))}<br>          &lt;/ul&gt;<br>        &lt;/div&gt;<br>      &lt;/main&gt;<br>    &lt;/&gt;<br>  );<br>}<br><br>// this function gets called during the build time<br>export async function getStaticProps() {<br>  // calling an external API to fetch data<br>  const res = await fetch(&quot;https://jsonplaceholder.typicode.com/users&quot;);<br>  const users = await res.json();<br><br>  // this returning data can be accessed from the component using the prop name<br>  return { props: { users } };<br>}</pre><p>Below is the output of that code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*x0aQ28xPQctuemSayIGVRg.png" /><figcaption>Output of Static Generation Code</figcaption></figure><p><a href="https://nextjs.org/docs/basic-features/data-fetching/get-static-props">This guide</a> will give you more information about getStaticProps</p><p>If you want to route to a specific page (which contains more details about that specific user) when you click on a name in that list of users above, you can call getStaticPaths() function from a dynamic page.</p><pre>// pages/sg/[id].js<br><br>import styles from &quot;../../styles/Home.module.css&quot;;<br><br>const Post = ({ user }) =&gt; {<br>  console.log(&quot;user&quot;, user);<br><br>  return (<br>    &lt;&gt;<br>      &lt;main className={styles.main}&gt;<br>        &lt;h1&gt;Static Generation (Paths)&lt;/h1&gt;<br>        &lt;div className={styles.description}&gt;Selected User : {user.name}&lt;/div&gt;<br>      &lt;/main&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>// this function gets called during the build time<br>export async function getStaticPaths() {<br>  // calling an external API to fetch all data<br>  const res = await fetch(&quot;https://jsonplaceholder.typicode.com/users&quot;);<br>  const users = await res.json();<br><br>  const paths = users.map((item) =&gt; ({<br>    params: { id: item.id.toString() },<br>  }));<br><br>  //these paths will get pre-rendered only at build time.<br>  // { fallback: false } means other routes should 404.<br>  return { paths, fallback: false };<br>}<br><br>// This also gets called at build time<br>export async function getStaticProps({ params }) {<br>  // this fetch call has been made only to get the specific data<br>  const res = await fetch(<br>    `https://jsonplaceholder.typicode.com/users/${params.id}`<br>  );<br>  const user = await res.json();<br><br>  return { props: { user } };<br>}<br><br>export default Post;</pre><p>Below is the output of above code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*pb4-W3FhyKl-6LjpVQ59pA.png" /></figure><p>Next.js has advised that you should use getStaticPaths if you are pre-rendering pages that use dynamic routes and if the data is coming from one of the sources from the below list</p><ul><li>headless CMS</li><li>database</li><li>filesystem</li></ul><p>You can learn more about getStaticPaths using <a href="https://nextjs.org/docs/basic-features/data-fetching/get-static-paths">this guide</a>.</p><h3>Server-side rendering</h3><p>A page that uses server-side rendering as its pre-rendering form, <strong>generates HTML on each request.</strong></p><p>If your page shows data that are getting updated frequently, then Server-side rendering is the advised form to be used for pre-rendering. But this would be much slower than the static generation.</p><p>If you need to configure a page in your app for server-side rendering, you have to include getServerSideProps function which will get called by the server on each request.</p><pre>import styles from &quot;../../styles/Home.module.css&quot;;<br><br>export default function Component({ users }) {<br>  return (<br>    &lt;&gt;<br>      &lt;main className={styles.main}&gt;<br>        &lt;h1&gt;Server-side rendering&lt;/h1&gt;<br>        &lt;div className={styles.description}&gt;<br>          &lt;ul&gt;<br>            {users.map((user) =&gt; (<br>              &lt;li key={user.email}&gt;{user.name}&lt;/li&gt;<br>            ))}<br>          &lt;/ul&gt;<br>        &lt;/div&gt;<br>      &lt;/main&gt;<br>    &lt;/&gt;<br>  );<br>}<br><br>// this function gets called on each request<br>export async function getServerSideProps() {<br>  // calling an external API to fetch data<br>  const res = await fetch(&quot;https://jsonplaceholder.typicode.com/users&quot;);<br>  const users = await res.json();<br><br>  // this returning data can be accessed from the component using the prop name<br>  return { props: { users } };<br>}</pre><p>Follow <a href="https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props">this guide</a> to learn more about getServerSideProps</p><h3>References</h3><p>Pre-rendering and Data Fetching (Next.js Learn Guide) — <a href="https://nextjs.org/learn/basics/data-fetching/pre-rendering">https://nextjs.org/learn/basics/data-fetching/pre-rendering</a></p><p>Next.js Docs on Pre-rendering — <a href="https://nextjs.org/docs/basic-features/pages">https://nextjs.org/docs/basic-features/pages</a></p><p>My Github Repo used for this article — <a href="https://github.com/sankharr/next_pre-render">https://github.com/sankharr/next_pre-render</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90bbfc644cd2" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/pre-rendering-in-next-js-90bbfc644cd2">Pre-rendering in Next.js</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Optimize Your React App With Loadable Components]]></title>
            <link>https://sankhar.medium.com/how-to-optimize-your-react-app-with-loadable-components-5c9975bc0e2e?source=rss-543f9aa50458------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c9975bc0e2e</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[loadable-component]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[package]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Sankha Rathnayake]]></dc:creator>
            <pubDate>Sat, 17 Dec 2022 13:09:34 GMT</pubDate>
            <atom:updated>2022-12-17T13:09:34.205Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>How to Optimize Your React App With Loadable Components</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HTGxLgpZGfqMW1UNpBXFyw.png" /><figcaption>Photo by <a href="https://unsplash.com/@fakurian?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Milad Fakurian</a> on <a href="https://unsplash.com/s/photos/abstract-background?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>A good developer is always keen to find, learn and adapt new ways to optimize the app that he/she is working on. ‘Loadable Components’ is such a package that helps you to optimize your react app in numerous ways.</p><p>Let’s find out about its features.</p><h3>Component Splitting</h3><p>This feature allows you to load the components separately that are not necessary to load during the initial load. So that it will help to reduce the initial loading time.<br>It’s not mandatory to provide a fallback UI with this even though it’s something good to have for a better user experience.</p><pre>import { useState } from &quot;react&quot;;<br>import &quot;./App.css&quot;;<br>// import ComponentA from &#39;./components/ComponentA&#39;;<br>import loadable from &quot;@loadable/component&quot;;<br>const ComponentA = loadable(() =&gt; import(&quot;./components/ComponentA&quot;));<br><br>function App() {<br>  const [state, setState] = useState(false);<br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;button onClick={() =&gt; setState(!state)}&gt;Update State&lt;/button&gt;<br>      {state &amp;&amp; &lt;ComponentA fallback={&lt;p&gt;Loading..........&lt;/p&gt;}/&gt;}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>According to the above code, when the user clicks on the button, ComponentA will get rendered into the DOM.<br>The below screenshot was taken during the test that I did <strong>without</strong> using loadable-components (Which means I have uncommented line 3 from the above code and commented lines 4 and 5.)</p><p>In that scenario, ComponentA is also in bundle.jstogether with all other codes. That means the app has used its resources to load ComponentA during the initial rendering of the app, which is not necessary as ComponentA is something that we need only after we click the button to render it. Hence the initial loading time is recorded as 66ms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*Ia9Y8pt8sBe3k9PA8Tnf4A.png" /><figcaption>Without using loadable-components</figcaption></figure><p>The below screenshot was taken during the test that I did while using loadable-components. (Which means I used the previous code exactly as it is). This time the componentA has got loaded as a separate component (src_Components_Com…). So that it has not bothered the initial rendering. Hence the initial loading time of bundle.js has been reduced to 63ms. The size of bundle.js has increased because we had to import loadable-components package (line 4) to make things work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*E-J2P4XSmmOdVFJl9BZy0g.png" /><figcaption>Using loadable</figcaption></figure><h3>Library Splitting</h3><p>This is something new that you won’t get from React library. This will allow you to import the libraries that you need for a specific task only when the need arises. So that it will reduce the load that will be put on the initial rendering of the page. Here also, It’s not mandatory to include the fallback prop.</p><pre>import { useState } from &quot;react&quot;;<br>import &quot;./App.css&quot;;<br>import loadable from &quot;@loadable/component&quot;;<br>const Moment = loadable.lib(() =&gt; import(&quot;moment&quot;));<br><br>function App() {<br>  const [state, setState] = useState(false);<br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;button onClick={() =&gt; setState(!state)}&gt;Update State&lt;/button&gt;<br>      {state &amp;&amp; (<br>        &lt;Moment fallback={&lt;p&gt;Loading..........&lt;/p&gt;}&gt;<br>          {({ default: moment }) =&gt; moment(&quot;2026-02-23&quot;).fromNow()}<br>        &lt;/Moment&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><h3>Full Dynamic Import</h3><p>With the help of this feature, you don’t have to worry about writing an import statement for every component that you need. You just need to pass the file name as a prop to the common component (in this case DynamicComponent) and the rest will be taken care of by loadable-components.</p><pre>import &quot;./App.css&quot;;<br>import loadable from &quot;@loadable/component&quot;;<br><br>const DynamicComponent = loadable((props) =&gt; import(`./components/${props.page}`), {<br>  cacheKey: (props) =&gt; props.page,<br>});<br><br>function App() {<br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;DynamicComponent page=&quot;ComponentA&quot; /&gt;<br>      &lt;DynamicComponent page=&quot;ComponentB&quot; /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><h3>Suspense</h3><p>This feature is not something new to react devs as the same thing can be achieved by using React.lazy. When React.lazy method was introduced back in the day, It didn’t initially support server-side rendering. That issue was solved by this loadable-components. Because of that, the React team itself recommended using this loadable-components in its official documentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*TUdTh2qFG3RsQtCnrMjkwg.png" /><figcaption>‘Loadable Components’ was recommended in React Documentation</figcaption></figure><p>But later on, The react team released React 18 with the support of server-side rendering for suspense. So now they have removed this recommendation from their documentation.</p><pre>import React, { Suspense } from &#39;react&#39;<br>import { lazy } from &#39;@loadable/component&#39;<br>const OtherComponent = lazy(() =&gt; import(&#39;./OtherComponent&#39;))<br>function MyComponent() {<br>  return (<br>    &lt;div&gt;<br>      &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>        &lt;OtherComponent /&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><h3>Prefetching</h3><p>If you want to load a component when the browser is idle (which means that the component is not a high-priority one to be loaded during the initial loading), you can add a ‘magic comment’ (from webpack) inside your import statement.</p><pre>import loadable from &#39;@loadable/component&#39;;<br><br>const ComponentA = loadable(() =&gt;<br>  import(/* webpackPrefetch: true */ &#39;./ComponentA&#39;),<br>)</pre><p>Let’s talk about some specific scenarios that we’ll have to deal while using this library.</p><h3>Handling Errors</h3><p>If a module gets failed to get loaded due to a network failure or any other issue, without rendering a blank page on the app, you can use an error boundary to handle the situation in a nicer way.</p><pre>import ErrorBoundary1 from &#39;./ErrorBoundary1&#39;<br>const ComponentA = loadable(() =&gt; import(&#39;./ComponentA&#39;))<br>const ComponentB = loadable(() =&gt; import(&#39;./ComponentB&#39;))<br>const MyComponent = () =&gt; (<br>  &lt;div&gt;<br>    &lt;ErrorBoundary1&gt;<br>        &lt;ComponentA /&gt;<br>        &lt;ComponentB /&gt;<br>    &lt;/ErrorBoundary1&gt;<br>  &lt;/div&gt;<br>)</pre><h3>Flashing of the Loading Page</h3><p>If the page load is getting done in a much faster way, you might notice that the loading page gets appeared for a few milliseconds and then gone. In some cases, that might not give a good impression to the user. To solve this issue, you can use p-min-delay package to add a small delay for the package loading, allowing the loading screen to appear at least for a second.</p><pre>import { useState } from &quot;react&quot;;<br>import &quot;./App.css&quot;;<br>import loadable from &quot;@loadable/component&quot;;<br>import pMinDelay from &#39;p-min-delay&#39;<br><br><br>const ComponentA = loadable(() =&gt; pMinDelay(import(&quot;./components/ComponentA&quot;), 1000));<br><br>function App() {<br>  const [state, setState] = useState(false);<br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;button onClick={() =&gt; setState(!state)}&gt;Update State&lt;/button&gt;<br>      {state &amp;&amp; &lt;ComponentA fallback={&lt;div&gt;Loading.....&lt;/div&gt;}/&gt;}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><h3>Manually Preloading</h3><p>To forcefully preload a component, you can use preload() method on the component that you imported using loadable.</p><pre>import loadable from &#39;@loadable/component&#39;<br>const ComponentA = loadable(() =&gt; import(&#39;./ComponentA&#39;))<br>function App() {<br>  const [show, setShow] = useState(false)<br>  return (<br>    &lt;div&gt;<br>      &lt;a onMouseOver={() =&gt; ComponentA.preload()} onClick={() =&gt; setShow(true)}&gt;<br>        Show Element<br>      &lt;/a&gt;<br>      {show &amp;&amp; &lt;ComponentA /&gt;}<br>    &lt;/div&gt;<br>  )<br>}</pre><h3>Wrapping it up</h3><p>In this article, we have discussed some important features of Loadable Components package to improve the performance of your react app.</p><p>Component Splitting, Library Splitting, Full Dynamic Import and Suspense are great features to get added in to your project. Use them wisely and make your projects great!</p><p>Thanks for taking the time to read this. I hope this was helpful. If you have any doubts, feel free to leave a response.</p><h3>Resources</h3><p>Loadable Components Docs - <a href="https://loadable-components.com/docs/getting-started/">https://loadable-components.com/docs/getting-started/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c9975bc0e2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Cognito Authentication without using Amplify]]></title>
            <link>https://sankhar.medium.com/aws-cognito-authentication-without-using-amplify-8d0e3af997c2?source=rss-543f9aa50458------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d0e3af997c2</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-cognito]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sankha Rathnayake]]></dc:creator>
            <pubDate>Wed, 07 Dec 2022 13:32:01 GMT</pubDate>
            <atom:updated>2022-12-08T06:55:35.616Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Amazon Cognito Authentication without using Amplify</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2hkvHGmQO-O8SoWyqL08-w.png" /></figure><p>When you want to add authentication service from AWS for your app, you have few ways to do that.<br>1. You can use AWS <a href="https://aws.amazon.com/amplify/">Amplify</a> <br>2. You can use amazon-cognito-identity-js library<br>3. You can use Cognito AWS SDK</p><p>AWS Amplify is a solution which let’s you to integrate your app easily with many other AWS Services. But if you don’t need those other services and you only need to integrate Cognito authentication service with your app, then you have <em>amazon-cognito-identity-js</em> package at your service. One of the main advantages of choosing this package over AWS Amplify is, you will get a reduced bundle size which will positively affect the performance of your app.</p><p>To begin with, Let’s create our react app by running below command.</p><pre>npx create-react-app react-aws</pre><p>After that, let’s run below two commands to install webpack and <em>amazon-cognito-identity-js</em> packages</p><pre>npm install --save-dev webpack-cli<br>npm install --save amazon-cognito-identity-js</pre><p>Since we’ll be using forms inside our react app for authentication purposes, we’ll have to install formik (form library for react ) and yup (for validation).</p><pre>npm install formik –save<br>npm install yup --save</pre><p>Also for state management, styling and routing functionalities, we’ll need redux, sass and react-router-dom packages.</p><pre>npm install @reduxjs/toolkit react-redux sass react-router-dom</pre><p>Now that we have finished installing modules to our react app, let’s focus on setting up the configurations from AWS side.</p><h3>Configuring Amazon Cognito</h3><p>This article is written based on the assumption that you already have an AWS account. If you don’t have an account, please follow the instructions in this <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/aws-cognito-sign-up-aws-account.html">link</a>.</p><p>Through out this step by step guide, if I have not mentioned about a particular configuration option, leave those fields as they are to finish this tutorial successfully. If you have any questions, you are always welcome to ask those in the comment section of this article.</p><ol><li>Log in to <a href="https://console.aws.amazon.com/cognito/home">AWS Cognito Console</a> and choose User Pools.</li><li>Then click on ‘Create user pool’</li><li>Under ‘Cognito user pool sign-in options’ section, select the options that allow your users to get signed in with. For example, If you choose all the options there (Username, email and phone number), you will have to get values for all those options when the user is getting signed up, and then your user can use one of them (Either Username or email or phone number) to log in to your app. For this tutorial, I’ll be using only ‘Email’ option. After selecting your options, Click ‘Next’ button.</li><li>In Password Policy, You can either choose Cognito defaults or Custom mode. I’ll go with Cognito defaults</li><li>Under Multi-factor authentication section, you can choose the recommended method (Require MFA) to enable multi-factor authentication. Since we are building a simple app here, I will go with “No MFA” option. MFA option will be covered in another article in near future.</li><li>For User Account Recovery, I checked ‘Enable self-service account recovery — Recommended’ box and choose ‘Email Only’ as the delivery method for user account recovery messages. Then click on ‘Next’.</li><li>Check ‘Allow Cognito to automatically send messages to verify and confirm — Recommended’ and select ‘Send email message, verify email address’ option</li><li>Under Custom attributes section, add below attribute<br>=================<br>Name — telnum<br>Type — String<br>Mutable — checked<br>=================<br>Click ‘Next’ after adding that attribute.</li><li>As Email Provider, select ‘Send email with Cognito’ option and then click ‘Next’</li><li>Enter a user pool name of your choice. I’ll go with ‘react-test’</li><li>Under ‘Initial app client’, Select App type as ‘Public Client’ and enter an app client name. the name that I entered is ‘react-test_AppClient’</li><li>Select ‘Don’t generate a client secret’ then click next. Review all the settings that you have updated. Below are my settings.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*0khqyTfyFEU3brrVP9gWOA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*bSbLhg0RiyDcC-DBWXT3cQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*64Lk-8l3xO9kxHJqKm8kag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*JtRbuqDl2k8OyWTEVwXsQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*AOK4dFRM351Ol97z3I3R2Q.png" /></figure><p>13. After checking everything, Click on ‘Create user pool’ button.</p><p>14. Sometimes, even if your user pool gets created successfully, the creation of your app client might have got failed (You may receive a red alert at the top of your cognito dashboard, if the app client creation has got failed). In such scenarios, you will have to create the app client again. Let’s see how you can do that. If you didn’t receive such alert, you can skip to step 19. Click on the name of the user pool that you created from the list of user pools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MrGzAFRHS-A5pBrz37kHEw.png" /><figcaption>List of User Pools</figcaption></figure><p>15. Switch to ‘App Integration’ tab and scroll to the bottom until you find ‘App client list’ section</p><p>16. Click on ‘Create App Client’ button there.</p><p>17. Select App type as ‘Public Client’ and enter an app client name. the name that I entered is ‘react-testAppClient’</p><p>18. Select ‘Don’t generate a client secret’ then click ‘Create app client’.</p><p>19. (If you have skipped from step 14 to here, please click and open the user pool that you created from the list of user pools before starting this step.)<br>Let’s add a domain to our user pool. In ‘App Integration’ tab. Under Domain Section, Click on ‘Action’ button, and then select ‘Create Cognito domain’ from the list.</p><p>20. Enter a domain prefix of your choice. You cannot enter a phrase which includes either aws or amazon or cognito words. So I decide to put ‘react-test1’ there. If the prefix that you choose is acceptable, you will see a tick with the word ‘Available’. Once it is done, click on ‘Create cognito domain’ button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NaUoCXmDxIq1Pzze5UxmXg.png" /></figure><h3>Getting user pool credentials into react project</h3><ol><li>Open the react-aws project that we created earlier from Visual Studio Code (Or any other software that you are familiar with)</li><li>First of all, we need to create a .env file which we will store the credentials of our user pool. Create a file named .env inside react-aws project folder. (It should be located along with package.json file).</li><li>Inside that file, write below two lines<br>REACT_APP_USERPOOL_ID=<br>REACT_APP_APPCLIENT_ID=</li><li>Now we need to find the values for above two variables. In order to do that, select and open the user pool that you created in AWS Cognito.</li><li>Copy the value of User pool ID and paste it as the value for the variable REACT_APP_USERPOOL_ID in .env file.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a3-BEuJS9NoyGz39u7QfEg.png" /><figcaption>Getting User Pool ID from Cognito Dashboard</figcaption></figure><p>6. After that, switch to ‘App Integration’ tab and scroll down to the bottom and find ‘App Client list’ section and get the Client ID from there and paste it as the value for REACT_APP_APPCLIENT_ID variable in .env file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KWfwz5tvw4LprXp6KWehjQ.png" /><figcaption>Getting App Client ID</figcaption></figure><h3>Changing the verification email type from code to link</h3><ol><li>When a user gets signed up, by default he/she will recieve a code from cognito via email to verify his/her email address. Instead of this code, let’s update the verification email settings to send a link via email. So that the user will only have to click on that link to confirm his/her registration. In order to do that, we need to switch to ‘Messaging’ tab in your user pool settings, and scroll down to the bottom of that tab and find ‘Message templates’ section.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2MswFZZpN5flOWaGpz6nyA.png" /><figcaption>‘Messaging’ tab in User pool settings</figcaption></figure><p>2. Click on ‘Verification Message’ in that table. After that, click on ‘Edit’ button in the popup box just opened.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l7TFi_cMGdXaeRxzJIT70A.png" /><figcaption>Verification message popup box</figcaption></figure><p>3. Under Verification Type, Click on ‘Link’ radio button and save the changes.</p><h3>It’s time for some coding</h3><p>Now let’s get back to our react project</p><ol><li>Inside src folder, create two folders named styles and redux.</li><li>Create the additional files and folders based on the screenshot below.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*GhYSJenUfIxusB6laOo1yQ.png" /></figure><p>3. Update App.js file as in below code. Here we have removed the default code lines as they are not needed.</p><pre>// App.js<br>import &#39;./App.css&#39;;<br><br>function App() {<br>  return (<br>    &lt;&gt;&lt;/&gt;<br>  );<br>}<br><br>export default App;</pre><p>4. Update index.js file as in below code. Here we have added routing and redux configurations</p><pre>// index.js<br>import React from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom/client&quot;;<br>import &quot;./index.css&quot;;<br>import reportWebVitals from &quot;./reportWebVitals&quot;;<br>import { createBrowserRouter, RouterProvider } from &quot;react-router-dom&quot;;<br>import Login from &quot;./aws/Login&quot;;<br>import store from &quot;./redux/store&quot;;<br>import { Provider } from &quot;react-redux&quot;;<br>import WelcomeScreen from &quot;./aws/WelcomeScreen&quot;;<br>import { SignUp } from &quot;./aws/SignUp&quot;;<br><br>// routing configurations<br>const router = createBrowserRouter([<br>  {<br>    path: &quot;/&quot;,<br>    element: &lt;Login /&gt;,<br>  },<br>  {<br>    path: &quot;/signup&quot;,<br>    element: &lt;SignUp /&gt;,<br>  },<br>  {<br>    path: &quot;/welcome&quot;,<br>    element: &lt;WelcomeScreen /&gt;,<br>  },<br>]);<br><br>const root = ReactDOM.createRoot(document.getElementById(&quot;root&quot;));<br>root.render(<br>  &lt;Provider store={store}&gt;<br>    &lt;React.StrictMode&gt;<br>      &lt;RouterProvider router={router} /&gt;<br>    &lt;/React.StrictMode&gt;<br>  &lt;/Provider&gt;<br>);<br><br>reportWebVitals();</pre><h3>Signing up the users</h3><p>Update SignUp.jsx file as in below code. This file will render the signup page of our app. We have created a CognitoUserPool object by using the cognito credentials obtained from .env file. <em>process.env.REACT_APP_USERPOOL_ID </em>and<em> process.env.REACT_APP_APPCLIENT_ID )</em></p><ul><li><em>handleSubmit() </em>function will get the form values from formik and creates an attribute list based on those values. Then signup function will get invoked on userPool object to complete the signup process.</li><li>useFormik hook has the default values <em>(initialValues)</em> for the form. Yup is used to define the validationSchema for each form field.</li><li>Once the user enters the correct details in signup form and submits it, an email will be sent to the user with the confirmation link. the user has to open that email and click on that link to complete the registration process.</li></ul><pre>// modules<br>import React, { useEffect } from &quot;react&quot;;<br>import {<br>  CognitoUserPool,<br>  CognitoUserAttribute,<br>} from &quot;amazon-cognito-identity-js&quot;;<br>import styled from &quot;styled-components&quot;;<br>import { useFormik } from &quot;formik&quot;;<br>import * as Yup from &quot;yup&quot;;<br>import { useNavigate } from &quot;react-router-dom&quot;;<br><br>// styling<br>import &quot;./styles/SignUp.scss&quot;;<br><br>const userPool = new CognitoUserPool({<br>  UserPoolId: process.env.REACT_APP_USERPOOL_ID,<br>  ClientId: process.env.REACT_APP_APPCLIENT_ID,<br>});<br><br>export const SignUp = () =&gt; {<br>  const navigate = useNavigate();<br><br>  const handleSubmit = (values) =&gt; {<br>    const email = values.email.trim();<br>    const password = values.password.trim();<br>    const attributeList = [<br>      new CognitoUserAttribute({<br>        Name: &quot;email&quot;,<br>        Value: email,<br>      }),<br>      new CognitoUserAttribute({<br>        Name: &quot;name&quot;,<br>        Value: values.name,<br>      }),<br>      new CognitoUserAttribute({<br>        Name: &quot;custom:telnum&quot;,<br>        Value: values.telnum,<br>      }),<br>    ];<br>    userPool.signUp(email, password, attributeList, null, (err, result) =&gt; {<br>      if (err) {<br>        console.log(err);<br>        return;<br>      }<br>      console.log(&quot;call result: &quot;, result);<br>      navigate(&quot;/&quot;);<br>    });<br>  };<br><br>  const formik = useFormik({<br>    initialValues: {<br>      name: &quot;&quot;,<br>      telnum: &quot;&quot;,<br>      email: &quot;&quot;,<br>      password: &quot;&quot;,<br>    },<br>    validationSchema: Yup.object({<br>      name: Yup.string()<br>        .max(30, &quot;Must be 15 characters or less&quot;)<br>        .required(&quot;Required&quot;),<br>      telnum: Yup.string()<br>        .max(10, &quot;Must be 10 characters or less&quot;)<br>        .required(&quot;Required&quot;),<br>      email: Yup.string().email(&quot;Invalid email address&quot;).required(&quot;Required&quot;),<br>      password: Yup.string()<br>        .required(&quot;No password provided.&quot;)<br>        .matches(/[0-9]/, &quot;Password requires a number&quot;)<br>        .matches(/[a-z]/, &quot;Password requires a lowercase letter&quot;)<br>        .matches(/[A-Z]/, &quot;Password requires an uppercase letter&quot;)<br>        .matches(/[^\w]/, &quot;Password requires a symbol&quot;)<br>        .min(8, &quot;Password is too short. There should be 8 chars minimum.&quot;),<br>    }),<br>    onSubmit: (values) =&gt; {<br>      handleSubmit(values);<br>    },<br>  });<br><br>  return (<br>    &lt;&gt;<br>      &lt;div className=&quot;signup__container&quot;&gt;<br>        &lt;div className=&quot;signup__form&quot; onSubmit={formik.handleSubmit}&gt;<br>          &lt;h1&gt;Sign Up&lt;/h1&gt;<br>          &lt;div className=&quot;signup__fieldName&quot; htmlFor=&quot;name&quot;&gt;<br>            Name<br>          &lt;/div&gt;<br>          &lt;input<br>            className=&quot;signup__inputField&quot;<br>            name=&quot;name&quot;<br>            type=&quot;text&quot;<br>            onChange={formik.handleChange}<br>            onBlur={formik.handleBlur}<br>            value={formik.values.name}<br>          /&gt;<br>          {formik.touched.name &amp;&amp; formik.errors.name ? (<br>            &lt;div className=&quot;signup__error&quot;&gt;{formik.errors.name}&lt;/div&gt;<br>          ) : null}<br><br>          &lt;div className=&quot;signup__fieldName&quot; htmlFor=&quot;telnum&quot;&gt;<br>            Telephone Number<br>          &lt;/div&gt;<br>          &lt;input<br>            className=&quot;signup__inputField&quot;<br>            name=&quot;telnum&quot;<br>            type=&quot;text&quot;<br>            onChange={formik.handleChange}<br>            onBlur={formik.handleBlur}<br>            value={formik.values.telnum}<br>          /&gt;<br>          {formik.touched.telnum &amp;&amp; formik.errors.telnum ? (<br>            &lt;div className=&quot;signup__error&quot;&gt;{formik.errors.telnum}&lt;/div&gt;<br>          ) : null}<br><br>          &lt;div className=&quot;signup__fieldName&quot; htmlFor=&quot;email&quot;&gt;<br>            Email Address<br>          &lt;/div&gt;<br>          &lt;input<br>            className=&quot;signup__inputField&quot;<br>            name=&quot;email&quot;<br>            type=&quot;email&quot;<br>            onChange={formik.handleChange}<br>            onBlur={formik.handleBlur}<br>            value={formik.values.email}<br>          /&gt;<br>          {formik.touched.email &amp;&amp; formik.errors.email ? (<br>            &lt;div className=&quot;signup__error&quot;&gt;{formik.errors.email}&lt;/div&gt;<br>          ) : null}<br><br>          &lt;div className=&quot;signup__fieldName&quot; htmlFor=&quot;password&quot;&gt;<br>            Password<br>          &lt;/div&gt;<br>          &lt;input<br>            className=&quot;signup__inputField&quot;<br>            name=&quot;password&quot;<br>            type=&quot;password&quot;<br>            onChange={formik.handleChange}<br>            onBlur={formik.handleBlur}<br>            value={formik.values.password}<br>          /&gt;<br>          {formik.touched.password &amp;&amp; formik.errors.password ? (<br>            &lt;div className=&quot;signup__error&quot;&gt;{formik.errors.password}&lt;/div&gt;<br>          ) : null}<br><br>          {/* &lt;div className=&quot;signup__fieldName&quot; htmlFor=&quot;confirmPassword&quot;&gt;<br>            Confirm Password<br>          &lt;/div&gt;<br>          &lt;input<br>            className=&quot;signup__inputField&quot;<br>            name=&quot;confirmPassword&quot;<br>            type=&quot;password&quot;<br>            onChange={formik.handleChange}<br>            onBlur={formik.handleBlur}<br>            value={formik.values.confirmPassword}<br>          /&gt;<br>          {formik.touched.confirmPassword &amp;&amp; formik.errors.confirmPassword ? (<br>            &lt;div className=&quot;signup__error&quot;&gt;{formik.errors.confirmPassword}&lt;/div&gt;<br>          ) : null} */}<br><br>          &lt;button<br>            className=&quot;signup__submitButton&quot;<br>            name=&quot;Hello&quot;<br>            onClick={() =&gt; handleSubmit(formik.values)}<br>          &gt;<br>            Submit<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>};</pre><ul><li>In case if you are using an email which doesn’t exist (for testing purposes), you will not be able to receive the verification email to confirm the user account. In such scenarios, you can still confirm the user account using cognito dashboard. Just open the user pool that you created and switch to ‘Users’ tab. Find and click on the user that you want to confirm from the users list.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PDyYmXPlk9LgPb8GiAVEng.png" /><figcaption>Users list in Users tab</figcaption></figure><ul><li>Click on ‘Actions’ button in right side, and select ‘Confirm Account’ option from the menu that gets popped up. Now your user is ready to get logged into the app.</li></ul><p>6. Update SignUp.scss file as in code below</p><pre>.signup__container {<br>  display: flex;<br>  flex-direction: column;<br>  align-items: center;<br>  justify-content: center;<br>  height: 100vh;<br>}<br><br>.signup__form {<br>  display: flex;<br>  flex-direction: column;<br>  align-items: center;<br>  justify-content: center;<br>}<br>.signup__fieldName {<br>  align-self: flex-start;<br>  margin-top: 20pt;<br>}<br><br>.signup__inputField {<br>  margin: 1rem 0 0.25rem;<br>  width: 15rem;<br>}<br><br>.signup__error {<br>  font-size: 12px;<br>  color: red;<br>}<br><br>.signup__submitButton {<br>  background: white;<br>  margin: 1.5rem;<br>  padding: 0.5rem 1rem;<br>  color: #2196f3;<br>  border: 1px solid #2196f3;<br>  border-radius: 10px;<br>  font-weight: 700;<br><br>  &amp;:hover {<br>    background: #2196f3;<br>    color: white;<br>  }<br>}</pre><h3>User Signing in</h3><p>7. Update Login.jsx file as in below code. This file will render the login page in the app.</p><ul><li>handleSubmit() function will create a cognitoUser Object and an authenticationDetails object. After that, authenticateUser function will get invoked on cognitoUser Object. Once the authentication gets succeeded, it will get the user data using getUserAttributes method and then it will dispatch an action to update that value in Redux store.</li></ul><pre>// modules<br>import React from &quot;react&quot;;<br>import {<br>  CognitoUserPool,<br>  CognitoUser,<br>  AuthenticationDetails,<br>} from &quot;amazon-cognito-identity-js&quot;;<br>import { useFormik } from &quot;formik&quot;;<br>import * as Yup from &quot;yup&quot;;<br>import { useNavigate } from &quot;react-router-dom&quot;;<br>import { useDispatch } from &quot;react-redux&quot;;<br>import { updateData } from &quot;../redux/slices/authSlice&quot;;<br><br>// styling<br>import &quot;./styles/Login.scss&quot;;<br><br>const userPool = new CognitoUserPool({<br>  UserPoolId: process.env.REACT_APP_USERPOOL_ID,<br>  ClientId: process.env.REACT_APP_APPCLIENT_ID,<br>});<br><br>const Login = () =&gt; {<br>  const navigate = useNavigate();<br>  const dispatch = useDispatch();<br><br>  const handleSubmit = (values) =&gt; {<br>    const cognitoUser = new CognitoUser({<br>      Username: values.email,<br>      Pool: userPool,<br>    });<br><br>    const authenticationDetails = new AuthenticationDetails({<br>      Username: values.email,<br>      Password: values.password,<br>    });<br><br>    cognitoUser.authenticateUser(authenticationDetails, {<br>      onSuccess: (result) =&gt; {<br>        cognitoUser.getUserAttributes(function (err, result) {<br>          if (err) {<br>            console.log(&quot;err&quot;, err);<br>            return;<br>          }<br>          dispatch(<br>            updateData({<br>              name: result[2].Value,<br>              email: values.email,<br>            })<br>          );<br>          navigate(&quot;/welcome&quot;);<br>        });<br>      },<br>      onFailure: (err) =&gt; {<br>        console.log(&quot;login failed&quot;, err);<br>      },<br>    });<br>  };<br>  const formik = useFormik({<br>    initialValues: {<br>      email: &quot;&quot;,<br>      password: &quot;&quot;,<br>    },<br>    validationSchema: Yup.object({<br>      email: Yup.string().email(&quot;Invalid email address&quot;).required(&quot;Required&quot;),<br>      password: Yup.string().required(&quot;No password provided.&quot;),<br>    }),<br>    onSubmit: (values) =&gt; {<br>      handleSubmit(values);<br>    },<br>  });<br><br>  return (<br>    &lt;&gt;<br>      &lt;div className=&quot;login__container&quot;&gt;<br>        &lt;div className=&quot;login__form&quot; onSubmit={formik.handleSubmit}&gt;<br>          &lt;h1&gt;Sign In&lt;/h1&gt;<br><br>          &lt;div className=&quot;login__fieldName&quot; htmlFor=&quot;email&quot;&gt;<br>            Email Address<br>          &lt;/div&gt;<br>          &lt;input<br>            className=&quot;login__inputField&quot;<br>            name=&quot;email&quot;<br>            type=&quot;email&quot;<br>            onChange={formik.handleChange}<br>            onBlur={formik.handleBlur}<br>            value={formik.values.email}<br>          /&gt;<br>          {formik.touched.email &amp;&amp; formik.errors.email ? (<br>            &lt;div className=&quot;login__error&quot;&gt;{formik.errors.email}&lt;/div&gt;<br>          ) : null}<br><br>          &lt;div className=&quot;login__fieldName&quot; htmlFor=&quot;password&quot;&gt;<br>            Password<br>          &lt;/div&gt;<br>          &lt;input<br>            className=&quot;login__inputField&quot;<br>            name=&quot;password&quot;<br>            type=&quot;password&quot;<br>            onChange={formik.handleChange}<br>            onBlur={formik.handleBlur}<br>            value={formik.values.password}<br>          /&gt;<br>          {formik.touched.password &amp;&amp; formik.errors.password ? (<br>            &lt;div className=&quot;login__error&quot;&gt;{formik.errors.password}&lt;/div&gt;<br>          ) : null}<br><br>          &lt;button<br>            className=&quot;login__submitButton&quot;<br>            onClick={() =&gt; handleSubmit(formik.values)}<br>          &gt;<br>            {&quot; &quot;}<br>            Log in{&quot; &quot;}<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default Login;</pre><p>8. Update Login.scss file as in below code.</p><pre>.login__container {<br>  display: flex;<br>  flex-direction: column;<br>  align-items: center;<br>  justify-content: center;<br>  height: 100vh;<br>}<br><br>.login__form {<br>  display: flex;<br>  flex-direction: column;<br>  align-items: center;<br>  justify-content: center;<br>}<br>.login__fieldName {<br>  align-self: flex-start;<br>  margin-top: 20pt;<br>}<br><br>.login__inputField {<br>  margin: 1rem 0 0.25rem;<br>  width: 15rem;<br>}<br><br>.login__error {<br>  font-size: 12px;<br>  color: red;<br>}<br><br>.login__submitButton {<br>  background: white;<br>  margin: 1.5rem;<br>  padding: 0.5rem 1rem;<br>  color: #2196f3;<br>  border: 1px solid #2196f3;<br>  border-radius: 10px;<br>  font-weight: 700;<br><br>  &amp;:hover {<br>    background: #2196f3;<br>    color: white;<br>  }<br>}</pre><p>9. Update WelcomeScreen.jsx file as in below code.</p><ul><li>Here the code will obtain the name of the user which was stored in redux store and display it in the welcome screen.</li><li>User can log out from the app by clicking Logout button which will invoke signout() method on cognitoUser object.</li></ul><pre>// modules<br>import React, { useEffect } from &quot;react&quot;;<br>import {<br>  CognitoUserPool<br>} from &quot;amazon-cognito-identity-js&quot;;<br>import { useSelector } from &quot;react-redux&quot;;<br>import { useNavigate } from &quot;react-router-dom&quot;;<br><br>// styling<br>import &quot;./styles/Welcome.scss&quot;;<br><br>const userPool = new CognitoUserPool({<br>  UserPoolId: process.env.REACT_APP_USERPOOL_ID,<br>  ClientId: process.env.REACT_APP_APPCLIENT_ID,<br>});<br><br>const WelcomeScreen = () =&gt; {<br><br>  const navigate = useNavigate();<br>  const userData = useSelector((state) =&gt; state.auth.userData);<br><br>  const signOut = () =&gt; {<br><br>    const cognitoUser = userPool.getCurrentUser();<br><br>    if (cognitoUser != null) {<br>      cognitoUser.signOut();<br>    }<br><br>    navigate(&quot;/&quot;);<br>  };<br><br>  <br>  return (<br>    &lt;div className=&quot;Container&quot;&gt;<br>      &lt;h1 className=&quot;Greeting&quot;&gt;Hi {userData.name}!&lt;/h1&gt;<br>      &lt;button<br>        className=&quot;SignoutButton&quot;<br>        onClick={() =&gt; {<br>          signOut();<br>        }}<br>      &gt;<br>        Logout<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default WelcomeScreen;</pre><p>10. Update WelcomeScreen.scss file as in below code.</p><pre>@import url(https://medium.com/&#39;https://fonts.googleapis.com/css2?family=Roboto&amp;display=swap&#39;);<br><br>.Container {<br>    height: 100vh;<br>    display: flex;<br>    flex-direction: column;<br>    align-items: center;<br>    justify-content: center;<br>    font-family: &#39;Roboto&#39;, sans-serif;<br>    font-size: 2rem;<br>}<br><br>.Column {<br>    display: flex;<br>    flex-direction: column;<br>    justify-content: center;<br>}<br><br>.Row {<br>    display: flex;<br>    flex-direction: row;<br>    width: 100%;<br>}<br><br>.justifyRight {<br>    justify-content: right;<br>}<br><br>.Greeting {<br>    justify-self: center;<br>}<br><br>.SignoutButton {<br>    padding: 10px 20px;<br>    color: rgb(36, 114, 224);<br>    font-weight: 700;<br>    border-radius: 10px;<br>    border-width: 1px;<br>    border-color: rgb(36, 114, 224);<br>    background: none;<br>    margin: 20px;<br><br>    &amp;:hover {<br>        background-color: rgb(36, 114, 224);<br>        color: white;<br>    }<br>}</pre><p>11. Update authSlice.js file as in below code.</p><pre>// authSlice.js<br>import { createSlice } from &quot;@reduxjs/toolkit&quot;;<br><br>export const authSlice = createSlice({<br>  name: &quot;auth&quot;,<br>  initialState: {<br>    userData: { name: &quot;&quot;, email: &quot;&quot; },<br>  },<br>  reducers: {<br><br>    updateData: (state, action) =&gt; {<br>      state.userData = action.payload;<br>    },<br><br>  },<br>});<br><br>// Action creators are generated for each case reducer function<br>export const { updateData } = authSlice.actions;<br><br>export default authSlice.reducer;</pre><p>12. Update store.js file as in below code.</p><pre>// store.js<br>import { configureStore } from &#39;@reduxjs/toolkit&#39;<br>import authSlice from &#39;./slices/authSlice&#39;<br><br>export default configureStore({<br>  reducer: {<br>    auth: authSlice,<br>  },<br>})</pre><p>That’s all and now you are good to go with your simple app.<br>In addition to above scenarios, here are some other scenarios that take advantage of some more cognito functionalities. These codes are taken from <strong>amazon-cognito-identity-js</strong> <a href="https://github.com/aws-amplify/amplify-js/tree/main/packages/amazon-cognito-identity-js">repo</a>.</p><p>For most of the below scenarios where cognitoUser object is used invoke a certain method, Below code snippet needs to be there to define the cognitoUser object.</p><pre>var poolData = {<br> UserPoolId: &#39;...&#39;, // Your user pool id here<br> ClientId: &#39;...&#39;, // Your client id here<br>};<br><br>var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);<br>var userData = {<br> Username: &#39;username&#39;,<br> Pool: userPool,<br>};<br><br>var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);</pre><p><strong>Scenario 1 - </strong>Confirming a registered, unauthenticated user using a confirmation code received via SMS or Email.</p><pre>cognitoUser.confirmRegistration(&#39;123456&#39;, true, function(err, result) {<br> if (err) {<br>  alert(err.message || JSON.stringify(err));<br>  return;<br> }<br> console.log(&#39;call result: &#39; + result);<br>});</pre><p><strong>Scenario 2 - </strong>Resending a confirmation code via SMS for confirming registration for a unauthenticated user.</p><pre>cognitoUser.resendConfirmationCode(function(err, result) {<br> if (err) {<br>  alert(err.message || JSON.stringify(err));<br>  return;<br> }<br> console.log(&#39;call result: &#39; + result);<br>});</pre><p><strong>Scenario 3 -</strong> Resending a confirmation code via SMS for confirming registration for a unauthenticated user.</p><pre>cognitoUser.resendConfirmationCode(function(err, result) {<br> if (err) {<br>  alert(err.message || JSON.stringify(err));<br>  return;<br> }<br> console.log(&#39;call result: &#39; + result);<br>});</pre><p><strong>Scenario 4</strong> - Retrieve user attributes for an authenticated user.</p><pre>cognitoUser.getUserAttributes(function(err, result) {<br> if (err) {<br>  alert(err.message || JSON.stringify(err));<br>  return;<br> }<br> for (i = 0; i &lt; result.length; i++) {<br>  console.log(<br>   &#39;attribute &#39; + result[i].getName() + &#39; has value &#39; + result[i].getValue()<br>  );<br> }<br>});</pre><p><strong>Scenario 5</strong> - Verify user attribute for an authenticated user.</p><p>Note that the inputVerificationCode method needs to be defined but does not need to actually do anything. If you would like the user to input the verification code on another page, you can set inputVerificationCode to null. If inputVerificationCode is null, onSuccess will be called immediately (assuming there is no error).</p><pre>cognitoUser.getAttributeVerificationCode(&#39;email&#39;, {<br> onSuccess: function(result) {<br>  console.log(&#39;call result: &#39; + result);<br> },<br> onFailure: function(err) {<br>  alert(err.message || JSON.stringify(err));<br> },<br> inputVerificationCode: function() {<br>  var verificationCode = prompt(&#39;Please input verification code: &#39;, &#39;&#39;);<br>  cognitoUser.verifyAttribute(&#39;email&#39;, verificationCode, this);<br> },<br>});</pre><p><strong>Scenario 6</strong> - Delete user attribute for an authenticated user.</p><pre>var attributeList = [];<br>attributeList.push(&#39;nickname&#39;);<br><br>cognitoUser.deleteAttributes(attributeList, function(err, result) {<br> if (err) {<br>  alert(err.message || JSON.stringify(err));<br>  return;<br> }<br> console.log(&#39;call result: &#39; + result);<br>});</pre><p><strong>Scenario 7</strong> - Update user attributes for an authenticated user.</p><pre>var attributeList = [];<br>var attribute = {<br> Name: &#39;nickname&#39;,<br> Value: &#39;joe&#39;,<br>};<br>var attribute = new AmazonCognitoIdentity.CognitoUserAttribute(attribute);<br>attributeList.push(attribute);<br><br>cognitoUser.updateAttributes(attributeList, function(err, result) {<br> if (err) {<br>  alert(err.message || JSON.stringify(err));<br>  return;<br> }<br> console.log(&#39;call result: &#39; + result);<br>});</pre><p><strong>Scenario 8</strong> - Changing the current password for an authenticated user.</p><pre>cognitoUser.changePassword(&#39;oldPassword&#39;, &#39;newPassword&#39;, function(err, result) {<br>	if (err) {<br>		alert(err.message || JSON.stringify(err));<br>		return;<br>	}<br>	console.log(&#39;call result: &#39; + result);<br>});</pre><p><strong>Scenario 9</strong> - Starting and completing a forgot password flow for an unauthenticated user.</p><p>For example:</p><pre>&lt;body&gt;<br>    &lt;label for=&quot;#code&quot;&gt;Code: &lt;/label&gt;<br>    &lt;input id=&quot;code&quot;&gt;&lt;/input&gt;<br>    &lt;/br&gt;<br>    &lt;label for=&quot;#new_password&quot;&gt;New Password: &lt;/label&gt;<br>    &lt;input id=&quot;new_password&quot; type=&quot;password&quot;&gt;&lt;/input&gt;<br>    &lt;br/&gt;<br>&lt;/body&gt;</pre><pre>cognitoUser.forgotPassword({<br>	onSuccess: function(data) {<br>		// successfully initiated reset password request<br>		console.log(&#39;CodeDeliveryData from forgotPassword: &#39; + data);<br>	},<br>	onFailure: function(err) {<br>		alert(err.message || JSON.stringify(err));<br>	},<br>	//Optional automatic callback<br>	inputVerificationCode: function(data) {<br>		console.log(&#39;Code sent to: &#39; + data);<br>		var verificationCode = document.getElementById(&#39;code&#39;).value;<br>		var newPassword = document.getElementById(&#39;new_password&#39;).value;<br>		cognitoUser.confirmPassword(verificationCode, newPassword, {<br>			onSuccess() {<br>				console.log(&#39;Password confirmed!&#39;);<br>			},<br>			onFailure(err) {<br>				console.log(&#39;Password not confirmed!&#39;);<br>			},<br>		});<br>	},<br>});</pre><p><strong>Scenario 10 </strong>- Deleting an authenticated user.</p><pre>cognitoUser.deleteUser(function(err, result) {<br>	if (err) {<br>		alert(err.message || JSON.stringify(err));<br>		return;<br>	}<br>	console.log(&#39;call result: &#39; + result);<br>});</pre><p><strong>Scenario 11 </strong>- Signing out from the application.</p><pre>cognitoUser.signOut();</pre><p><strong>Scenario</strong> <strong>12</strong> - Global signout for an authenticated user(invalidates all issued tokens).</p><pre>cognitoUser.globalSignOut(callback);</pre><p><strong>Scenario</strong> <strong>13</strong> - Retrieving the current user from local storage.</p><pre>var poolData = {<br>	UserPoolId: &#39;...&#39;, // Your user pool id here<br>	ClientId: &#39;...&#39;, // Your client id here<br>};<br>var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);<br>var cognitoUser = userPool.getCurrentUser();<br><br>if (cognitoUser != null) {<br> cognitoUser.getSession(function(err, session) {<br>  if (err) {<br>   alert(err.message || JSON.stringify(err));<br>   return;<br>  }<br>  console.log(&#39;session validity: &#39; + session.isValid());<br><br>  // NOTE: getSession must be called to authenticate user before calling getUserAttributes<br>  cognitoUser.getUserAttributes(function(err, attributes) {<br>   if (err) {<br>    // Handle error<br>   } else {<br>    // Do something with attributes<br>   }<br>  });<br><br>  AWS.config.credentials = new AWS.CognitoIdentityCredentials({<br>   IdentityPoolId: &#39;...&#39;, // your identity pool id here<br>   Logins: {<br>    // Change the key below according to the specific region your user pool is in.<br>    &#39;cognito-idp.&lt;region&gt;.amazonaws.com/&lt;YOUR_USER_POOL_ID&gt;&#39;: session<br>     .getIdToken()<br>     .getJwtToken(),<br>   },<br>  });<br><br>  // Instantiate aws sdk service objects now that the credentials have been updated.<br>  // example: var s3 = new AWS.S3();<br> });<br>}</pre><p><strong>Scenario</strong> <strong>14</strong> - Integrating User Pools with Cognito Identity.</p><pre>var cognitoUser = userPool.getCurrentUser();<br>if (cognitoUser != null) {<br> cognitoUser.getSession(function(err, result) {<br>  if (result) {<br>   console.log(&#39;You are now logged in.&#39;);<br><br>   //POTENTIAL: Region needs to be set if not already set previously elsewhere.<br>   AWS.config.region = &#39;&lt;region&gt;&#39;;<br><br>   // Add the User&#39;s Id Token to the Cognito credentials login map.<br>   AWS.config.credentials = new AWS.CognitoIdentityCredentials({<br>    IdentityPoolId: &#39;YOUR_IDENTITY_POOL_ID&#39;,<br>    Logins: {<br>     &#39;cognito-idp.&lt;region&gt;.amazonaws.com/&lt;YOUR_USER_POOL_ID&gt;&#39;: result<br>      .getIdToken()<br>      .getJwtToken(),<br>    },<br>   });<br>  }<br> });<br>}<br>//call refresh method in order to authenticate user and get new temp credentials<br>AWS.config.credentials.refresh(error =&gt; {<br> if (error) {<br>  console.error(error);<br> } else {<br>  console.log(&#39;Successfully logged!&#39;);<br> }<br>});</pre><p><strong>Scenario</strong> <strong>15</strong> - List all remembered devices for an authenticated user. In this case, we need to pass a limit on the number of devices retrieved at a time and a pagination token is returned to make subsequent calls. The pagination token can be subsequently passed. When making the first call, the pagination token should be null.</p><pre>cognitoUser.listDevices(limit, paginationToken, {<br>	onSuccess: function(result) {<br>		console.log(&#39;call result: &#39; + result);<br>	},<br>	onFailure: function(err) {<br>		alert(err.message);<br>	},<br>});</pre><p><strong>Scenario</strong> <strong>16</strong> - List information about the current device.</p><pre>cognitoUser.getDevice({<br>	onSuccess: function(result) {<br>		console.log(&#39;call result: &#39; + result);<br>	},<br>	onFailure: function(err) {<br>		alert(err.message || JSON.stringify(err));<br>	},<br>});</pre><p><strong>Scenario</strong> <strong>17</strong> - Remember a device.</p><pre>cognitoUser.setDeviceStatusRemembered({<br>	onSuccess: function(result) {<br>		console.log(&#39;call result: &#39; + result);<br>	},<br>	onFailure: function(err) {<br>		alert(err.message || JSON.stringify(err));<br>	},<br>});</pre><p><strong>Scenario</strong> <strong>18</strong> - Do not remember a device.</p><pre>cognitoUser.setDeviceStatusNotRemembered({<br>	onSuccess: function(result) {<br>		console.log(&#39;call result: &#39; + result);<br>	},<br>	onFailure: function(err) {<br>		alert(err.message || JSON.stringify(err));<br>	},<br>});</pre><p><strong>Scenario</strong> <strong>19</strong> - Forget the current device.</p><pre>cognitoUser.forgetDevice({<br>	onSuccess: function(result) {<br>		console.log(&#39;call result: &#39; + result);<br>	},<br>	onFailure: function(err) {<br>		alert(err.message || JSON.stringify(err));<br>	},<br>});</pre><p><strong>Scenario</strong> <strong>20</strong> - Authenticate a user and set new password for a user that was created using AdminCreateUser API.</p><pre>var cognitoUser, sessionUserAttributes; // global variables to handle completeNewPasswordChallenge flow<br>cognitoUser.authenticateUser(authenticationDetails, {<br>        onSuccess: function (result) {<br>            // User authentication was successful<br>        },<br><br>        onFailure: function(err) {<br>            // User authentication was not successful<br>        },<br><br>        mfaRequired: function(codeDeliveryDetails) {<br>            // MFA is required to complete user authentication.<br>            // Get the code from user and call<br>            cognitoUser.sendMFACode(mfaCode, this)<br>        },<br><br>        newPasswordRequired: function(userAttributes, requiredAttributes) {<br>            // User was signed up by an admin and must provide new<br>            // password and required attributes, if any, to complete<br>            // authentication.<br><br>            // the api doesn&#39;t accept this field back<br>            delete userAttributes.email_verified;<br><br>            // store userAttributes on global variable<br>            sessionUserAttributes = userAttributes;<br>        }<br>    });<br><br>    // ... handle new password flow on your app<br>    handleNewPassword(newPassword) {<br>      cognitoUser.completeNewPasswordChallenge(newPassword, sessionUserAttributes);<br>    }</pre><p><strong>Scenario</strong> <strong>21</strong> - Retrieve the MFA settings for the user.</p><pre>cognitoUser.getUserData((err, data) =&gt; {<br>	if (err) {<br>		alert(err.message || JSON.stringify(err));<br>		return;<br>	}<br>	const { PreferredMfaSetting, UserMFASettingList } = data;<br>	console.log(<br>		JSON.stringify({ PreferredMfaSetting, UserMFASettingList }, null, 2)<br>	);<br>});</pre><p>E.g.</p><pre>{<br>	&quot;PreferredMfaSetting&quot;: &quot;SMS_MFA&quot;,<br>	&quot;UserMFASettingList&quot;: [&quot;SMS_MFA&quot;]<br>}</pre><p><strong>Scenario</strong> <strong>22</strong> - Authenticating a user with a passwordless custom flow.</p><pre>cognitoUser.setAuthenticationFlowType(&#39;CUSTOM_AUTH&#39;);<br>cognitoUser.initiateAuth(authenticationDetails, {<br> onSuccess: function(result) {<br>  // User authentication was successful<br> },<br> onFailure: function(err) {<br>  // User authentication was not successful<br> },<br> customChallenge: function(challengeParameters) {<br>  // User authentication depends on challenge response<br>  var challengeResponses = &#39;challenge-answer&#39;;<br>  cognitoUser.sendCustomChallengeAnswer(challengeResponses, this);<br> },<br>});</pre><p><strong>Scenario</strong> <strong>23</strong> - Using cookies to store cognito tokens</p><p>To use the CookieStorage you have to pass it in the constructor map of CognitoUserPool and CognitoUser (when constructed directly):</p><pre>var poolData = {<br>     UserPoolId : &#39;...&#39;, // Your user pool id here<br>     ClientId : &#39;...&#39; // Your client id here<br>     Storage: new AmazonCognitoIdentity.CookieStorage({domain: &quot;.yourdomain.com&quot;})<br> };<br><br> var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);<br><br> var userData = {<br>     Username: &#39;username&#39;,<br>     Pool: userPool,<br>     Storage: new AmazonCognitoIdentity.CookieStorage({domain: &quot;.yourdomain.com&quot;})<br> };</pre><p>The CookieStorage object receives a map (data) in its constructor that may have these values:</p><ul><li>data.domain Cookies domain (mandatory)</li><li>data.path Cookies path (default: ‘/’)</li><li>data.expires Cookie expiration (in days, default: 365)</li><li>data.secure Cookie secure flag (default: true)</li><li>data.sameSite Cookie request behaviour (default: null)</li></ul><p><strong>Scenario</strong> <strong>24</strong> - Selecting the MFA method and authenticating using TOTP.</p><pre>var authenticationData = {<br>	Username: &#39;username&#39;,<br>	Password: &#39;password&#39;,<br>};<br>var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(<br>	authenticationData<br>);<br>var poolData = {<br>	UserPoolId: &#39;...&#39;, // Your user pool id here<br>	ClientId: &#39;...&#39;, // Your client id here<br>};<br>var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);<br>var userData = {<br>	Username: &#39;username&#39;,<br>	Pool: userPool,<br>};<br>var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);<br><br>cognitoUser.authenticateUser(authenticationDetails, {<br> onSuccess: function(result) {<br>  var accessToken = result.getAccessToken().getJwtToken();<br> },<br><br> onFailure: function(err) {<br>  alert(err.message || JSON.stringify(err));<br> },<br><br> mfaSetup: function(challengeName, challengeParameters) {<br>  cognitoUser.associateSoftwareToken(this);<br> },<br><br> associateSecretCode: function(secretCode) {<br>  var challengeAnswer = prompt(&#39;Please input the TOTP code.&#39;, &#39;&#39;);<br>  cognitoUser.verifySoftwareToken(challengeAnswer, &#39;My TOTP device&#39;, this);<br> },<br><br> selectMFAType: function(challengeName, challengeParameters) {<br>  var mfaType = prompt(&#39;Please select the MFA method.&#39;, &#39;&#39;); // valid values for mfaType is &quot;SMS_MFA&quot;, &quot;SOFTWARE_TOKEN_MFA&quot;<br>  cognitoUser.sendMFASelectionAnswer(mfaType, this);<br> },<br><br> totpRequired: function(secretCode) {<br>  var challengeAnswer = prompt(&#39;Please input the TOTP code.&#39;, &#39;&#39;);<br>  cognitoUser.sendMFACode(challengeAnswer, this, &#39;SOFTWARE_TOKEN_MFA&#39;);<br> },<br><br> mfaRequired: function(codeDeliveryDetails) {<br>  var verificationCode = prompt(&#39;Please input verification code&#39;, &#39;&#39;);<br>  cognitoUser.sendMFACode(verificationCode, this);<br> },<br>});</pre><p><strong>Scenario</strong> <strong>25</strong> - Enabling and setting SMS MFA as the preferred MFA method for the user.</p><pre>var smsMfaSettings = {<br>	PreferredMfa: true,<br>	Enabled: true,<br>};<br>cognitoUser.setUserMfaPreference(smsMfaSettings, null, function(err, result) {<br>	if (err) {<br>		alert(err.message || JSON.stringify(err));<br>	}<br>	console.log(&#39;call result &#39; + result);<br>});</pre><p><strong>Scenario</strong> <strong>26</strong> - Enabling and setting TOTP MFA as the preferred MFA method for the user.</p><pre>var totpMfaSettings = {<br>	PreferredMfa: true,<br>	Enabled: true,<br>};<br>cognitoUser.setUserMfaPreference(null, totpMfaSettings, function(err, result) {<br>	if (err) {<br>		alert(err.message || JSON.stringify(err));<br>	}<br>	console.log(&#39;call result &#39; + result);<br>});</pre><p><strong>Scenario 27</strong> - Authenticating a user with a user password auth flow.</p><pre>cognitoUser.setAuthenticationFlowType(&#39;USER_PASSWORD_AUTH&#39;);<br>cognitoUser.authenticateUser(authenticationDetails, {<br> onSuccess: function(result) {<br>  // User authentication was successful<br> },<br> onFailure: function(err) {<br>  // User authentication was not successful<br> },<br> mfaRequired: function(codeDeliveryDetails) {<br>  // MFA is required to complete user authentication.<br>  // Get the code from user and call<br>  cognitoUser.sendMFACode(verificationCode, this);<br> },<br>});</pre><p><strong>Scenario 28</strong> - Retrieve the user data for an authenticated user.</p><pre>cognitoUser.getUserData(function(err, userData) {<br>	if (err) {<br>		alert(err.message || JSON.stringify(err));<br>		return;<br>	}<br>	console.log(&#39;User data for user &#39; + userData);<br>});<br>// If you want to force to get the user data from backend,<br>// you can set the bypassCache to true<br>cognitoUser.getUserData(<br>	function(err, userData) {<br>		if (err) {<br>			alert(err.message || JSON.stringify(err));<br>			return;<br>		}<br>		console.log(&#39;User data for user &#39; + userData);<br>	},<br>	{ bypassCache: true }<br>);</pre><p><strong>Scenario 29</strong> - Handling expiration of the Id Token.</p><pre>var refresh_token = session.getRefreshToken(); // receive session from calling cognitoUser.getSession()<br>if (AWS.config.credentials.needsRefresh()) {<br>	cognitoUser.refreshSession(refresh_token, (err, session) =&gt; {<br>		if (err) {<br>			console.log(err);<br>		} else {<br>			AWS.config.credentials.params.Logins[<br>				&#39;cognito-idp.&lt;YOUR-REGION&gt;.amazonaws.com/&lt;YOUR_USER_POOL_ID&gt;&#39;<br>			] = session.getIdToken().getJwtToken();<br>			AWS.config.credentials.refresh(err =&gt; {<br>				if (err) {<br>					console.log(err);<br>				} else {<br>					console.log(&#39;TOKEN SUCCESSFULLY UPDATED&#39;);<br>				}<br>			});<br>		}<br>	});<br>}</pre><h3><strong>References</strong></h3><ul><li>amazon-cognito-identity-js repo - <a href="https://github.com/aws-amplify/amplify-js/tree/main/packages/amazon-cognito-identity-js">https://github.com/aws-amplify/amplify-js/tree/main/packages/amazon-cognito-identity-js</a></li><li>Amazon Cognito Developer Guide - <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html">https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html</a></li><li>Amazon Cognito API Reference - <a href="https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_Operations.html">https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_Operations.html</a></li><li>Github repo of this tutorial - <a href="https://github.com/sankharr/react-aws">https://github.com/sankharr/react-aws</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d0e3af997c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>