Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 23, 2023 05:01 am GMT

Building and Launching a Serverless GraphQL React Application with AWS Amplify: A Step-by-Step Guide

Image description

Introduction

Serverless computing has been gaining popularity in recent years due to its numerous benefits, such as scalability, cost-effectiveness, and flexibility. AWS Amplify is a development platform that allows developers to build and deploy serverless applications quickly and easily. In this blog post, I will guide you through the process of building and launching a serverless GraphQL React application with AWS Amplify.

Prerequisites

Before getting started, you will need the following:

  1. An AWS account.
  2. Node.js installed on your machine.
  3. Basic knowledge of React and GraphQL.

Step-1: Create a new React app

To get started, lets create a new React application. Open up your terminal and run the following command:

npx create-react-app amplify-react-graphql-demo

~/Documents/amplify-hackathon  npx create-react-app amplify-react-graphql-demo                                                                                                        1   4s  07:11:58Creating a new React app in ~/Documents/amplify-hackathon/amplify-react-graphql-demo.Installing packages. This might take a couple of minutes.Installing react, react-dom, and react-scripts with cra-template...added 1420 packages in 1m233 packages are looking for funding  run `npm fund` for detailsInitialized a git repository.Installing template dependencies using npm...added 62 packages, and changed 1 package in 6s233 packages are looking for funding  run `npm fund` for detailsRemoving template package using npm...removed 1 package, and audited 1482 packages in 3s233 packages are looking for funding  run `npm fund` for details6 high severity vulnerabilitiesTo address all issues (including breaking changes), run:  npm audit fix --forceRun `npm audit` for details.Created git commit.Success! Created amplify-react-graphql-demo at ~/Documents/amplify-hackathon/amplify-react-graphql-demoInside that directory, you can run several commands:  npm start    Starts the development server.  npm run build    Bundles the app into static files for production.  npm test    Starts the test runner.  npm run eject    Removes this tool and copies build dependencies, configuration files    and scripts into the app directory. If you do this, you cant go back!We suggest that you begin by typing:  cd amplify-react-graphql-demo  npm startHappy hacking!

This will create a new React app in a directory called amplify-react-graphql-demo.

~/Documents/amplify-hackathon/amplify-react-graphql-demo> ll   07:14:16total 1336-rw-r - r - 1 macpro staff 3.3K 28 Mar 07:13 README.mddrwxr-xr-x 826 macpro staff 26K 28 Mar 07:13 node_modules-rw-r - r - 1 macpro staff 658K 28 Mar 07:13 package-lock.json-rw-r - r - 1 macpro staff 829B 28 Mar 07:13 package.jsondrwxr-xr-x 8 macpro staff 256B 28 Mar 07:13 publicdrwxr-xr-x 10 macpro staff 320B 28 Mar 07:13 src

To start our React app we can run from the amplify-react-graphql-demo directory npm start. This will start the development server at http://localhost:3000

~/Documents/amplify-hackathon/amplify-react-graphql-demo  main  npm start                                                                                                                     07:14:17> [email protected] start> react-scripts start(node:29299) [DEP_WEBPACK_DEV_SERVER_ON_AFTER_SETUP_MIDDLEWARE] DeprecationWarning: 'onAfterSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option.(Use `node --trace-deprecation ...` to show where the warning was created)(node:29299) [DEP_WEBPACK_DEV_SERVER_ON_BEFORE_SETUP_MIDDLEWARE] DeprecationWarning: 'onBeforeSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option.Starting the development server...Compiled successfully!You can now view amplify-react-graphql-demo in the browser.  Local:            http://localhost:3000  On Your Network:  http://192.168.0.87:3000Note that the development build is not optimized.To create a production build, use npm run build.webpack compiled successfullyCompiling...Compiled successfully!You can now view amplify-react-graphql-demo in the browser.  Local:            http://localhost:3000  On Your Network:  http://192.168.0.87:3000Note that the development build is not optimized.To create a production build, use npm run build.webpack compiled successfully

This will start the development server at http://localhost:3000.

Step-2: Install AWS Amplify CLI

