• 沒有找到結果。

Add a GraphQL backend

在文檔中 AWS Amplify (頁 18-111)

Step 3: Add a GraphQL backend

1. Let’s add a GraphQL API backend with a NoSQL database to your app. To start, clone the repository that was forked in your account.

git clone [email protected]:<username>/create-react-app-auth-amplify.git cd create-react-app-auth-amplify

2. From the Backend environments tab, choose Edit backend. As a pre-requisite, follow the instructions to install and configure the Amplify CLI. The Amplify command line toolchain allows you to edit the backend you just created to add more functionality such as GraphQL/REST APIs, analytics, and storage. Once the Amplify CLI is configured, copy the amplify pull command to connect to this backend from your local machine.

amplify pull --appId XXXXXXXX --envName devw

3. Add the GraphQL API using the default todo example. Learn more about modeling your backend with the GraphQL transform.

amplify add api

? Please select from one of the below mentioned services GraphQL

? Provide API name: todo

? Choose the default authorization type for the API API key

? Enter a description for the API key:

? After how many days from now the API key should expire (1-365): 7

? Do you want to configure advanced settings for the GraphQL API No, I am done.

? Do you have an annotated GraphQL schema? No

? Do you want a guided schema creation? (Y/n) Y

? What best describes your project: Single object with fields (e.g., “Todo” with ID, name, description)

? Do you want to edit the schema now? No ...

GraphQL schema compiled successfully.

4. To deploy these changes to the cloud run the following commands.

Next steps: Set up feature branch deployments

amplify push

Current Environment: devw

| Category | Resource name | Operation | Provider plugin |

| --- | --- | --- | --- |

| Api | todo | Create | awscloudformation |

| Auth | cognitocf0c6096 | No Change | awscloudformation |

? Are you sure you want to continue? (Y/n) Y ..

✔ Generated GraphQL operations successfully and saved at src/graphql

✔ All resources are updated in the cloud

GraphQL endpoint: https://gumwpbojgraj5b547y5d3shurq.appsync-api.us-west-2.amazonaws.com/

graphql

GraphQL API KEY: da2-vlthvw5qcffxzl2hibgowv3rdq

5. Visit the Amplify Console to view the added API category. Choosing the API category will allow you to navigate to the AppSync Console (to write queries or mutations performing CRUD operations), or the DynamoDB Console (to view your Todo table).

6. Use the Amplify GraphQL client to write frontend code that lists and updates the todos. To deploy the updates to your frontend, simply commit your code and a new build will be triggered in the Amplify Console.

Next steps: Set up feature branch deployments

Follow our recommended workflow to set up feature branch deployments with multiple backend environments.

What is server-side rendering

Deploy and host server-side rendered apps with Amplify

You can use AWS Amplify to deploy and host web apps that use server-side rendering (SSR). Currently, Amplify supports SSR apps created using the Next.js framework. When you deploy your app, Amplify automatically detects SSR–you do not have to perform any manual configuration in the AWS

Management Console.

To learn about how Amplify supports SSR, review the following topics.

Topics

• What is server-side rendering (p. 14)

• Amplify support for Next.js SSR (p. 14)

• Pricing for Next.js SSR apps (p. 15)

• Deploying a Next.js SSR app with Amplify (p. 16)

• Adding SSR functionality to a static Next.js app (p. 17)

• Updating the Next.js version for an existing app (p. 18)

• AWS Identity and Access Management permissions for SSR apps (p. 19)

• Troubleshooting SSR deployment issues (p. 20)

What is server-side rendering

Previously, Amplify supported the deployment and hosting of static web apps only. These include apps created with single-page application (SPA) frameworks such as React, and apps created with a static site generator (SSG) such as Gatsby. Static web apps consist of a combination of files, such as HTML, CSS, and JavaScript files, that are stored on a content delivery network (CDN). When a client browser makes a request to the website, the server returns a page to the client with an HTTP response and the client browser interprets the content and displays it to the user.

Amplify now supports web apps with server-side rendering (SSR). When a client sends a request to an SSR page, the HTML for the page is created on the server on each request. SSR enables a developer to customize a website per request and per user. In addition, SSR can improve performance and search engine optimization (SEO) for a website.

Amplify support for Next.js SSR

Currently Amplify supports deployment and hosting for server-side rendered (SSR) web apps created using Next.js only. Next.js is a React framework for developing SPAs with JavaScript. You can deploy apps built with Next.js 11 with features such as image and script optimization, and Incremental Static Regeneration (ISR).

