### Continue Sign-In with TOTP Setup Source: https://docs.amplify.aws/nextjs/frontend/auth/multi-step-sign-in For TOTP setup, use the `totpSetupDetails` to get a setup URI for authenticator apps. After setup, collect the TOTP code from the user and pass it to `confirmSignIn`. ```typescript import { type SignInOutput, confirmSignIn } from '@aws-amplify/auth'; async function handleSignInResult(result: SignInOutput) { switch (result.nextStep.signInStep) { case 'CONTINUE_SIGN_IN_WITH_TOTP_SETUP': { const { totpSetupDetails } = result.nextStep; const appName = 'my_app_name'; const setupUri = totpSetupDetails.getSetupUri(appName); // Open setupUri with an authenticator app // Prompt user to enter OTP code to complete setup break; } } } // Then, pass the collected OTP code to `confirmSignIn` async function confirmTotpCode(totpCode: string) { const result = await confirmSignIn({ challengeResponse: totpCode }); return handleSignInResult(result); } ``` -------------------------------- ### Install Amplify Client Libraries Source: https://docs.amplify.aws/nextjs/ai/set-up-ai Install the necessary Amplify client libraries for your project using npm. ```bash npm add aws-amplify @aws-amplify/ui-react @aws-amplify/ui-react-ai ``` -------------------------------- ### Install Amplify Next.js Adapter Source: https://docs.amplify.aws/nextjs/frontend/server-side-rendering/nextjs-app-router-server-components Install the Amplify adapter for Next.js to enable server-side integration. ```bash npm add @aws-amplify/adapter-nextjs ``` -------------------------------- ### Install Amplify Client Library Source: https://docs.amplify.aws/nextjs/build-a-backend/data/set-up-data Install the Amplify client library using npm. This is the first step to connecting your application to the Amplify backend. ```bash npm add aws-amplify ``` -------------------------------- ### Start Amplify Sandbox Source: https://docs.amplify.aws/nextjs/ai/set-up-ai Run this command to start your local cloud sandbox, which provisions and watches for updates to your Amplify resources. ```bash npx ampx sandbox ``` -------------------------------- ### AWS SSO Configuration Prompts Source: https://docs.amplify.aws/nextjs/start/account-setup Example of the interactive prompts during `aws configure sso`. You will need to provide your SSO start URL, region, and potentially other details. ```bash aws configure sso | SSO session name (Recommended): amplify-admin | SSO start URL: | SSO region: | SSO registration scopes [sso:account:access]: | Attempting to automatically open the SSO authorization page in your default browser. | If the browser does not open or you wish to use a different device to authorize this request, open the following URL: | | https://device.sso.us-east-2.amazonaws.com/ | | Then enter the code: | | SOME-CODE ``` -------------------------------- ### Verify Identity Center Setup and Session URL Source: https://docs.amplify.aws/nextjs/start/account-setup After the automated setup, run this command in CloudShell to display the session start URL, region, and username for accessing the AWS console. ```bash printf "\n\nStart session url: https://$ssoId.awsapps.com/start\nRegion: $AWS_REGION\nUsername: amplify-admin\n\n" ``` -------------------------------- ### Install Amplify UI Library Source: https://docs.amplify.aws/nextjs/build-ui/formbuilder Install the Amplify UI React library using npm. This is a prerequisite for using connected forms. ```bash npm add @aws-amplify/ui-react ``` -------------------------------- ### Install Amplify UI for React Source: https://docs.amplify.aws/nextjs/frontend/in-app-messaging/integrate-application Install the necessary Amplify UI packages for React and in-app notifications using npm. ```bash npm add @aws-amplify/ui-react @aws-amplify/ui-react-notifications ``` -------------------------------- ### Install Amplify UI React Storage Source: https://docs.amplify.aws/nextjs/frontend/storage/download-files Install the necessary Amplify UI React Storage package using npm. ```bash npm add @aws-amplify/ui-react-storage aws-amplify ``` -------------------------------- ### Install Amplify Libraries Source: https://docs.amplify.aws/nextjs/build-a-backend/add-aws-services/analytics/set-up-analytics Install the `aws-amplify` library using npm. This command should be run in your project's terminal. ```bash npm add aws-amplify ``` -------------------------------- ### Install AWS SDK for Polly Source: https://docs.amplify.aws/nextjs/build-a-backend/data/custom-business-logic/connect-amazon-polly Install the AWS SDK for Amazon Polly using npm. This command should be run in your project's root folder. ```bash npm add @aws-sdk/client-polly ``` -------------------------------- ### List Installed Plugins Source: https://docs.amplify.aws/nextjs/develop-with-ai/agent-plugins Verifies the installation of plugins, including the aws-amplify plugin. Run this command in Claude Code. ```bash /plugin list ``` -------------------------------- ### Clone and Install Next.js Template Source: https://docs.amplify.aws/nextjs/start/quickstart/nextjs-app-router-client-components Clone the Amplify Next.js template repository and install its dependencies. ```bash git clone https://github.com//amplify-next-template.git cd amplify-next-template && npm install ``` -------------------------------- ### Start Next.js Local Dev Server Source: https://docs.amplify.aws/nextjs/frontend/server-side-rendering/nextjs-app-router-server-components Run this command in your terminal to start the local development server for your Next.js frontend. ```bash npm run dev ``` -------------------------------- ### Install Amplify Backend AI Package Source: https://docs.amplify.aws/nextjs/frontend/ai/conversation/tools Install the necessary Amplify backend AI package using npm. ```bash npm install @aws-amplify/backend-ai ``` -------------------------------- ### Install Amplify Auth Types Source: https://docs.amplify.aws/nextjs/build-a-backend/functions/examples/override-token Install the necessary types for AWS Lambda to define custom triggers. ```bash npm add --save-dev @types/aws-lambda ``` -------------------------------- ### Install Amplify Next.js Adapter Source: https://docs.amplify.aws/nextjs/frontend/server-side-rendering Install the Amplify Next.js adapter to enable server-side API usage. Ensure your Next.js version is compatible. ```bash npm add aws-amplify @aws-amplify/adapter-nextjs ``` -------------------------------- ### Install Amplify Libraries for Predictions Source: https://docs.amplify.aws/nextjs/build-a-backend/add-aws-services/predictions/set-up-predictions Installs the necessary Amplify libraries for using predictions features in your project. ```bash npm add aws-amplify @aws-amplify/predictions ``` -------------------------------- ### Install Amplify Backend Dependencies Source: https://docs.amplify.aws/nextjs/start/manual-installation Install the necessary Amplify backend and CLI packages, along with TypeScript, for building your backend. ```bash npm add --save-dev @aws-amplify/backend@latest @aws-amplify/backend-cli@latest typescript ``` -------------------------------- ### Install Amplify Gen 2 CLI Source: https://docs.amplify.aws/nextjs/start/migrate-to-gen2/feature-matrix Install the Gen 2 CLI as a local dev dependency. Run commands using `npx ampx`. ```bash npm i @aws-amplify/backend-cli ``` -------------------------------- ### Install Any AWS Agent Plugin Source: https://docs.amplify.aws/nextjs/develop-with-ai/agent-plugins Installs a specified AWS agent plugin, such as aws-serverless or deploy-on-aws. Replace with the desired plugin. Run this command in Claude Code. ```bash /plugin install @agent-plugins-for-aws ``` -------------------------------- ### Install Amazon Translate SDK Source: https://docs.amplify.aws/nextjs/build-a-backend/data/custom-business-logic/connect-amazon-translate Install the Amazon Translate SDK using npm. Run this command in your project's root folder. ```bash npm add @aws-sdk/client-translate ``` -------------------------------- ### Install AWS SDK for Rekognition Source: https://docs.amplify.aws/nextjs/build-a-backend/data/custom-business-logic/connect-amazon-rekognition Install the AWS SDK client for Amazon Rekognition using npm. This command should be run in your project's root folder. ```bash npm add @aws-sdk/client-rekognition ``` -------------------------------- ### Install AWS SDK v3 and types/aws-lambda Source: https://docs.amplify.aws/nextjs/build-a-backend/functions/examples/add-user-to-group Install the AWS SDK v3 client for Cognito Identity Provider and the types/aws-lambda package for defining Lambda handler types. ```bash npm add --save-dev @aws-sdk/client-cognito-identity-provider @types/aws-lambda ``` -------------------------------- ### Handle MFA Setup Selection in Sign-In Source: https://docs.amplify.aws/nextjs/frontend/auth/multi-step-sign-in Use this when the sign-in flow requires the user to select an MFA method for setup. Present the available options and pass the user's choice to `confirmSignIn`. ```typescript import { type SignInOutput, confirmSignIn } from '@aws-amplify/auth'; async function handleSignInResult(result: SignInOutput) { switch (result.nextStep.signInStep) { case 'CONTINUE_SIGN_IN_WITH_MFA_SETUP_SELECTION': { const { allowedMFATypes } = result.nextStep; // Present available MFA options to user // Prompt for selection console.log(`There are multiple MFA options available for setup.`); console.log(`Select an MFA type from the allowedMFATypes list.`); break; } } } type MfaType = 'SMS' | 'TOTP' | 'EMAIL'; async function handleMfaSelection(mfaType: MfaType) { const result = await confirmSignIn({ challengeResponse: mfaType }); return handleSignInResult(result); } ``` -------------------------------- ### Basic AIConversation Component Setup Source: https://docs.amplify.aws/nextjs/frontend/ai/conversation/ai-conversation This example shows the basic setup of the AIConversation component. It requires an empty messages array and a placeholder for the send message handler. ```jsx import { AIConversation } from '@aws-amplify/ui-react-ai'; export default function Chat() { return ( {}} /> ) } ``` -------------------------------- ### Amplify Deployment Guide Workflow Source: https://docs.amplify.aws/nextjs/develop-with-ai/mcp-server/amplify-workflows Utilize this workflow for deployment tasks related to your Amplify project. The `amplify-deployment-guide` argument ensures the correct SOP is retrieved. ```bash retrieve_agent_sop with amplify-deployment-guide ``` -------------------------------- ### Project Structure with amplify_outputs.json Source: https://docs.amplify.aws/nextjs/start/quickstart/nextjs-app-router-client-components Illustrates the project structure after downloading the amplify_outputs.json file, which contains backend configuration details. ```text ├── amplify ├── src ├── amplify_outputs.json <== backend outputs file ├── package.json └── tsconfig.json ``` -------------------------------- ### Test GET method with query string in API Gateway console Source: https://docs.amplify.aws/nextjs/frontend/rest-api/test-api This example shows how to test a GET request with a query string parameter using the API Gateway console's test feature. ```bash GET /items?limit=10 ``` -------------------------------- ### Clone Amplify Next.js Template Source: https://docs.amplify.aws/nextjs/start/quickstart/nextjs-pages-router Clone the Amplify Next.js template repository and install dependencies to start your project. ```bash git clone https://github.com//amplify-next-template.git cd amplify-next-template && npm install ``` -------------------------------- ### Customize Scopes for External Providers Source: https://docs.amplify.aws/nextjs/build-a-backend/auth/concepts/external-identity-providers Specify the data scopes to retrieve from external providers during setup in `amplify/auth/resource.ts`. This example shows how to set scopes for login with Amazon. ```typescript import { defineAuth, secret } from '@aws-amplify/backend'; export const auth = defineAuth({ loginWith: { email: true, externalProviders: { loginWithAmazon: { clientId: secret('LOGINWITHAMAZON_CLIENT_ID'), clientSecret: secret('LOGINWITHAMAZON_CLIENT_SECRET'), scopes: ['profile'] }, callbackUrls: [ 'http://localhost:3000/profile', 'https://mywebsite.com/profile' ], logoutUrls: ['http://localhost:3000/', 'https://mywebsite.com'], } } }); ``` -------------------------------- ### Initiate Sign In with TOTP Setup Source: https://docs.amplify.aws/nextjs/build-a-backend/auth/concepts/multi-factor-authentication Call this when a user signs in and is required to set up TOTP. The output indicates `CONTINUE_SIGN_IN_WITH_TOTP_SETUP` if MFA is required, TOTP is enabled, and the user hasn't set it up yet. Use `totpSetupDetails.getSetupUri()` to configure an authenticator app. ```javascript import { signIn, SignInOutput } from 'aws-amplify/auth'; const output = await signIn({ username: "hello@mycompany.com", password: "hunter2" }); const { nextStep } = output; switch (nextStep.signInStep) { // ... case 'CONTINUE_SIGN_IN_WITH_TOTP_SETUP': const totpSetupDetails = nextStep.totpSetupDetails; const appName = 'my_app_name'; const setupUri = totpSetupDetails.getSetupUri(appName); // Open setupUri with an authenticator APP to retrieve an OTP code break; // ... } ``` -------------------------------- ### Handle subscription connection status and fetch data Source: https://docs.amplify.aws/nextjs/frontend/data/subscribe-data This example demonstrates listening for connection state changes and fetching recent data when the connection transitions from 'Connecting' to 'Connected'. It also includes setting up and cleaning up various subscription types. ```typescript import { generateClient, CONNECTION_STATE_CHANGE, ConnectionState } from 'aws-amplify/data' import { Hub } from 'aws-amplify/utils' import { Schema } from '../amplify/data/resource'; const client = generateClient() const fetchRecentData = () => { const { data: allTodos } = await client.models.Todo.list() } let priorConnectionState: ConnectionState; Hub.listen("api", (data: any) => { const { payload } = data; if ( payload.event === CONNECTION_STATE_CHANGE ) { if (priorConnectionState === ConnectionState.Connecting && payload.data.connectionState === ConnectionState.Connected) { fetchRecentData(); } priorConnectionState = payload.data.connectionState; } }); const createSub = client.models.Todo.onCreate().subscribe({ next: payload => // Process incoming messages }); const updateSub = client.models.Todo.onUpdate().subscribe({ next: payload => // Process incoming messages }); const deleteSub = client.models.Todo.onDelete().subscribe({ next: payload => // Process incoming messages }); const cleanupSubscriptions = () => { createSub.unsubscribe(); updateSub.unsubscribe(); deleteSub.unsubscribe(); } ``` -------------------------------- ### Initiate Sign-In with External Provider Source: https://docs.amplify.aws/nextjs/build-a-backend/auth/concepts/external-identity-providers Use `signInWithRedirect` to start the authentication flow with a chosen external identity provider. Ensure the provider is configured in your Amplify setup. ```javascript import { signInWithRedirect } from 'aws-amplify/auth'; await signInWithRedirect({ provider: 'Apple' }); ``` -------------------------------- ### Get File Properties Source: https://docs.amplify.aws/nextjs/frontend/storage/list-files Demonstrates how to use the `getProperties` function to retrieve file properties. It includes an example of specifying the file path and optionally configuring the target bucket. ```APIDOC ## Get File Properties You can view the properties of an individual file using the `getProperties` function. ### Method Signature ```javascript import { getProperties } from 'aws-amplify/storage'; await getProperties({ path: string | ({ identityId: string }) => string, options?: { bucket?: string; useAccelerateEndpoint?: boolean; } }); ``` ### Parameters #### Path Parameter - **path** (string | ({ identityId: string }) => string) - Required - The path to the file. Can be a string or a function that returns a string, allowing for dynamic path generation based on the identity ID. #### Options Object - **bucket** (string) - Optional - The name of the target bucket as assigned in your Amplify Backend configuration. Alternatively, an object `{ bucketName: string; region: string; }` can be provided to specify the bucket name and region. - **useAccelerateEndpoint** (boolean) - Optional - Defaults to `false`. Set to `true` to use the AWS S3 Transfer Acceleration endpoint. ### Request Example ```javascript import { getProperties } from 'aws-amplify/storage'; try { const result = await getProperties({ path: 'album/2024/1.jpg', options: { bucket: 'assignedNameInAmplifyBackend' } }); console.log('File Properties ', result); } catch (error) { console.log('Error ', error); } ``` ### Response Example ```json { "path": "album/2024/1.jpg", "contentType": "image/jpeg", "contentLength": 6873, "eTag": "\"56b32cf4779ff6ca3ba3f2d455fa56a7\"", "lastModified": "Wed Apr 19 2023 14:20:55 GMT-0700 (Pacific Daylight Time)", "metadata": { "owner": "aws" } } ``` ### Notes - To retrieve user-defined metadata in the results, ensure that user-defined metadata is configured in your CORS settings. - Refer to the Amplify documentation for details on configuring additional storage buckets and setting up appropriate CORS policies. ``` -------------------------------- ### Project Structure Overview Source: https://docs.amplify.aws/nextjs/start/quickstart/nextjs-pages-router This snippet outlines the directory structure of the starter Next.js (Pages) template, including Amplify backend configuration and React UI code. ```bash ├── amplify/ # Folder containing your Amplify backend configuration │ ├── auth/ # Definition for your auth backend │ │ └── resource.tsx │ ├── data/ # Definition for your data backend │ │ └── resource.ts | ├── backend.ts | └── tsconfig.json ├── src/ # React UI code │ ├── App.tsx # UI code to sync todos in real-time │ ├── index.css # Styling for your app │ └── main.tsx # Entrypoint of the Amplify client library ├── package.json └── tsconfig.json ``` -------------------------------- ### Initialize Map with Location Search Control Source: https://docs.amplify.aws/nextjs/frontend/geo/location-search Create a MapLibre map and add the Amplify Geo location search control to it. This example demonstrates basic setup and integration. ```javascript import { createMap, createAmplifyGeocoder } from "maplibre-gl-js-amplify"; import maplibregl from "maplibre-gl"; import "maplibre-gl/dist/maplibre-gl.css"; import "@maplibre/maplibre-gl-geocoder/dist/maplibre-gl-geocoder.css"; import "maplibre-gl-js-amplify/dist/public/amplify-geocoder.css"; // Optional CSS for Amplify recommended styling async function initializeMap() { const el = document.createElement("div"); el.setAttribute("id", "map"); document.body.appendChild(el); const map = await createMap({ container: "map", center: [-123.1187, 49.2819], // [Longitude, Latitude] zoom: 11, }) map.addControl(createAmplifyGeocoder()); } initializeMap(); ``` -------------------------------- ### Sign Up User Source: https://docs.amplify.aws/nextjs/frontend/auth/sign-up Use the `signUp()` API to create a new user in your backend. The response includes a `nextStep` property to determine if further action is required. ```APIDOC ## signUp() ### Description Creates a new user in your backend. ### Method `signUp` ### Parameters #### Request Body - **username** (string) - Required - The username for the new user. - **password** (string) - Required - The password for the new user. - **options** (object) - Optional - Additional options for sign-up. - **userAttributes** (object) - Optional - User-specific attributes. - **email** (string) - Optional - The user's email address. - **phone_number** (string) - Optional - The user's phone number in E.164 format. ### Response #### Success Response (200) - **isSignUpComplete** (boolean) - Indicates if the sign-up process is complete. - **userId** (string) - The ID of the newly created user. - **nextStep** (object) - Information about the next step in the sign-up process. - **signInStep** (string) - The next step required (e.g., `CONFIRM_SIGN_UP`, `DONE`, `COMPLETE_AUTO_SIGN_IN`). ### Request Example ```javascript import { signUp} from "aws-amplify/auth" const { isSignUpComplete, userId, nextStep } = await signUp({ username: "hello@mycompany.com", password: "hunter2", options: { userAttributes: { email: "hello@mycompany.com", phone_number: "+15555555555" // E.164 number convention }, } }); ``` ### Response Example ```json { "isSignUpComplete": false, "userId": "some-user-id", "nextStep": { "signInStep": "CONFIRM_SIGN_UP" } } ``` ``` -------------------------------- ### Cancellable Folder Deletion Source: https://docs.amplify.aws/nextjs/frontend/storage/remove-files This example demonstrates how to initiate a folder deletion that can be cancelled. By not using `await` immediately, you get an operation object with a `cancel()` method, which is useful for user-initiated cancellations. ```javascript import { remove } from 'aws-amplify/storage'; let deleteOperation; // Start deletion when user clicks delete button function handleDeleteFolder() { // remove() returns { result: Promise, cancel: Function } deleteOperation = remove({ path: 'user-uploads/large-dataset/', options: { onProgress: (fileBatch) => { updateProgressBar(fileBatch.deleted?.length || 0); } } }); // Access the promise via .result property deleteOperation.result.then(result => { console.log('Success', result); }).catch(error => { if (error.name === 'CanceledError') { console.log('Deletion cancelled by user'); } else { console.log('Error:', error); } }); } // Cancel when user clicks cancel or navigates away function handleCancel() { if (deleteOperation) { deleteOperation.cancel(); } } ``` -------------------------------- ### Update MFA Preferences with Multiple Methods Source: https://docs.amplify.aws/nextjs/build-a-backend/auth/concepts/multi-factor-authentication After TOTP setup is complete, record the MFA type as enabled and optionally set it as preferred. This example shows updating both SMS and TOTP preferences. ```javascript import { updateMFAPreference } from 'aws-amplify/auth'; await updateMFAPreference({ sms: 'ENABLED', totp: 'PREFERRED' }); ``` -------------------------------- ### Complete HTML Page with Map Integration Source: https://docs.amplify.aws/nextjs/frontend/geo/maps This is a full HTML page example demonstrating how to include all necessary Amplify and MapLibre GL JS scripts, define a map container, and initialize the map with configuration. ```html Display a map on a webpage
``` -------------------------------- ### Fetch Related Data Client-Side Source: https://docs.amplify.aws/nextjs/build-a-backend/data/data-modeling/relationships Retrieve related data on the client-side by first fetching a primary record and then accessing its related fields. This example shows how to get a post and then fetch its author and editor. ```typescript const client = generateClient(); const { data: post } = await client.models.Post.get({ id: "SOME_POST_ID" }); const { data: author } = await post?.author(); const { data: editor } = await post?.editor(); ``` -------------------------------- ### Start Amplify Sandbox Source: https://docs.amplify.aws/nextjs/start/account-setup Launches the AWS Amplify sandbox environment. Use the --profile flag if your AWS profile is not named 'default'. ```bash npx ampx sandbox ``` ```bash npx ampx sandbox --profile ``` -------------------------------- ### Get URL with Guest Access in getStaticProps Source: https://docs.amplify.aws/nextjs/frontend/server-side-rendering This example demonstrates how to use `getStaticProps` with `null` for `nextServerContext` to access Amplify Storage APIs with guest access, useful for fetching public assets like splash images. ```typescript export async function getStaticProps() { const splashUrl = await runWithAmplifyServerContext({ nextServerContext: null, operation: (contextSpec) => getUrl(contextSpec, { key: 'splash.png' }) }); return { props: { imageUrl: splashUrl.url.toString() }, revalidate: (splashUrl.expiresAt.getTime() - Date.now()) / 1000 // in seconds }; } ``` -------------------------------- ### Practical Example: List and Delete WebAuthn Credentials Source: https://docs.amplify.aws/nextjs/build-a-backend/auth/manage-users/manage-webauthn-credentials Demonstrates using list and delete APIs together. This example lists passkeys with a page size of 2, fetches the next page if available, and then deletes the first passkey in the combined list. ```typescript import { listWebAuthnCredentials, deleteWebAuthnCredential } from 'aws-amplify/auth'; let passkeys = []; const result = await listWebAuthnCredentials({ pageSize: 2 }); passkeys.push(...result.credentials); const nextPage = await listWebAuthnCredentials({ pageSize: 2, nextToken: result.nextToken, }); passkeys.push(...nextPage.credentials); const id = passkeys[0].credentialId; await deleteWebAuthnCredential({ credentialId: id }); ``` -------------------------------- ### Update and Get Device Position using Amazon Location Service SDK Source: https://docs.amplify.aws/nextjs/frontend/geo/amazon-location-sdk Example demonstrating how to update a device's position and retrieve it using the Amazon Location Service SDK. Requires a provisioned Tracker resource. ```javascript // UpdateDevicePosition API const params = { TrackerName: 'trackerId', Updates: [ { DeviceId: 'deviceId', Position: [-122.431297, 37.773972], SampleTime: new Date() } ] }; const command = new BatchUpdateDevicePositionCommand(params); client.send(command, (err, data) => { if (err) console.error(err); if (data) console.log(data); }); // GetDevicePosition API const client = await createClient(); const params = { TrackerName: 'trackerId', DeviceId: 'deviceId' }; const command = new GetDevicePositionCommand(params); client.send(command, (err, data) => { if (err) console.error(err); if (data) console.log(data); }); ``` -------------------------------- ### Configure Custom S3 Bucket for Authenticated Users Source: https://docs.amplify.aws/nextjs/frontend/storage/use-with-custom-s3 Define access permissions for authenticated users to files within a custom S3 bucket. This example grants 'get', 'list', 'write', and 'delete' access to objects under the 'public/*' path. ```typescript import { defineBackend } from "@aws-amplify/backend"; import { Effect, Policy, PolicyStatement } from "aws-cdk-lib/aws-iam"; import { Bucket } from "aws-cdk-lib/aws-s3"; import { auth } from "./auth/resource"; const backend = defineBackend({ auth, }); const customBucketStack = backend.createStack("custom-bucket-stack"); // Import existing bucket const customBucket = Bucket.fromBucketAttributes(customBucketStack, "MyCustomBucket", { bucketArn: "arn:aws:s3:::", region: "" }); backend.addOutput({ storage: { aws_region: customBucket.env.region, bucket_name: customBucket.bucketName, buckets: [ { aws_region: customBucket.env.region, bucket_name: customBucket.bucketName, name: customBucket.bucketName, paths: { "public/*": { guest: ["get", "list"], authenticated: ["get", "list", "write", "delete"], }, }, } ] }, }); // ... Unauthenticated/guest user policies and role attachments go here ... /* Define an inline policy to attach to Amplify's auth role This policy defines how authenticated users can access your existing bucket */ const authPolicy = new Policy(backend.stack, "customBucketAuthPolicy", { statements: [ new PolicyStatement({ effect: Effect.ALLOW, actions: [ "s3:GetObject", "s3:PutObject", "s3:DeleteObject" ], resources: [`${customBucket.bucketArn}/public/*`,], }), new PolicyStatement({ effect: Effect.ALLOW, actions: ["s3:ListBucket"], resources: [ `${customBucket.bucketArn}`, `${customBucket.bucketArn}/*` ], conditions: { StringLike: { "s3:prefix": ["public/*", "public/"], }, }, }), ], }); // Add the policies to the authenticated user role backend.auth.resources.authenticatedUserIamRole.attachInlinePolicy(authPolicy); ``` -------------------------------- ### get Source: https://docs.amplify.aws/nextjs/build-a-backend/data/reference Performs a GET HTTP request. Requires input for the get operation. ```APIDOC ## GET /get ### Description Performs a GET HTTP request. ### Method GET ### Endpoint /get ### Parameters #### Request Body - **input** (GetInput) - Required - Input for GET operation ### Throws - `RestApiError` ### Returns `GetOperation` ``` -------------------------------- ### Configure Amplify and ThemeProvider Source: https://docs.amplify.aws/nextjs/build-ui/formbuilder In your application's entry point, import Amplify UI styles, configure Amplify with your outputs, and wrap your app with ThemeProvider. ```javascript import '@aws-amplify/ui-react/styles.css'; import { ThemeProvider } from '@aws-amplify/ui-react'; import { Amplify } from 'aws-amplify'; import outputs from './amplify_outputs.json'; Amplify.configure(outputs); ``` -------------------------------- ### get Source: https://docs.amplify.aws/nextjs/build-a-backend/add-aws-services/rest-api/reference Performs a GET HTTP request. It requires an input object for the get operation and may throw a RestApiError. ```APIDOC ## GET /get ### Description Performs a GET HTTP request. ### Method GET ### Endpoint /get ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **input** (GetInput) - Required - Input for GET operation ### Request Example ```json { "input": { ... } } ``` ### Response #### Success Response (200) - **GetOperation** - The result of the get operation. #### Response Example ```json { "data": { ... } } ``` ### Throws - `RestApiError` ``` -------------------------------- ### Initialize Amplify Backend Entry Point Source: https://docs.amplify.aws/nextjs/start/manual-installation Create the main backend entry point file for Amplify. ```typescript import { defineBackend } from '@aws-amplify/backend'; defineBackend({}); ``` -------------------------------- ### Install AWS CLI on Linux Source: https://docs.amplify.aws/nextjs/start/account-setup Installs the AWS Command Line Interface version 2 on a Linux system. Ensure you have curl and unzip installed. ```bash curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" unzip awscliv2.zip ./aws/install -i /usr/local/aws-cli -b /usr/local/bin ``` -------------------------------- ### Install Amplify Seed Package Source: https://docs.amplify.aws/nextjs/deploy-and-host/sandbox-environments/seed Install the `@aws-amplify/seed` package as a development dependency in your project. ```bash npm install @aws-amplify/seed --save-dev ``` -------------------------------- ### List Data Models on the Client Side Source: https://docs.amplify.aws/nextjs/build-a-backend/data/connect-to-existing-data-sources/connect-postgres-mysql-database Once deployed, you can interact with your SQL-backed data models from the client side. This example demonstrates fetching a list of 'event' data. ```javascript const { data: events } = await client.models.event.list() ``` -------------------------------- ### Copy a File to a Specific Bucket Source: https://docs.amplify.aws/nextjs/frontend/storage/copy-files This example demonstrates copying a file to a specific bucket, either by its Amplify-assigned name or by providing the bucket name and region from the console. Both source and destination must define the `bucket` option when copying across buckets. ```javascript import { copy } from 'aws-amplify/storage'; const copyFile = async () => { try { const response = await copy({ source: { path: 'album/2024/1.jpg', // Specify a target bucket using name assigned in Amplify Backend // or bucket name from console and associated region bucket: 'assignedNameInAmplifyBackend', expectedBucketOwner: '123456789012' }, destination: { path: 'shared/2024/1.jpg', // Specify a target bucket using name assigned in Amplify Backend // or bucket name from console and associated region bucket: { bucketName: 'generated-second-bucket-name', region: 'us-east-2' }, expectedBucketOwner: '123456789013' } }); } catch (error) { console.error('Error', error); } }; ``` -------------------------------- ### Install otpauth Library Source: https://docs.amplify.aws/nextjs/deploy-and-host/sandbox-environments/seed Install the 'otpauth' library, which is used for generating TOTP codes in the seeding script. ```bash npm install otpauth ``` -------------------------------- ### Amplify App and Branch Setup for Custom Pipelines Source: https://docs.amplify.aws/nextjs/start/migrate-to-gen2/feature-matrix Use these AWS CLI commands for one-time setup to register an Amplify app and a branch for custom pipeline deployments. Ensure you replace placeholders like with your actual values. ```bash # (Optional) Create a new Amplify App — only needed if not reusing your existing app aws amplify create-app --name my-app # Register a branch name for your pipeline to deploy to # (this is a logical name, not necessarily a real Git branch) aws amplify create-branch --app-id --branch-name gen2-main # Disable auto-build so Amplify doesn't build on git push aws amplify update-branch --app-id --branch-name gen2-main --no-enable-auto-build ``` -------------------------------- ### Set Up TOTP After User Sign In Source: https://docs.amplify.aws/nextjs/build-a-backend/auth/concepts/multi-factor-authentication Invoke this API to generate TOTP setup details when MFA is optional or required and TOTP is enabled. Use `totpSetupDetails.getSetupURI()` to configure an authenticator app. ```javascript import { setUpTOTP } from 'aws-amplify/auth'; const totpSetupDetails = await setUpTOTP(); const appName = 'my_app_name'; const setupUri = totpSetupDetails.getSetupUri(appName); // Open setupUri with an authenticator APP to retrieve an OTP code ``` -------------------------------- ### Ask about available Amplify workflows Source: https://docs.amplify.aws/nextjs/develop-with-ai/mcp-server/set-up-mcp After setup, verify that the Amplify workflows are accessible by asking your AI assistant this question. ```text Which guided workflows are available for Amplify development? ``` -------------------------------- ### Make a GET request to a REST API Source: https://docs.amplify.aws/nextjs/frontend/rest-api/fetch-data Use the `get` function to make a GET request to your REST API. You can configure options like `apiName`, `path`, and `retryStrategy`. API status codes greater than 299 will throw an `ApiError`. ```javascript import { get } from 'aws-amplify/api'; async function getItem() { try { const restOperation = get({ apiName: 'myRestApi', path: 'items' options: { retryStrategy: { strategy: 'no-retry' // Overrides default retry strategy }, } }); const response = await restOperation.response; console.log('GET call succeeded: ', response); } catch (error) { console.log('GET call failed: ', JSON.parse(error.response.body)); } } ``` -------------------------------- ### Making a GET Request Source: https://docs.amplify.aws/nextjs/frontend/rest-api/fetch-data Demonstrates how to perform a GET request to a specified API endpoint with optional retry strategies. ```APIDOC ## GET /items ### Description Fetches data from the '/items' endpoint of the configured REST API. ### Method GET ### Endpoint /items ### Parameters #### Query Parameters None explicitly documented for this example. #### Request Body None ### Request Example ```javascript import { get } from 'aws-amplify/api'; async function getItem() { try { const restOperation = get({ apiName: 'myRestApi', path: 'items', options: { retryStrategy: { strategy: 'no-retry' // Overrides default retry strategy } } }); const response = await restOperation.response; console.log('GET call succeeded: ', response); } catch (error) { console.log('GET call failed: ', JSON.parse(error.response.body)); } } ``` ### Response #### Success Response (200) - **body** (any) - The response payload from the API. Can be consumed as text, blob, or JSON. #### Response Example ```json { "example": "response body" } ``` ### Retry Strategy Options - `no-retry`: Single attempt, fails immediately on error. - `jittered-exponential-backoff`: Default strategy that retries with increasing delays, maximum 3 attempts. ```