Next, we need to install the AWS Amplify CLI. Open up your terminal and run the following command:

npm install -g @aws-amplify/cli

 ~/Documents/amplify-hackathon/amplify-react-graphql-demo  main !5 ?3  npm install -g @aws-amplify/cli                                                                                 1   4s  22:11:35changed 26 packages in 25s7 packages are looking for funding  run `npm fund` for detailsnpm noticenpm notice New minor version of npm available! 9.4.0 -> 9.6.5npm notice Changelog: https://github.com/npm/cli/releases/tag/v9.6.5npm notice Run npm install -g [email protected] to update!npm notice

This will install the Amplify CLI globally on your machine or upgrade the old version.

Step 3: Configure Amplify

Now that we have installed the Amplify CLI, lets configure it. Run the following command in your terminal:

amplify configure

This will prompt you to enter your AWS credentials. Follow the prompts to enter your Access Key ID and Secret Access Key.

Step 4: Initialise Amplify

Now that Amplify is configured, lets initialise it in our React app. Run the following command in your terminal:

amplify init

 ~/Documents/amplify-hackathon/amplify-react-graphql-demo> amplify init                                                                                                    INT   5m 37s  07:20:11Note: It is recommended to run this command from the root of your app directory? Enter a name for the project amplifyhackathonThe following configuration will be applied:Project information| Name: amplifyhackathon| Environment: dev| Default editor: Visual Studio Code| App type: javascript| Javascript framework: react| Source Directory Path: src| Distribution Directory Path: build| Build Command: npm run-script build| Start Command: npm run-script start? Initialize the project with the above configuration? YesUsing default provider  awscloudformation? Select the authentication method you want to use: AWS profileFor more information on AWS Profiles, see:https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html? Please choose the profile you want to use defaultAdding backend environment dev to AWS Amplify app: d3jyorszjwcditDeployment completed.Deploying root stack amplifyhackathon [ ====================-------------------- ] 2/4 amplify-amplifyhackathon-dev- AWS::CloudFormation::Stack     CREATE_IN_PROGRESS             Tue Mar 28 2023 07:21:14 UnauthRole                     AWS::IAM::Role                 CREATE_COMPLETE                Tue Mar 28 2023 07:21:32 AuthRole                       AWS::IAM::Role                 CREATE_COMPLETE                Tue Mar 28 2023 07:21:32 DeploymentBucket               AWS::S3::Bucket                CREATE_IN_PROGRESS             Tue Mar 28 2023 07:21:18 Help improve Amplify CLI by sharing non sensitive configurations on failures (y/N)  noDeployment state saved successfully. Initialized provider successfully. Initialized your environment successfully.Your project has been successfully initialized and connected to the cloud!Some next steps:"amplify status" will show you what you've added already and if it's locally configured or deployed"amplify add <category>" will allow you to add features like user login or a backend API"amplify push" will build all your local backend resources and provision it in the cloud"amplify console" to open the Amplify Console and view your project status"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloudPro tip:Try "amplify add api" to create a backend API and then "amplify push" to deploy everything

This will initialise Amplify in your React app. Follow the prompts to configure Amplify.

Step 5: Add a GraphQL API

With Amplify initialised, we can now add a GraphQL API. Run the following command in your terminal:

amplify add api

~/Documents/amplify-hackathon/amplify-react-graphql-demo  main !4 ?1  amplify add api                                                                                                    39s  07:28:44? Select from one of the below mentioned services: GraphQL? Here is the GraphQL API that we will create. Select a setting to edit or continue Continue? Choose a schema template: Single object with fields (e.g., Todo with ID, name, description)  WARNING: your GraphQL API currently allows public create, read, update, and delete access to all models via an API Key. To configure PRODUCTION-READY authorization rules, review: https://docs.amplify.aws/cli/graphql/authorization-rules GraphQL schema compiled successfully.Edit your schema at ~/Documents/amplify-hackathon/amplify-react-graphql-demo/amplify/backend/api/amplifyhackathon/schema.graphql or place .graphql files in a directory at ~/Documents/amplify-hackathon/amplify-react-graphql-demo/amplify/backend/api/amplifyhackathon/schema Do you want to edit the schema now? (Y/n)  yesEdit the file in your editor: ~/Documents/amplify-hackathon/amplify-react-graphql-demo/amplify/backend/api/amplifyhackathon/schema.graphql Successfully added resource amplifyhackathon locally Some next steps:"amplify push" will build all your local backend resources and provision it in the cloud"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloudThis will prompt you to choose a type of API. Select GraphQL and follow the