Developers can use Next.js to combine static site generation (SSG), and SSR in a single project. SSG pages are prerendered at build time, and SSR pages are prerendered at request time.

Supported and unsupported Next.js features

Prerendering can improve performance and search engine optimization. Because Next.js prerenders all pages on the server, the HTML content of each page is ready when it reaches the client's browser. This content can also load faster. Faster load times improve the end user's experience with a website and positively impact the site's SEO ranking. Prerendering also improves SEO by enabling search engine bots to find and crawl a website's HTML content easily.

Next.js provides built-in analytics support for measuring various performance metrics, such as Time to first byte (TTFB) and First contentful paint (FCP). For more information about Next.js, see Getting started on the Next.js website.

Supported and unsupported Next.js features

Amplify supports apps built with the Next.js major versions 9, 10, and 11. The following list describes the specific features that Amplify supports and does not support.

Supported features

• Server-side rendered pages (SSR)

• Static pages

• API routes

• Dynamic routes

• Catch all routes

• SSG (Static generation)

• Incremental Static Regeneration (ISR)

• Internationalized (i18n) sub-path routing

• Environment variables

• Image optimization. The size of the image can't exceed 1 MB. The AVIF and WebP image formats are not supported.

Unsupported features

• Internationalized (i18n) domain routing

• Internationalized (i18n) automatic locale detection

• Middleware

Pricing for Next.js SSR apps

When deploying your Next.js SSR app, Amplify creates additional backend resources in your AWS account, including:

• An Amazon Simple Storage Service (Amazon S3) bucket that stores the resources for your app's static assets. For information about Amazon S3 charges, see Amazon S3 Pricing.

• An Amazon CloudFront distribution to serve the app. For information about CloudFront charges, see Amazon CloudFront Pricing.

• Four Lambda@Edge functions to customize the content that CloudFront delivers.

When you use the Amplify Framework (Libraries, CLI, UI components), you pay only for the underlying AWS services you use. For more information about Amplify deployment and hosting charges, see AWS Amplify Pricing.

Deploying a Next.js SSR app with Amplify

Deploying a Next.js SSR app with Amplify

To deploy a Next.js SSR app with Amplify, follow the same workflow for setting up a static app with continuous deployments. For detailed instructions, see Getting started with existing code (p. 3). Note that you can't set up an SSR app in Amplify with manual deploys (p. 67).

Package.json file settings

When you deploy a Next.js app, Amplify inspects the app's build script in the package.json file to detect whether the app is SSR or SSG.

The following is an example of the build script for a Next.js SSR app. The build script "next build"

indicates that the app supports both SSG and SSR pages.

"scripts": {

"dev": "next dev", "build": "next build", "start": "next start"

},

The following is an example of the build script for a Next.js SSG app. The build script "next build &&

next export" indicates that the app supports only SSG pages.

"scripts": {

"dev": "next dev",

"build": "next build && next export", "start": "next start"

},

Amplify build settings

After inspecting your app's package.json file to determine whether you are deploying an SSG or SSR app, Amplify checks the build settings for the app. You can save build settings in the Amplify console or in an amplify.yml file in the root of your repository. For more information, see Configuring build settings (p. 40).

If Amplify detects that you are deploying a Next.js SSR app, and no amplify.yml file is present, it generates a buildspec for the app and sets baseDirectory to .next. If you are deploying an app where an amplify.yml file is present, the build settings in the file override any build settings in the console.

Therefore, you must manually set the baseDirectory to .next in the file.

The following is an example of the build settings for an app where baseDirectory is set to .next. This indicates that the build artifacts are for a Next.js app that supports SSG and SSR pages.

version: 1

Adding SSR functionality to a static Next.js app

If Amplify detects that you are deploying an SSG app, it generates a buildspec for the app and sets baseDirectory to out. If you are deploying an app where an amplify.yml file is present, you must manually set the baseDirectory to out in the file.

The following is an example of the build settings for an app where baseDirectory is set to out. This indicates that the build artifacts are for a Next.js app that supports only SSG pages.

version: 1

Adding SSR functionality to a static Next.js app

You can add SSR functionality to an existing static (SSG) Next.js app deployed with Amplify. This requires three steps. First, add a service role to the app. Next, update the output directory in the app's build settings. Lastly, update the app's package.json file to indicate that the app uses SSR.

