diff --git a/src/fragments/gen2/quickstart/build-a-backend.mdx b/src/fragments/gen2/quickstart/build-a-backend.mdx new file mode 100644 index 00000000000..94798b7c800 --- /dev/null +++ b/src/fragments/gen2/quickstart/build-a-backend.mdx @@ -0,0 +1,218 @@ +## Build a backend + +Next, we will add data and auth capabilities to the app. + +### Add data + +Each of the `resource.ts` files is where you _define_ the corresponding backend resource. If you open up the `/amplify/data/resource.ts` file in your text editor, you will see some generated code already there: + +```ts showLineNumbers title="amplify/data/resource.ts" +// amplify/data/resource.ts +import { type ClientSchema, a, defineData } from '@aws-amplify/backend'; + +/*== STEP 1 =============================================================== +The section below creates a Todo database table with a "content" field. Try +adding a new "isDone" field as a boolean. The authorization rules below +specify that owners, authenticated via your Auth resource, can "create", +"read", "update", and "delete" their own records. Public users, +authenticated via an API key, can only "read" records. +=========================================================================*/ +const schema = a.schema({ + Todo: a + .model({ + content: a.string() + }) + .authorization([a.allow.owner(), a.allow.public().to(['read'])]) +}); + +export type Schema = ClientSchema; + +export const data = defineData({ + schema, + authorizationModes: { + defaultAuthorizationMode: 'apiKey', + // API Key is used for a.allow.public() rules + apiKeyAuthorizationMode: { + expiresInDays: 30 + } + } +}); + +/*== STEP 2 =============================================================== +Go to your frontend source code. From your client-side code, generate a +Data client to make CRUDL requests to your table. (THIS SNIPPET WILL ONLY +WORK IN THE FRONTEND CODE FILE.) + +Using JavaScript or Next.js React Server Components, Middleware, Server +Actions, or Pages Router? Review how to generate Data clients for those use +cases: https://docs.amplify.aws/gen2/build-a-backend/data/connect-to-API/ +=========================================================================*/ + +/* +"use client" +import { generateClient } from "aws-amplify/data"; +import { type Schema } from "@/amplify/data/resource"; + +const client = generateClient() // use this Data client for CRUDL requests +*/ + +/*== STEP 3 =============================================================== +Fetch records from the database and use them in your frontend component. +(THIS SNIPPET WILL ONLY WORK IN THE FRONTEND CODE FILE.) +=========================================================================*/ + +/* For example, in a React component, you can use this snippet in your + function's RETURN statement */ +// const { data: todos } = client.models.Todo.list() + +// return +``` + + + The schema generated by Amplify is for a to-do app. A schema is a blueprint + for how our app's data will be organized. Within the schema, we will define + models which will correspond to a database table—`Todo` in the above code. + Finally, we will define fields which are attributes that each data instance + will have—in the generated code, the fields are `name` and `description`. Each + field will have a type attached to it—in the above examples, we are stating + that both `name` and `description` are strings. + + +Let's make a quick change to our data model and add a `done` field. This will be a `boolean`, which can be set to `true` or `false` depending on whether our to-do list item is complete. Let's also add a priority field, which will be an `enum`. This field type will allow for just a few options to be stored—low, medium, or high. + +We've removed the default comments to shorten the code below; however, you can choose to keep them for help in connecting to your frontend resources. + +```diff title="amplify/data/resource.ts" +// amplify/data/resource.ts +import { type ClientSchema, a, defineData } from '@aws-amplify/backend'; + +// ... + +const schema = a.schema({ + Todo: a + .model({ + content: a.string(), ++ done: a.boolean(), ++ priority: a.enum(['low', 'medium', 'high']) + }) + .authorization([a.allow.owner(), a.allow.public().to(['read'])]), +}); + +export type Schema = ClientSchema; + +export const data = defineData({ + schema, + authorizationModes: { + defaultAuthorizationMode: 'apiKey', + // API Key is used for a.allow.public() rules + apiKeyAuthorizationMode: { + expiresInDays: 30, + }, + }, +}); + +// ... +``` + +Once you save your changes to the data model, your changes will be deployed in seconds within your cloud sandbox. + +Our Todo data model also has authorization set up. Our model has the `authorization` method chained to it, which you can add rules to. In our example, we are allowing an owner, or the person who creates the Todo instance, to perform all actions on the data they own. We are also allowing all page viewers, including unauthenticated users, to read data. These can be modified; for example, we could remove the `.to(['read'])` and allow all visitors to perform all actions on data. We could also add permissions for signed-in users or users who belong to user groups such as `Admin`. You can learn more about all options for authorization in the [customize your auth rules](/gen2/build-a-backend/data/customize-authz/) section of the docs. + +Let's remove public access. + +```js +.authorization([a.allow.owner()]), +``` + +Then, you will see the `defineData` function, which has our schema and authorization configuration passed in as arguments. We have an `apiKey` set up to enable public access. Let's change our `defaultAuthorizationMode` to `userPool` instead so that the default is to use user authentication. + +```js +export const data = defineData({ + schema, + authorizationModes: { + defaultAuthorizationMode: 'userPool' + } +}); +``` + +The definitions are imported and set in the `backend` file. We will not need to change anything in this file right now, but you can see its contents, which define a backend with our data and auth configurations from their respective files. + +```ts title="amplify/backend.ts" +// amplify/backend.ts +import { defineBackend } from '@aws-amplify/backend'; +import { auth } from './auth/resource.js'; +import { data } from './data/resource.js'; + +defineBackend({ + auth, + data +}); +``` + +### Add authentication + +Now let's work on our authentication configuration. Similar to the `data/resource.ts` we just worked on, the `auth/resource.ts` file has code to define our authentication configuration. In this case, setting the authentication method to log in with email. + +```ts title="amplify/auth/resource.ts" +// amplify/auth/resource.ts +import { defineAuth } from '@aws-amplify/backend'; + +/** + * Define and configure your auth resource + * When used alongside data, it is automatically configured as an auth provider for data + * @see https://docs.amplify.aws/gen2/build-a-backend/auth + */ +export const auth = defineAuth({ + loginWith: { + email: true, + // add social providers + externalProviders: { + /** + * first, create your secrets using `amplify sandbox secret` + * then, import `secret` from `@aws-amplify/backend` + * @see https://docs.amplify.aws/gen2/deploy-and-host/sandbox-environments/features/#setting-secrets + */ + // loginWithAmazon: { + // clientId: secret('LOGINWITHAMAZON_CLIENT_ID'), + // clientSecret: secret('LOGINWITHAMAZON_CLIENT_SECRET'), + // } + } + }, + /** + * enable multifactor authentication + * @see https://docs.amplify.aws/gen2/build-a-backend/auth/manage-mfa + */ + // multifactor: { + // mode: 'OPTIONAL', + // sms: { + // smsMessage: (code) => `Your verification code is ${code}`, + // }, + // }, + userAttributes: { + /** request additional attributes for your app's users */ + // profilePicture: { + // mutable: true, + // required: false, + // }, + } +}); +``` + +Let's customize the verification email for our app. We can add a subject line by defining an object with email authentication properties. Again, we have removed comments for brevity. + +```diff title="amplify/auth/resource.ts" +// amplify/auth/resource.ts +import { defineAuth } from '@aws-amplify/backend'; + +export const auth = defineAuth({ + loginWith: { +- email: true, ++ email: { ++ verificationEmailSubject: 'Welcome! Verify your email!' ++ }, + // add social providers + externalProviders: { + } + } +}); +``` diff --git a/src/fragments/gen2/quickstart/create-nextjs-project.mdx b/src/fragments/gen2/quickstart/create-nextjs-project.mdx new file mode 100644 index 00000000000..e095f8cf922 --- /dev/null +++ b/src/fragments/gen2/quickstart/create-nextjs-project.mdx @@ -0,0 +1,58 @@ +## Create a project + +First, you will need to create a new Next.js app. The following command will create a Next.js app in a directory called `next-amplify-gen2` that uses the **App Router**. + +```bash +npm create next-app@14 -- next-amplify-gen2 --typescript --eslint --app --no-src-dir --no-tailwind --import-alias '@/*' +cd next-amplify-gen2 +``` + +The easiest way to get started with AWS Amplify is through npm with `create-amplify`. + +```bash +npm create amplify@latest +``` + +```console +? Where should we create your project? (.) # press enter +``` + +Running this command will scaffold a lightweight Amplify project in your current project with the following files: + +```text +├── amplify/ +│ ├── auth/ +│ │ └── resource.ts +│ ├── data/ +│ │ └── resource.ts +│ ├── backend.ts +│ └── package.json +├── node_modules/ +├── .gitignore +├── package-lock.json +├── package.json +└── tsconfig.json +``` + +## Start local dev server + +Let's start a local dev server for your app development. For the frontend, run `npm run dev` to spin up a `localhost` dev server with the default Next.js template. + +```bash +npm run dev +``` + + + +Now [configure your AWS account to use Amplify](/gen2/start/account-setup/). Note: If you already have an AWS profile with credentials on your local machine, and you have configured the corresponding AWS profile with the **AmplifyBackendDeployFullAccess** permission policy, you can skip this step. + + + +For the backend, we're going to start a cloud sandbox environment. Amplify gives every developer a personal cloud sandbox environment that provides isolated development spaces to rapidly build, test, and iterate. When you're working with a team, each developer will have their own personal cloud sandbox. In a new terminal window, run the following command: + +```bash +npx amplify sandbox +``` +Do not use cloud sandbox environments in production. + +You should now have these two commands running concurrently in different terminal windows. diff --git a/src/fragments/gen2/quickstart/deploy-and-host.mdx b/src/fragments/gen2/quickstart/deploy-and-host.mdx new file mode 100644 index 00000000000..55be5ed2b1e --- /dev/null +++ b/src/fragments/gen2/quickstart/deploy-and-host.mdx @@ -0,0 +1,35 @@ +## Deploy and host a fullstack branch + +Now that your app is working, let's deploy it to a shared fullstack branch so you can share the project with your team. Amplify offers a fully managed hosting service with CI/CD built in, making it easy to set up production and staging environments with Git branches. In Gen 2, every Git branch in your repository maps 1:1 to a fullstack branch in Amplify. + +### Create remote Git repository + +If you already have your project remotely hosted in a Git repository, you can skip this step. Otherwise, navigate to your preferred Git provider, and add your project to a new repository. Amplify supports [GitHub](https://docs.github.com/en/get-started/quickstart/create-a-repo), [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-create-repository.html), [GitLab](https://docs.gitlab.com/ee/user/project/index.html), and [Bitbucket](https://support.atlassian.com/bitbucket-cloud/docs/create-a-git-repository/). + +### Connect branch in the Amplify console + +1. To get started with Gen 2, log in to the [AWS console](https://console.aws.amazon.com/console/home?#amplify) and navigate to your preferred Region. (The Amplify console is available in [19 Regions](https://docs.aws.amazon.com/general/latest/gr/amplify.html#amplify_region)). +2. If you have never created apps with Amplify before, choose _Create an app_ from the purple banner (top screenshot). If you have Amplify apps, you can find the option under *New app > Build an app (Gen 2)*. + +![gen2](/images/gen2/getting-started/console1.png) + +3. In the Git provider screen, choose _Option 2: Start with an existing app_. Connect the repository you just deployed and pick a branch. + +Next.js 14 apps require a [minimum node version](https://nextjs.org/blog/next-14#other-changes) of 18.17 at build time. + +4. Under _Advanced settings_, navigate to _Build Image_ and enter `amplify:al2023`. The Amplify Amazon Linux 2023 build image supports Node.js versions 18 and 20 at build time. You can specify the Node.js version during your build via [live package updates](https://docs.aws.amazon.com/amplify/latest/userguide/custom-build-image.html#setup-live-updates) or [nvm](https://github.com/nvm-sh/nvm). Amplify Hosting will automatically deploy your compute runtime to match the Node.js version used at build time. + +![Amplify Gen 2 console showing the "Advanced Settings" view with "amplify:al2023" specified for build image](/images/gen2/getting-started/console4.png) + +If you have an existing Gen 2 application, you can modify the build image by navigating to _Hosting_ -> _Environment Variables_ and create a new environment variable `_CUSTOM_IMAGE` with the value `amplify:al2023`, then redeploy the build. + +5. Review all of your settings to ensure everything is set up correctly. Choose _Save and deploy_ to deploy your web app. + + + + +### Manage fullstack branch + +The new Amplify console gives you a central place to manage your branches, hosting settings, CI/CD builds, and backend resources. Even though you can access backend resources directly from AWS service consoles, the Amplify console offers built-in user and data administration. diff --git a/src/fragments/gen2/quickstart/prerequisites.mdx b/src/fragments/gen2/quickstart/prerequisites.mdx new file mode 100644 index 00000000000..aaa8b136434 --- /dev/null +++ b/src/fragments/gen2/quickstart/prerequisites.mdx @@ -0,0 +1,8 @@ +## Prerequisites + +Before you get started, make sure you have the following installed: + +- [Node.js](https://nodejs.org/) v18.17 or later +- [npm](https://www.npmjs.com/) v9 or later +- [git](https://git-scm.com/) v2.14.1 or later +- You will also need to [create an AWS account](https://portal.aws.amazon.com/billing/signup). Note that AWS Amplify is part of the [AWS Free Tier](https://aws.amazon.com/amplify/pricing/). diff --git a/src/pages/gen2/start/quickstart/nextjs-app-router/index.mdx b/src/pages/gen2/start/quickstart/nextjs-app-router/index.mdx index 4e332a679b7..dcd40b1b8b0 100644 --- a/src/pages/gen2/start/quickstart/nextjs-app-router/index.mdx +++ b/src/pages/gen2/start/quickstart/nextjs-app-router/index.mdx @@ -13,292 +13,18 @@ export function getStaticProps(context) { This Quickstart guide will walk you through how to build a task list application with TypeScript, Next.js **App Router**, and React. If you are new to these technologies, we recommend you go through the official [React](https://react.dev/learn/tutorial-tic-tac-toe), [Next.js](https://nextjs.org/docs/getting-started/installation), and [TypeScript](https://www.typescriptlang.org/docs/handbook/typescript-from-scratch.html) tutorials first. -## Prerequisites +import prerequisites from 'src/fragments/gen2/quickstart/prerequisites.mdx'; -Before you get started, make sure you have the following installed: + -- [Node.js](https://nodejs.org/) v18.17 or later -- [npm](https://www.npmjs.com/) v9 or later -- [git](https://git-scm.com/) v2.14.1 or later -- You will also need to [create an AWS account](https://portal.aws.amazon.com/billing/signup). Note that AWS Amplify is part of the [AWS Free Tier](https://aws.amazon.com/amplify/pricing/). +import createProject from 'src/fragments/gen2/quickstart/create-nextjs-project.mdx'; -## Create a project + -First, you will need to create a new Next.js app. The following command will create a Next.js app in a directory called `next-amplify-gen2` that uses the **App Router**. +import buildABackend from 'src/fragments/gen2/quickstart/build-a-backend.mdx'; -```bash -npm create next-app@14 -- next-amplify-gen2 --typescript --eslint --app --no-src-dir --no-tailwind --import-alias '@/*' -cd next-amplify-gen2 -``` - -The easiest way to get started with AWS Amplify is through npm with `create-amplify`. - -```bash -npm create amplify@latest -``` - -```console -? Where should we create your project? (.) # press enter -``` - -Running this command will scaffold a lightweight Amplify project in your current project with the following files: - -```text -├── amplify/ -│ ├── auth/ -│ │ └── resource.ts -│ ├── data/ -│ │ └── resource.ts -│ ├── backend.ts -│ └── package.json -├── node_modules/ -├── .gitignore -├── package-lock.json -├── package.json -└── tsconfig.json -``` - -## Start local dev server - -Let's start a local dev server for your app development. For the frontend, run `npm run dev` to spin up a `localhost` dev server with the default Next.js template. - -```bash -npm run dev -``` - - - -Now [configure your AWS account to use Amplify](/gen2/start/account-setup/). Note: If you already have an AWS profile with credentials on your local machine, and you have configured the corresponding AWS profile with the **AmplifyBackendDeployFullAccess** permission policy, you can skip this step. - - - -For the backend, we're going to start a cloud sandbox environment. Amplify gives every developer a personal cloud sandbox environment that provides isolated development spaces to rapidly build, test, and iterate. When you're working with a team, each developer will have their own personal cloud sandbox. In a new terminal window, run the following command: - -```bash -npx amplify sandbox -``` -Do not use cloud sandbox environments in production. - -You should now have these two commands running concurrently in different terminal windows. - -## Build a backend - -Next, we will add data and auth capabilities to the app. - -### Add data - -Each of the `resource.ts` files is where you _define_ the corresponding backend resource. If you open up the `/amplify/data/resource.ts` file in your text editor, you will see some generated code already there: - -```ts showLineNumbers title="amplify/data/resource.ts" -// amplify/data/resource.ts -import { type ClientSchema, a, defineData } from '@aws-amplify/backend'; - -/*== STEP 1 =============================================================== -The section below creates a Todo database table with a "content" field. Try -adding a new "isDone" field as a boolean. The authorization rules below -specify that owners, authenticated via your Auth resource, can "create", -"read", "update", and "delete" their own records. Public users, -authenticated via an API key, can only "read" records. -=========================================================================*/ -const schema = a.schema({ - Todo: a - .model({ - content: a.string() - }) - .authorization([a.allow.owner(), a.allow.public().to(['read'])]) -}); - -export type Schema = ClientSchema; - -export const data = defineData({ - schema, - authorizationModes: { - defaultAuthorizationMode: 'apiKey', - // API Key is used for a.allow.public() rules - apiKeyAuthorizationMode: { - expiresInDays: 30 - } - } -}); - -/*== STEP 2 =============================================================== -Go to your frontend source code. From your client-side code, generate a -Data client to make CRUDL requests to your table. (THIS SNIPPET WILL ONLY -WORK IN THE FRONTEND CODE FILE.) - -Using JavaScript or Next.js React Server Components, Middleware, Server -Actions, or Pages Router? Review how to generate Data clients for those use -cases: https://docs.amplify.aws/gen2/build-a-backend/data/connect-to-API/ -=========================================================================*/ - -/* -"use client" -import { generateClient } from "aws-amplify/data"; -import { type Schema } from "@/amplify/data/resource"; - -const client = generateClient() // use this Data client for CRUDL requests -*/ - -/*== STEP 3 =============================================================== -Fetch records from the database and use them in your frontend component. -(THIS SNIPPET WILL ONLY WORK IN THE FRONTEND CODE FILE.) -=========================================================================*/ - -/* For example, in a React component, you can use this snippet in your - function's RETURN statement */ -// const { data: todos } = client.models.Todo.list() - -// return
    {todos.map(todo =>
  • {todo.content}
  • )}