This will prompt you to choose a type of API. Select GraphQL and follow the prompts to configure your API.

Step 6: Generate GraphQL schema and queries

Now that we have added a GraphQL API, lets generate the schema and queries. Run the following command in your terminal:

amplify codegen

This will generate the GraphQL schema and queries based on your API.

Step 7: Create a React component

With the GraphQL schema and queries generated, lets create a React component that will display the data from our API. Create a new file called Data.js in the src directory and add the following code:

import React, { useState, useEffect } from 'react';import { API } from 'aws-amplify';import { listData } from './graphql/queries';function Data() {  const [data, setData] = useState([]);  useEffect(() => {    fetchData();  }, []);  async function fetchData() {    const apiData = await API.graphql({ query: listData });    setData(apiData.data.listData.items);  }  return (    <div>      {data.map(item => (        <div key={item.id}>          <h2>{item.title}</h2>          <p>{item.description}</p>        </div>      ))}    </div>  );}export default Data;

This component will fetch the data from our API and display it in the browser.

Step 8: Update App.js

With the Data component created, let's update App.js to render it. Replace the contents of App.js with the following code:

import React from 'react';import Data from './Data';function App() {  return (<div className="App">      <Data />    </div>  );}export default App;

Step 9: Deploy the application

With the React app and GraphQL API set up, lets deploy the application. Run the following command in your terminal:

amplify push