Add a service role

A service role is the AWS Identity and Access Management (IAM) role that Amplify assumes when calling other services on your behalf. Follow these steps to add a service role to an SSG app that's already deployed with Amplify.

To add a service role

1. Sign in to the AWS Management Console and open the Amplify console.

2. If you haven't already created a service role in your Amplify account, see create a service role (p. 105) to complete this prerequisite step. See AWS Identity and Access Management permissions for SSR apps (p. 19) for information about the permissions required to deploy an SSR app.

3. Choose the static Next.js app that you want to add a service role to.

4. In the navigation pane, choose App settings, General.

5. On the App details page, choose Edit

6. For Service role, choose the name of an existing service role or the name of the service role that you created in step 2.

Update build settings

7. Choose Save.

Update build settings

Before you redeploy your app with SSR functionality, you must update the build settings for the app to set the output directory to .next. You can edit the build settings in the Amplify console or in an amplify.yml file stored in your repo. For more information see, Configuring build settings (p. 40).

The following is an example of the build settings for an app where baseDirectory is set to .next.

version: 1

After you add a service role and update the build settings, update the app's package.json file. As in the following example, set the build script to "next build" to indicate that the Next.js app supports both SSG and SSR pages.

"scripts": {

"dev": "next dev", "build": "next build", "start": "next start"

},

Amplify detects the change to the package.json file in your repo and redeploys the app with SSR functionality.

Updating the Next.js version for an existing app

When you deploy a new Next.js app with Amplify, by default Amplify uses the most recent supported version of Next.js. Currently, Amplify supports Next.js version 11.

For an existing app, use the following instructions to change the version of Next.js that Amplify uses to build the app.

To update the Next.js version for an existing app

1. Sign in to the AWS Management Console and open the Amplify console.

2. Choose the Next.js app that you want to update.

AWS Identity and Access Management permissions for SSR apps 3. In the navigation pane, choose App settings, Build settings.

4. On the Build settings page, in the Build image settings section, choose Edit.

5. In the Edit build image settings dialog box, expand the Add package version override list, and choose Next.js version.

6. For Version, do one of the following:

Enter 9 for support up to Next.js version 9.4.x.

Enter 10 for support for Next.js versions 9.4.x to 10.x.x.

Enter 11 for support for Next.js versions 11.x to 11.1.3.

Enter latest, to always upgrade to the latest Next.js version that Amplify supports.

7. Choose Save. The next time the app builds, it can use the features supported by the Next.js version you specified in step 6.

AWS Identity and Access Management permissions for SSR apps

Amplify requires AWS Identity and Access Management (IAM) permissions to deploy an SSR app. Without the required minimum permissions, you will get an error when you try to deploy your SSR app. To provide Amplify with the required permissions, you must create an IAM service role that Amplify assumes when calling other services on your behalf. See create a service role (p. 105) for detailed instructions on creating an Amplify-Backend Deployment service role that Amplify uses to create and manage AWS resources. IAM attaches the AdministratorAccess-Amplify managed policy to the Amplify-Backend Deployment service role.

The AdministratorAccess-Amplify managed policy provides access to multiple AWS services, including IAM actions. and should be considered as powerful as the AdministratorAccess policy. This policy provides more permissions than required to deploy your SSR app. It is recommended that you follow the best practice of granting least privilege and reduce the permissions granted to the service role.

Instead of granting administrator access permissions to your service role, you can create your own customer managed IAM policy that grants only the permissions required to deploy your SSR app. See Creating IAM policies in the IAM User Guide for instructions on creating a customer managed policy. Add the following list of minimum permissions required to deploy an SSR app to the policy you create.

acm:DescribeCertificate

Troubleshooting SSR deployment issues

To reduce the scope of permissions granted to an Amplify service role in your account, edit the role to remove the AdministratorAccess-Amplify policy and attach your new SSR-specific policy.

Troubleshooting SSR deployment issues

If you experience unexpected issues when deploying an SSR app with Amplify, review the following troubleshooting topics.

Topics

• Your output directory is overridden (p. 21)

• You get a 404 error after deploying your SSR site (p. 21)

• Your app is missing the rewrite rule for CloudFront SSR distributions (p. 21)

• Your app is too large to deploy (p. 22)

• Your app has both SSR and SSG branches (p. 22)