-``` - - - The schema generated by Amplify is for a to-do app. A schema is a blueprint - for how our app's data will be organized. Within the schema, we will define - models which will correspond to a database table—`Todo` in the above code. - Finally, we will define fields which are attributes that each data instance - will have—in the generated code, the fields are `name` and `description`. Each - field will have a type attached to it—in the above examples, we are stating - that both `name` and `description` are strings. - - -Let's make a quick change to our data model and add a `done` field. This will be a `boolean`, which can be set to `true` or `false` depending on whether our to-do list item is complete. Let's also add a priority field, which will be an `enum`. This field type will allow for just a few options to be stored—low, medium, or high. - -We've removed the default comments to shorten the code below; however, you can choose to keep them for help in connecting to your frontend resources. - -```diff title="amplify/data/resource.ts" -// amplify/data/resource.ts -import { type ClientSchema, a, defineData } from '@aws-amplify/backend'; - -// ... - -const schema = a.schema({ - Todo: a - .model({ - content: a.string(), -+ done: a.boolean(), -+ priority: a.enum(['low', 'medium', 'high']) - }) - .authorization([a.allow.owner(), a.allow.public().to(['read'])]), -}); - -export type Schema = ClientSchema; - -export const data = defineData({ - schema, - authorizationModes: { - defaultAuthorizationMode: 'apiKey', - // API Key is used for a.allow.public() rules - apiKeyAuthorizationMode: { - expiresInDays: 30, - }, - }, -}); - -// ... -``` - -Once you save your changes to the data model, your changes will be deployed in seconds within your cloud sandbox. - -Our Todo data model also has authorization set up. Our model has the `authorization` method chained to it, which you can add rules to. In our example, we are allowing an owner, or the person who creates the Todo instance, to perform all actions on the data they own. We are also allowing all page viewers, including unauthenticated users, to read data. These can be modified; for example, we could remove the `.to(['read'])` and allow all visitors to perform all actions on data. We could also add permissions for signed-in users or users who belong to user groups such as `Admin`. You can learn more about all options for authorization in the [customize your auth rules](/gen2/build-a-backend/data/customize-authz/) section of the docs. - -Let's remove public access. - -```js -.authorization([a.allow.owner()]), -``` - -Then, you will see the `defineData` function, which has our schema and authorization configuration passed in as arguments. We have an `apiKey` set up to enable public access. Let's change our `defaultAuthorizationMode` to `userPool` instead so that the default is to use user authentication. - -```js -export const data = defineData({ - schema, - authorizationModes: { - defaultAuthorizationMode: 'userPool' - } -}); -``` - -The definitions are imported and set in the `backend` file. We will not need to change anything in this file right now, but you can see its contents, which define a backend with our data and auth configurations from their respective files. - -```ts title="amplify/backend.ts" -// amplify/backend.ts -import { defineBackend } from '@aws-amplify/backend'; -import { auth } from './auth/resource.js'; -import { data } from './data/resource.js'; - -defineBackend({ - auth, - data -}); -``` - -### Add authentication - -Now let's work on our authentication configuration. Similar to the `data/resource.ts` we just worked on, the `auth/resource.ts` file has code to define our authentication configuration. In this case, setting the authentication method to log in with email. - -```ts title="amplify/auth/resource.ts" -// amplify/auth/resource.ts -import { defineAuth } from '@aws-amplify/backend'; - -/** - * Define and configure your auth resource - * When used alongside data, it is automatically configured as an auth provider for data - * @see https://docs.amplify.aws/gen2/build-a-backend/auth - */ -export const auth = defineAuth({ - loginWith: { - email: true, - // add social providers - externalProviders: { - /** - * first, create your secrets using `amplify sandbox secret` - * then, import `secret` from `@aws-amplify/backend` - * @see https://docs.amplify.aws/gen2/deploy-and-host/sandbox-environments/features/#setting-secrets - */ - // loginWithAmazon: { - // clientId: secret('LOGINWITHAMAZON_CLIENT_ID'), - // clientSecret: secret('LOGINWITHAMAZON_CLIENT_SECRET'), - // } - } - }, - /** - * enable multifactor authentication - * @see https://docs.amplify.aws/gen2/build-a-backend/auth/manage-mfa - */ - // multifactor: { - // mode: 'OPTIONAL', - // sms: { - // smsMessage: (code) => `Your verification code is ${code}`, - // }, - // }, - userAttributes: { - /** request additional attributes for your app's users */ - // profilePicture: { - // mutable: true, - // required: false, - // }, - } -}); -``` + -Let's customize the verification email for our app. We can add a subject line by defining an object with email authentication properties. Again, we have removed comments for brevity. - -```diff title="amplify/auth/resource.ts" -// amplify/auth/resource.ts -import { defineAuth } from '@aws-amplify/backend'; - -export const auth = defineAuth({ - loginWith: { -- email: true, -+ email: { -+ verificationEmailSubject: 'Welcome! Verify your email!' -+ }, - // add social providers - externalProviders: { - } - } -}); -``` ## Build UI @@ -494,38 +220,6 @@ useEffect(() => { Go to `localhost` in the browser to make sure you can now log in and create and list to-dos. You can end your development session by shutting down the frontend dev server and cloud sandbox. The sandbox prompts you to delete your backend resources. While you can retain your backend, we recommend deleting all resources so you can start clean again next time. -## Deploy and host a fullstack branch - -Now that your app is working, let's deploy it to a shared fullstack branch so you can share the project with your team. Amplify offers a fully managed hosting service with CI/CD built in, making it easy to set up production and staging environments with Git branches. In Gen 2, every Git branch in your repository maps 1:1 to a fullstack branch in Amplify. - -### Create remote Git repository - -If you already have your project remotely hosted in a Git repository, you can skip this step. Otherwise, navigate to your preferred Git provider, and add your project to a new repository. Amplify supports [GitHub](https://docs.github.com/en/get-started/quickstart/create-a-repo), [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-create-repository.html), [GitLab](https://docs.gitlab.com/ee/user/project/index.html), and [Bitbucket](https://support.atlassian.com/bitbucket-cloud/docs/create-a-git-repository/). - -### Connect branch in the Amplify console - -1. To get started with Gen 2, log in to the [AWS console](https://console.aws.amazon.com/console/home?#amplify) and navigate to your preferred Region. (The Amplify console is available in [19 Regions](https://docs.aws.amazon.com/general/latest/gr/amplify.html#amplify_region)). - -2. If you have never created apps with Amplify before, choose _Create an app_ from the purple banner (top screenshot). If you have Amplify apps, you can find the option under *New app > Build an app (Gen 2)*. - -![gen2](/images/gen2/getting-started/console1.png) - -3. In the Git provider screen, choose _Option 2: Start with an existing app_. Connect the repository you just deployed and pick a branch. - -Next.js 14 apps require a [minimum node version](https://nextjs.org/blog/next-14#other-changes) of 18.17 at build time. - -4. Under _Advanced settings_, navigate to _Build Image_ and enter `amplify:al2023`. The Amplify Amazon Linux 2023 build image supports Node.js versions 18 and 20 at build time. You can specify the Node.js version during your build via [live package updates](https://docs.aws.amazon.com/amplify/latest/userguide/custom-build-image.html#setup-live-updates) or [nvm](https://github.com/nvm-sh/nvm). Amplify Hosting will automatically deploy your compute runtime to match the Node.js version used at build time. - -![Amplify Gen 2 console showing the "Advanced Settings" view with "amplify:al2023" specified for build image](/images/gen2/getting-started/console4.png) - -If you have an existing Gen 2 application, you can modify the build image by navigating to _Hosting_ -> _Environment Variables_ and create a new environment variable `_CUSTOM_IMAGE` with the value `amplify:al2023`, then redeploy the build. - -5. Review all of your settings to ensure everything is set up correctly. Choose _Save and deploy_ to deploy your web app. - - - -### Manage fullstack branch +import deployAndHost from 'src/fragments/gen2/quickstart/deploy-and-host.mdx'; -The new Amplify console gives you a central place to manage your branches, hosting settings, CI/CD builds, and backend resources. Even though you can access backend resources directly from AWS service consoles, the Amplify console offers built-in user and data administration. + diff --git a/src/pages/gen2/start/quickstart/nextjs-pages-router/index.mdx b/src/pages/gen2/start/quickstart/nextjs-pages-router/index.mdx index 42227821a45..4065803c15f 100644 --- a/src/pages/gen2/start/quickstart/nextjs-pages-router/index.mdx +++ b/src/pages/gen2/start/quickstart/nextjs-pages-router/index.mdx @@ -13,292 +13,19 @@ export function getStaticProps(context) { This Quickstart guide will walk you through how to build a task list application with TypeScript, Next.js **Pages Router**, and React. If you are new to these technologies, we recommend you go through the official [React](https://react.dev/learn/tutorial-tic-tac-toe), [Next.js](https://nextjs.org/docs/getting-started/installation), and [TypeScript](https://www.typescriptlang.org/docs/handbook/typescript-from-scratch.html) tutorials first. -## Prerequisites -Before you get started, make sure you have the following installed: +import prerequisites from 'src/fragments/gen2/quickstart/prerequisites.mdx'; -- [Node.js](https://nodejs.org/) v18.17 or later -- [npm](https://www.npmjs.com/) v9 or later -- [git](https://git-scm.com/) v2.14.1 or later -- You will also need to [create an AWS account](https://portal.aws.amazon.com/billing/signup). Note that AWS Amplify is part of the [AWS Free Tier](https://aws.amazon.com/amplify/pricing/). + -## Create a project +import createProject from 'src/fragments/gen2/quickstart/create-nextjs-project.mdx'; -First, you will need to create a new Next.js app. The following command will create a Next.js app in a directory called `next-amplify-gen2` that uses the **Pages Router**. + -```bash -npm create next-app@14 -- next-amplify-gen2 --typescript --eslint --no-app --no-src-dir --no-tailwind --import-alias '@/*' -cd next-amplify-gen2 -``` - -The easiest way to get started with AWS Amplify is through npm with `create-amplify`. - -```bash -npm create amplify@latest -``` - -```console -? Where should we create your project? (.) # press enter -``` - -Running this command will scaffold a lightweight Amplify project in your current project with the following files: - -```text -├── amplify/ -│ ├── auth/ -│ │ └── resource.ts -│ ├── data/ -│ │ └── resource.ts -│ ├── backend.ts -│ └── package.json -├── node_modules/ -├── .gitignore -├── package-lock.json -├── package.json -└── tsconfig.json -``` - -## Start local dev server - -Let's start a local dev server for your app development. For the frontend, run `npm run dev` to spin up a `localhost` dev server with the default Next.js template. - -```bash -npm run dev -``` - - - -Now [configure your AWS account to use Amplify](/gen2/start/account-setup/). Note: If you already have an AWS profile with credentials on your local machine, and you have configured the corresponding AWS profile with the **AmplifyBackendDeployFullAccess** permission policy, you can skip this step. - - - -For the backend, we're going to start a cloud sandbox environment. Amplify gives every developer a personal cloud sandbox environment that provides isolated development spaces to rapidly build, test, and iterate. When you're working with a team, each developer will have their own personal cloud sandbox. In a new terminal window, run the following command: - -```bash -npx amplify sandbox -``` -Do not use cloud sandbox environments in production. - -You should now have these two commands running concurrently in different terminal windows. - -## Build a backend - -Next, we will add data and auth capabilities to the app. - -### Add data - -Each of the `resource.ts` files is where you _define_ the corresponding backend resource. If you open up the `/amplify/data/resource.ts` file in your text editor, you will see some generated code already there: - -```ts showLineNumbers title="amplify/data/resource.ts" -// amplify/data/resource.ts -import { type ClientSchema, a, defineData } from '@aws-amplify/backend'; - -/*== STEP 1 =============================================================== -The section below creates a Todo database table with a "content" field. Try -adding a new "isDone" field as a boolean. The authorization rules below -specify that owners, authenticated via your Auth resource, can "create", -"read", "update", and "delete" their own records. Public users, -authenticated via an API key, can only "read" records. -=========================================================================*/ -const schema = a.schema({ - Todo: a - .model({ - content: a.string() - }) - .authorization([a.allow.owner(), a.allow.public().to(['read'])]) -}); - -export type Schema = ClientSchema; - -export const data = defineData({ - schema, - authorizationModes: { - defaultAuthorizationMode: 'apiKey', - // API Key is used for a.allow.public() rules - apiKeyAuthorizationMode: { - expiresInDays: 30 - } - } -}); - -/*== STEP 2 =============================================================== -Go to your frontend source code. From your client-side code, generate a -Data client to make CRUDL requests to your table. (THIS SNIPPET WILL ONLY -WORK IN THE FRONTEND CODE FILE.) - -Using JavaScript or Next.js React Server Components, Middleware, Server -Actions, or Pages Router? Review how to generate Data clients for those use -cases: https://docs.amplify.aws/gen2/build-a-backend/data/connect-to-API/ -=========================================================================*/ - -/* -"use client" -import { generateClient } from "aws-amplify/data"; -import { type Schema } from "@/amplify/data/resource"; - -const client = generateClient() // use this Data client for CRUDL requests -*/ - -/*== STEP 3 =============================================================== -Fetch records from the database and use them in your frontend component. -(THIS SNIPPET WILL ONLY WORK IN THE FRONTEND CODE FILE.) -=========================================================================*/ - -/* For example, in a React component, you can use this snippet in your - function's RETURN statement */ -// const { data: todos } = client.models.Todo.list() - -// return
    {todos.map(todo =>
  • {todo.content}
  • )}