~/Documents/amplify-hackathon/amplify-react-graphql-demo  main !4 ?1  amplify push                                                                                                       55s  07:30:17 Building resource api/amplifyhackathon  WARNING: your GraphQL API currently allows public create, read, update, and delete access to all models via an API Key. To configure PRODUCTION-READY authorization rules, review: https://docs.amplify.aws/cli/graphql/authorization-rules GraphQL schema compiled successfully.Edit your schema at /Users/macpro/Documents/amplify-hackathon/amplify-react-graphql-demo/amplify/backend/api/amplifyhackathon/schema.graphql or place .graphql files in a directory at /Users/macpro/Documents/amplify-hackathon/amplify-react-graphql-demo/amplify/backend/api/amplifyhackathon/schema Successfully pulled backend environment dev from the cloud. Building resource api/amplifyhackathon  WARNING: your GraphQL API currently allows public create, read, update, and delete access to all models via an API Key. To configure PRODUCTION-READY authorization rules, review: https://docs.amplify.aws/cli/graphql/authorization-rules GraphQL schema compiled successfully.Edit your schema at /Users/macpro/Documents/amplify-hackathon/amplify-react-graphql-demo/amplify/backend/api/amplifyhackathon/schema.graphql or place .graphql files in a directory at /Users/macpro/Documents/amplify-hackathon/amplify-react-graphql-demo/amplify/backend/api/amplifyhackathon/schema    Current Environment: dev Category  Resource name     Operation  Provider plugin    Api       amplifyhackathon  Create     awscloudformation  Are you sure you want to continue? (Y/n)  yes  WARNING: your GraphQL API currently allows public create, read, update, and delete access to all models via an API Key. To configure PRODUCTION-READY authorization rules, review: https://docs.amplify.aws/cli/graphql/authorization-rules GraphQL schema compiled successfully.Edit your schema at /Users/macpro/Documents/amplify-hackathon/amplify-react-graphql-demo/amplify/backend/api/amplifyhackathon/schema.graphql or place .graphql files in a directory at ~/Documents/amplify-hackathon/amplify-react-graphql-demo/amplify/backend/api/amplifyhackathon/schema Building resource api/amplifyhackathon  WARNING: your GraphQL API currently allows public create, read, update, and delete access to all models via an API Key. To configure PRODUCTION-READY authorization rules, review: https://docs.amplify.aws/cli/graphql/authorization-rules GraphQL schema compiled successfully.Edit your schema at ~/Documents/amplify-hackathon/amplify-react-graphql-demo/amplify/backend/api/amplifyhackathon/schema.graphql or place .graphql files in a directory at ~/Documents/amplify-hackathon/amplify-react-graphql-demo/amplify/backend/api/amplifyhackathon/schema? Do you want to generate code for your newly created GraphQL API Yes? Choose the code generation language target typescript? Enter the file name pattern of graphql queries, mutations and subscriptions src/API.ts? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions Yes? Enter maximum statement depth [increase from default if your schema is deeply nested] 2? Enter the file name for the generated code src/API.tsDeployment completed.Deploying root stack amplifyhackathon [ ---------------------------------------- ] 0/2 amplify-amplifyhackathon-dev- AWS::CloudFormation::Stack     UPDATE_IN_PROGRESS             Tue Mar 28 2023 07:33:58 apiamplifyhackathon            AWS::CloudFormation::Stack     CREATE_IN_PROGRESS             Tue Mar 28 2023 07:34:02Deployed api amplifyhackathon [ ======================================== ] 6/6 GraphQLAPI                     AWS::AppSync::GraphQLApi       CREATE_COMPLETE                Tue Mar 28 2023 07:34:09 GraphQLAPINONEDS95A13CF0       AWS::AppSync::DataSource       CREATE_COMPLETE                Tue Mar 28 2023 07:34:13 GraphQLAPIDefaultApiKey215A6D AWS::AppSync::ApiKey           CREATE_COMPLETE                Tue Mar 28 2023 07:34:13 GraphQLAPITransformerSchema3C AWS::AppSync::GraphQLSchema    CREATE_COMPLETE                Tue Mar 28 2023 07:35:14 Todo                           AWS::CloudFormation::Stack     CREATE_COMPLETE                Tue Mar 28 2023 07:36:05 CustomResourcesjson            AWS::CloudFormation::Stack     CREATE_COMPLETE                Tue Mar 28 2023 07:36:18 Generated GraphQL operations successfully and saved at src Code generated successfully and saved in file src/API.tsDeployment state saved successfully.GraphQL endpoint: https://xxxxxxxxxx.appsync-api.us-east-1.amazonaws.com/graphqlGraphQL API KEY: da2-xxxxxxxxxxxxxxxxxGraphQL transformer version: 2

This will deploy the application to AWS and make it available online.

Step 10: Clean-up

Within the project directory that you want to delete, run the following amplify delete command:

For locally accessible projects
Within the project directory that you want to delete, run the following amplify delete command:

amplify delete

For cloud-based projects

  1. Pull the backend environment associated with your application to your local environment by running the following amplify pull command:
amplify pull
  1. Within the project directory that you want to delete, run the following amplify delete command:
amplify delete

Output:

~/Documents/amplify-hackathon/amplify-react-graphql-demo  main !4 ?7  amplify delete                                                                                                  5m 36s  07:37:13 Are you sure you want to continue? This CANNOT be undone. (This will delete all the environments of the project from the cloud and wipe out all the local files created by Amplify CLI) (y/N)  yes Deleting resources from the cloud. This will take a few minutes.Deleting env: dev. Project deleted in the cloud. Project deleted locally.

Conclusion

In this blog post, I walked through the process of building and launching a serverless GraphQL React application with AWS Amplify. I started by creating a new React app, installing the Amplify CLI, configuring Amplify, adding a GraphQL API, generating the GraphQL schema and queries, creating a React component to display the data, updating App.js to render the component, and finally deploying the application. I have also covered how to clean up the environment we have created in this demo to avoid unnecessary costs. I hope this guide helps you get started with serverless development using AWS Amplify.


Original Link: https://dev.to/aws-heroes/building-and-launching-a-serverless-graphql-react-application-with-aws-amplify-a-step-by-step-guide-366k

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To