• Your app stores static files in a folder with a reserved path (p. 22)

Your output directory is overridden

• Your app has reached a CloudFront limit (p. 22)

• Environment variables are not carried through to Lambda functions (p. 22)

• Lambda@Edge functions are created in the US East (N. Virginia) Region (p. 23)

• Your Next.js app uses unsupported features (p. 23)

• Images in your Next.js app aren't loading (p. 23)

• Unsupported Regions (p. 23)

Your output directory is overridden

The output directory for a Next.js app deployed with Amplify must be set to .next. If your app's output directory is being overridden, check the next.config.js file. To have the build output directory default to .next, remove the following line from the file:

distDir: 'build'

Verify that the output directory is set to .next in your build settings. For information about viewing your app's build settings, see Configuring build settings (p. 40).

The following is an example of the build settings for an app where baseDirectory is set to .next.

version: 1

You get a 404 error after deploying your SSR site

If you get a 404 error after deploying your site, the issue could be caused by your output directory being overridden. To check your next.config.js file and verify the correct build output directory in your app's build spec, follow the steps in the previous topic, Your output directory is overridden (p. 21).

Your app is missing the rewrite rule for CloudFront SSR distributions

When you deploy an SSR app, Amplify creates a rewrite rule for your CloudFront SSR distributions. If you can't access your app in a web browser, verify that the CloudFront rewrite rule exists in your AWS account. If it's missing, you can either add it manually or redeploy your app.

To view or edit an app's rewrite and redirect rules in the Amplify console, in the navigation pane, choose App settings, then Rewrites and redirects. The following screenshot shows an example of the rewrite rules that Amplify creates for you when you deploy an SSR app.

Your app is too large to deploy

Your app is too large to deploy

Amplify limits the size of an SSR deployment to 50 MB. If you try to deploy a Next.js SSR app to Amplify and get a RequestEntityTooLargeException error, your app is too large to deploy. You can attempt to work around this issue by adding cache cleanup code to your next.config.js file.

The following is an example of code in the next.config.js file that performs cache cleanup.

module.exports = {

webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => { config.optimization.splitChunks.cacheGroups = { }

config.optimization.minimize = true;

return config },

}

Your app has both SSR and SSG branches

You can't deploy an app that has both SSR and SSG branches. If you need to deploy both SSR and SSG branches, you must deploy one app that uses only SSR branches and another app that uses only SSG branches.

Your app stores static files in a folder with a reserved path

Next.js can serve static files from a folder named public that's stored in the project's root directory.

When you deploy and host a Next.js app with Amplify, your project can't include folders with the path public/static. Amplify reserves the public/static path for use when distributing the app. If your app includes this path, you must rename the static folder before deploying with Amplify.

Your app has reached a CloudFront limit

CloudFront service quotas limit your AWS account to 25 distributions with attached Lambda@Edge functions. If you exceed this quota, you can either delete any unused CloudFront distributions from your account or request a quota increase. For more information, see Requesting a quota increase in the Service Quotas User Guide.

Environment variables are not carried through to Lambda functions

Environment variables that you specify in the Amplify console for an SSR app are not carried through to the app's AWS Lambda functions. Use the following instructions to add environment variables that you can reference from your Lambda functions.

Lambda@Edge functions are created in the US East (N. Virginia) Region To add environment variables to a Next.js SSR app

1. Follow the Set environment variables (p. 84) instructions to add environment variables to your app in the Amplify console.

2. Open the next.config.js file for your app. If this file doesn't exist, create it.

3. Update the next.config.js file with the environment variables that you added in step 1. For example, if you created an environment variable named MY_ENV_VAR, add the following code to your next.config.js file:

module.exports = { env: {

MY_ENV_VAR: process.env.MY_ENV_VAR }

};

4. Rebuild your app. You can now reference the environment variables you added, such as process.env.MY_ENV_VAR, in the app's Lambda functions.

Lambda@Edge functions are created in the US East (N. Virginia) Region

When you deploy a Next.js app, Amplify creates Lambda@Edge functions to customize the content that CloudFront delivers. Lambda@Edge functions are created in the US East (N. Virginia) Region, not the

When you deploy a Next.js app, Amplify creates Lambda@Edge functions to customize the content that CloudFront delivers. Lambda@Edge functions are created in the US East (N. Virginia) Region, not the

在文檔中 AWS Amplify (頁 18-111)

相關文件