-``` - - - The schema generated by Amplify is for a to-do app. A schema is a blueprint - for how our app's data will be organized. Within the schema, we will define - models which will correspond to a database table—`Todo` in the above code. - Finally, we will define fields which are attributes that each data instance - will have—in the generated code, the fields are `name` and `description`. Each - field will have a type attached to it—in the above examples, we are stating - that both `name` and `description` are strings. - - -Let's make a quick change to our data model and add a `done` field. This will be a `boolean`, which can be set to `true` or `false` depending on whether our to-do list item is complete. Let's also add a priority field, which will be an `enum`. This field type will allow for just a few options to be stored—low, medium, or high. - -We've removed the default comments to shorten the code below; however, you can choose to keep them for help in connecting to your frontend resources. - -```diff title="amplify/data/resource.ts" -// amplify/data/resource.ts -import { type ClientSchema, a, defineData } from '@aws-amplify/backend'; - -// ... - -const schema = a.schema({ - Todo: a - .model({ - content: a.string(), -+ done: a.boolean(), -+ priority: a.enum(['low', 'medium', 'high']) - }) - .authorization([a.allow.owner(), a.allow.public().to(['read'])]), -}); - -export type Schema = ClientSchema; - -export const data = defineData({ - schema, - authorizationModes: { - defaultAuthorizationMode: 'apiKey', - // API Key is used for a.allow.public() rules - apiKeyAuthorizationMode: { - expiresInDays: 30, - }, - }, -}); - -// ... -``` - -Once you save your changes to the data model, your changes will be deployed in seconds within your cloud sandbox. - -Our Todo data model also has authorization set up. Our model has the `authorization` method chained to it, which you can add rules to. In our example, we are allowing an owner, or the person who creates the Todo instance, to perform all actions on the data they own. We are also allowing all page viewers, including unauthenticated users, to read data. These can be modified; for example, we could remove the `.to(['read'])` and allow all visitors to perform all actions on data. We could also add permissions for signed-in users or users who belong to user groups such as `Admin`. You can learn more about all options for authorization in the [customize your auth rules](/gen2/build-a-backend/data/customize-authz/) section of the docs. - -Let's remove public access. - -```js -.authorization([a.allow.owner()]), -``` - -Then, you will see the `defineData` function, which has our schema and authorization configuration passed in as arguments. We have an `apiKey` set up to enable public access. Let's change our `defaultAuthorizationMode` to `userPool` instead so that the default is to use user authentication. - -```js -export const data = defineData({ - schema, - authorizationModes: { - defaultAuthorizationMode: 'userPool' - } -}); -``` - -The definitions are imported and set in the `backend` file. We will not need to change anything in this file right now, but you can see its contents, which define a backend with our data and auth configurations from their respective files. - -```ts title="amplify/backend.ts" -// amplify/backend.ts -import { defineBackend } from '@aws-amplify/backend'; -import { auth } from './auth/resource.js'; -import { data } from './data/resource.js'; - -defineBackend({ - auth, - data -}); -``` - -### Add authentication - -Now let's work on our authentication configuration. Similar to the `data/resource.ts` we just worked on, the `auth/resource.ts` file has code to define our authentication configuration. In this case, setting the authentication method to log in with email. - -```ts title="amplify/auth/resource.ts" -// amplify/auth/resource.ts -import { defineAuth } from '@aws-amplify/backend'; - -/** - * Define and configure your auth resource - * When used alongside data, it is automatically configured as an auth provider for data - * @see https://docs.amplify.aws/gen2/build-a-backend/auth - */ -export const auth = defineAuth({ - loginWith: { - email: true, - // add social providers - externalProviders: { - /** - * first, create your secrets using `amplify sandbox secret` - * then, import `secret` from `@aws-amplify/backend` - * @see https://docs.amplify.aws/gen2/deploy-and-host/sandbox-environments/features/#setting-secrets - */ - // loginWithAmazon: { - // clientId: secret('LOGINWITHAMAZON_CLIENT_ID'), - // clientSecret: secret('LOGINWITHAMAZON_CLIENT_SECRET'), - // } - } - }, - /** - * enable multifactor authentication - * @see https://docs.amplify.aws/gen2/build-a-backend/auth/manage-mfa - */ - // multifactor: { - // mode: 'OPTIONAL', - // sms: { - // smsMessage: (code) => `Your verification code is ${code}`, - // }, - // }, - userAttributes: { - /** request additional attributes for your app's users */ - // profilePicture: { - // mutable: true, - // required: false, - // }, - } -}); -``` - -Let's customize the verification email for our app. We can add a subject line by defining an object with email authentication properties. Again, we have removed comments for brevity. +import buildABackend from 'src/fragments/gen2/quickstart/build-a-backend.mdx'; -```diff title="amplify/auth/resource.ts" -// amplify/auth/resource.ts -import { defineAuth } from '@aws-amplify/backend'; + -export const auth = defineAuth({ - loginWith: { -- email: true, -+ email: { -+ verificationEmailSubject: 'Welcome! Verify your email!' -+ }, - // add social providers - externalProviders: { - } - } -}); -``` ## Build UI @@ -422,38 +149,6 @@ useEffect(() => { Go to `localhost` in the browser to make sure you can now log in and create and list to-dos. You can end your development session by shutting down the frontend dev server and cloud sandbox. The sandbox prompts you to delete your backend resources. While you can retain your backend, we recommend deleting all resources so you can start clean again next time. -## Deploy and host a fullstack branch - -Now that your app is working, let's deploy it to a shared fullstack branch so you can share the project with your team. Amplify offers a fully managed hosting service with CI/CD built in, making it easy to set up production and staging environments with Git branches. In Gen 2, every Git branch in your repository maps 1:1 to a fullstack branch in Amplify. - -### Create remote Git repository - -If you already have your project remotely hosted in a Git repository, you can skip this step. Otherwise, navigate to your preferred Git provider, and add your project to a new repository. Amplify supports [GitHub](https://docs.github.com/en/get-started/quickstart/create-a-repo), [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-create-repository.html), [GitLab](https://docs.gitlab.com/ee/user/project/index.html), and [Bitbucket](https://support.atlassian.com/bitbucket-cloud/docs/create-a-git-repository/). - -### Connect branch in the Amplify console - -1. To get started with Gen 2, log in to the [AWS console](https://console.aws.amazon.com/console/home?#amplify) and navigate to your preferred Region. (The Amplify console is available in [19 Regions](https://docs.aws.amazon.com/general/latest/gr/amplify.html#amplify_region)). -2. If you have never created apps with Amplify before, choose _Create an app_ from the purple banner (top screenshot). If you have Amplify apps, you can find the option under *New app > Build an app (Gen 2)*. - -![gen2](/images/gen2/getting-started/console1.png) - -3. In the Git provider screen, choose _Option 2: Start with an existing app_. Connect the repository you just deployed and pick a branch. - -Next.js 14 apps require a [minimum node version](https://nextjs.org/blog/next-14#other-changes) of 18.17 at build time. - -4. Under _Advanced settings_, navigate to _Build Image_ and enter `amplify:al2023`. The Amplify Amazon Linux 2023 build image supports Node.js versions 18 and 20 at build time. You can specify the Node.js version during your build via [live package updates](https://docs.aws.amazon.com/amplify/latest/userguide/custom-build-image.html#setup-live-updates) or [nvm](https://github.com/nvm-sh/nvm). Amplify Hosting will automatically deploy your compute runtime to match the Node.js version used at build time. - -![Amplify Gen 2 console showing the "Advanced Settings" view with "amplify:al2023" specified for build image](/images/gen2/getting-started/console4.png) - -If you have an existing Gen 2 application, you can modify the build image by navigating to _Hosting_ -> _Environment Variables_ and create a new environment variable `_CUSTOM_IMAGE` with the value `amplify:al2023`, then redeploy the build. - -5. Review all of your settings to ensure everything is set up correctly. Choose _Save and deploy_ to deploy your web app. - - - - -### Manage fullstack branch +import deployAndHost from 'src/fragments/gen2/quickstart/deploy-and-host.mdx'; -The new Amplify console gives you a central place to manage your branches, hosting settings, CI/CD builds, and backend resources. Even though you can access backend resources directly from AWS service consoles, the Amplify console offers built-in user and data administration. +