From 0867720251d47e269f05556132043a36c6671d13 Mon Sep 17 00:00:00 2001 From: Muhammed Salih Guler Date: Thu, 2 May 2024 18:36:33 +0200 Subject: [PATCH 01/17] [Gen 2][Mobile] Add the sign in with web ui docs for iOS, Android and Flutter (#7282) --- src/directory/directory.mjs | 3 + .../auth/sign-in-with-web-ui/index.mdx | 401 ++++++++++++++++++ 2 files changed, 404 insertions(+) create mode 100644 src/pages/[platform]/build-a-backend/auth/sign-in-with-web-ui/index.mdx diff --git a/src/directory/directory.mjs b/src/directory/directory.mjs index 722c7c1c300..a3839af64e4 100644 --- a/src/directory/directory.mjs +++ b/src/directory/directory.mjs @@ -144,6 +144,9 @@ export const directory = { { path: 'src/pages/[platform]/build-a-backend/auth/multi-step-sign-in/index.mdx' }, + { + path: 'src/pages/[platform]/build-a-backend/auth/sign-in-with-web-ui/index.mdx' + }, { path: 'src/pages/[platform]/build-a-backend/auth/app-uninstall/index.mdx' }, diff --git a/src/pages/[platform]/build-a-backend/auth/sign-in-with-web-ui/index.mdx b/src/pages/[platform]/build-a-backend/auth/sign-in-with-web-ui/index.mdx new file mode 100644 index 00000000000..13ae1f661ff --- /dev/null +++ b/src/pages/[platform]/build-a-backend/auth/sign-in-with-web-ui/index.mdx @@ -0,0 +1,401 @@ +import { getCustomStaticPath } from '@/utils/getCustomStaticPath'; + +export const meta = { + title: 'Enable sign-in with web UI', + description: + 'Use Amazon Cognito Auth plugin to register and authenticate a user with a prebuilt web UI', + platforms: ['flutter', 'swift', 'android'] +}; + +export const getStaticPaths = async () => { + return getCustomStaticPath(meta.platforms); +}; + +export function getStaticProps(context) { + return { + props: { + platform: context.params.platform, + meta + } + }; +} + + +## Prerequisites +* An app set up according to the [getting started walkthrough](/[platform]/build-a-backend/auth/set-up-auth/) + + + When configuring social sign-in, it's important to exercise caution when designating attributes as "required." Different social identity providers have varied scopes in terms of the information they respond back to Cognito with. User pool attributes that are initially set up as "required" cannot be changed later, and may require you to migrate the users or create a new user pool. + + +## Configure Auth Category + + + +This library's Cognito plugin currently supports the [Authorization Code Grant](https://docs.aws.amazon.com/cognito/latest/developerguide/authorization-endpoint.html) OAuth Flow. + + + +In your `auth/resource.ts` file, update the +```ts +export const auth = defineAuth({ + loginWith: { + email: true, + externalProviders: { + callbackUrls: ["myapp://callback/"], + logoutUrls: ["myapp://signout/"], + }, + }, +}); +``` + +## Update AndroidManifest.xml + +Add the following activity and queries tag to your app's `AndroidManifest.xml` file, replacing `myapp` with +your redirect URI prefix if necessary: + +```xml + + ... + + + + + + + + + ... + +``` + +## Launch Web UI Sign In + +Sweet! You're now ready to launch sign in with web UI. For now, just add this method to the `onCreate` method of MainActivity: + + + + +```java +Amplify.Auth.signInWithWebUI( + this, + result -> Log.i("AuthQuickStart", result.toString()), + error -> Log.e("AuthQuickStart", error.toString()) +); +``` + + + + +```kotlin +Amplify.Auth.signInWithWebUI( + this, + { Log.i("AuthQuickStart", "Signin OK = $it") }, + { Log.e("AuthQuickStart", "Signin failed", it) } +) +``` + + + + +```kotlin +try { + val result = Amplify.Auth.signInWithWebUI(this) + Log.i("AuthQuickStart", "Signin OK: $result") +} catch (error: AuthException) { + Log.e("AuthQuickStart", "Signin failed", error) +} +``` + + + + +```java +RxAmplify.Auth.signInWithWebUI(this) + .subscribe( + result -> Log.i("AuthQuickStart", result.toString()), + error -> Log.e("AuthQuickStart", error.toString()) + ); +``` + + + + + + + +## Prerequisites + + + +**Note:** Social sign-in (OAuth) functionality is only available in **iOS** and **macOS**. + + When configuring social sign-in, it's important to exercise caution when designating attributes as "required." Different social identity providers have varied scopes in terms of the information they respond back to Cognito with. User pool attributes that are initially set up as "required" cannot be changed later, and may require you to migrate the users or create a new user pool. + + + +An application with a minimum target of **iOS 13.0** and/or **macOS 10.15** with Amplify libraries integrated, using **Xcode 14.1** or later. + +For a full example, please follow the [project setup walkthrough](/[platform]/start/project-setup/prerequisites/). + + + +To use Auth in a macOS project, you'll need to enable the Keychain Sharing capability. In Xcode, navigate to **your application target** > **Signing & Capabilities** > **+ Capability**, then select **Keychain Sharing.** + +This capability is required because Auth uses the Data Protection Keychain on macOS as a platform best practice. +See [TN3137: macOS keychain APIs and implementations](https://developer.apple.com/documentation/technotes/tn3137-on-mac-keychains) for more information on how Keychain works on macOS and the Keychain Sharing entitlement. + +For more information on adding capabilities to your application, see [Xcode Capabilities](https://developer.apple.com/documentation/xcode/capabilities). + + + +## Configure Auth Category + + + +This library's Cognito plugin currently supports the [Authorization Code Grant](https://docs.aws.amazon.com/cognito/latest/developerguide/authorization-endpoint.html) OAuth Flow. + + + +Update the `auth/resource.ts` file like the following to enable the sign-in and sign-out capabilities with a web ui. + +```ts +export const auth = defineAuth({ + loginWith: { + email: true, + externalProviders: { + callbackUrls: ["myapp://callback/"], + logoutUrls: ["myapp://signout/"], + }, + }, +}); +``` +## Update Info.plist + +Signin with web UI require the Amplify plugin to show up the signin UI inside a webview. After the signin process is complete it will redirect back to your app. +You have to enable this in your app's `Info.plist`. Right click Info.plist and then choose Open As > Source Code. Add the following entry in the URL scheme: + +```xml + + + + + + + + + CFBundleURLTypes + + + CFBundleURLSchemes + + myapp + + + + + + +``` + +When creating a new SwiftUI app using Xcode 13 no longer require configuration files such as the Info.plist. If you are missing this file, click on the project target, under Info, Url Types, and click '+' to add a new URL Type. Add `myapp` to the URL Schemes. You should see the Info.plist file now with the entry for CFBundleURLSchemes. + +## Launch Web UI Sign In + +You're now ready to launch sign in with web UI. The `signInWithWebUI` api require a presentationAnchor and for an iOS app it will be the main UIWindow of the app. The example code below assume that you are in a UIViewController where you can fetch the UIWindow instance by `self.view.window`. + + + + + +```swift +func signInWithWebUI() async { + do { + let signInResult = try await Amplify.Auth.signInWithWebUI(presentationAnchor: self.view.window!) + if signInResult.isSignedIn { + print("Sign in succeeded") + } + } catch let error as AuthError { + print("Sign in failed \(error)") + } catch { + print("Unexpected error: \(error)") + } +} +``` + + + + + +```swift +func signInWithWebUI() -> AnyCancellable { + Amplify.Publisher.create { + try await Amplify.Auth.signInWithWebUI(presentationAnchor: self.view.window!) + }.sink { + if case let .failure(authError) = $0 { + print("Sign in failed \(authError)") + } + } + receiveValue: { signInResult in + if signInResult.isSignedIn { + print("Sign in succeeded") + } + } +} +``` + + + + + +### Prefer private session during signIn + +Starting Amplify 1.6.0, `Amplify.Auth.signInWithWebUI` automatically uses [ASWebAuthenticationSession](https://developer.apple.com/documentation/authenticationservices/aswebauthenticationsession) internally for iOS 13.0+. For older iOS versions, it will fall back to [SFAuthenticationSession](https://developer.apple.com/documentation/safariservices/sfauthenticationsession). +This release also introduces a new `preferPrivateSession` flag to `AWSAuthWebUISignInOptions` during the sign in flow. If `preferPrivateSession` is set to `true` during sign in, the user will not see a web view displayed when they sign out. `preferPrivateSession` will set [ASWebAuthenticationSession.prefersEphemeralWebBrowserSession](https://developer.apple.com/documentation/authenticationservices/aswebauthenticationsession/3237231-prefersephemeralwebbrowsersessio) internally and the authentication session will be private if the user's preferred browser supports it. + +```swift +try await Amplify.Auth.signInWithWebUI( + presentationAnchor: self.view.window!, + options: .preferPrivateSession() +) { + ... +} +``` + + + +## Prerequisites + +* An app set up according to the [getting started walkthrough](/[platform]/build-a-backend/auth/set-up-auth/) + + + When configuring Social sign-in, it's important to exercise caution when designating attributes as "required." Different social identity providers have varied scopes in terms of the information they respond back to Cognito with. User pool attributes that are initially set up as "required" cannot be changed later, and may require you to migrate the users or create a new user pool. + + +## Configure Auth Category + + + +This library's Cognito plugin currently supports the [Authorization Code Grant](https://docs.aws.amazon.com/cognito/latest/developerguide/authorization-endpoint.html) OAuth Flow. + + + +Update the `auth/resource.ts` file like the following to enable the sign-in and sign-out capabilities with a web ui. + +```ts +export const auth = defineAuth({ + loginWith: { + email: true, + externalProviders: { + callbackUrls: ["myapp://callback/"], + logoutUrls: ["myapp://signout/"], + }, + }, +}); +``` + +## How It Works + +Sign-in with web UI will display the sign-in UI inside a webview. After the sign-in process is complete, the sign-in UI will redirect back to your app. + +## Platform Setup + +### Web + +To use Hosted UI in your Flutter web application locally, you must run the app with the `--web-port=3000` argument (with the value being whichever port you assigned to localhost host when configuring your redirect URIs). + +### Android + +Add the following `queries` element to the `AndroidManifest.xml` file in your app's `android/app/src/main` directory, as well as the following `intent-filter` to the `MainActivity` in the same file. + +Replace `myapp` with your redirect URI scheme as necessary: + +```xml + + + + + + + ... + + + + + + + + + ... + +``` + +### macOS + +Open XCode and enable the App Sandbox capability and then select "Incoming Connections (Server)" under "Network". + +![Incoming Connections setting selected in the App Sandbox section of the runner signing and capabilities tab.](/images/project-setup/flutter/mac/xcode-entitlements.png) + +### iOS, Windows and Linux + +No specific platform configuration is required. + +## Launch Web UI Sign In + +You're now ready to launch sign in with web UI. + +```dart +Future signInWithWebUI() async { + try { + final result = await Amplify.Auth.signInWithWebUI(); + safePrint('Sign in result: $result'); + } on AuthException catch (e) { + safePrint('Error signing in: ${e.message}'); + } +} +``` + +You can also specify a provider with the `provider` attribute: + +```dart +Future signInWithWebUIProvider() async { + try { + final result = await Amplify.Auth.signInWithWebUI( + provider: AuthProvider.google, + ); + safePrint('Result: $result'); + } on AuthException catch (e) { + safePrint('Error signing in: ${e.message}'); + } +} +``` + +Amplify Flutter currently supports the following social sign-in providers: + * Google + * Facebook + * Login With Amazon + * Apple + +### Prefer private session during signIn on iOS. + +Amplify.Auth.signInWithWebUI uses [ASWebAuthenticationSession](https://developer.apple.com/documentation/authenticationservices/aswebauthenticationsession) internally for iOS. ASWebAuthenticationSession has a property, [prefersEphemeralWebBrowserSession](https://developer.apple.com/documentation/authenticationservices/aswebauthenticationsession/3237231-prefersephemeralwebbrowsersessio) which can be used to indicate whether the session should ask the browser for a private authentication session. To set this flag to true, set `preferPrivateSession` to true using `CognitoSignInWithWebUIPluginOptions`. + +This will bypass the permissions dialog that is displayed to the end user during sign in and sign out. However, it will also prevent reuse of existing sessions from the user's browser. For example, if the user is logged into Google in their browser and try to sign in using Google in your app, they would now need to re-enter their credentials. + +```dart +Future signInWithWebUIAndPrivateSession() async { + await Amplify.Auth.signInWithWebUI( + options: const SignInWithWebUIOptions( + pluginOptions: CognitoSignInWithWebUIPluginOptions( + isPreferPrivateSession: true, + ), + ), + ); +} +``` + + From 1ec2dbf2b527806e91f7d3fb106e1294b3f2cbfe Mon Sep 17 00:00:00 2001 From: josef Date: Thu, 2 May 2024 09:46:21 -0700 Subject: [PATCH 02/17] remove callouts for "under active development" (#7435) --- .../add-aws-services/overriding-resources/index.mdx | 6 ------ .../predictions/set-up-predictions/index.mdx | 8 +------- .../grant-lambda-function-access-to-api/index.mdx | 6 ------ 3 files changed, 1 insertion(+), 19 deletions(-) diff --git a/src/pages/[platform]/build-a-backend/add-aws-services/overriding-resources/index.mdx b/src/pages/[platform]/build-a-backend/add-aws-services/overriding-resources/index.mdx index 9c6812a3e18..e7cc8162461 100644 --- a/src/pages/[platform]/build-a-backend/add-aws-services/overriding-resources/index.mdx +++ b/src/pages/[platform]/build-a-backend/add-aws-services/overriding-resources/index.mdx @@ -74,12 +74,6 @@ Most L1 and L2 AWS CDK constructs that are used by the `define*` functions are a ## Example - Grant access permissions between resources - - -**Under active development**: We are working to improve the experience of granting one resource access to another. For the time being, overrides can be used to achieve this. - - - Consider the case that we want to grant a function created by `defineFunction` access to call the Cognito user pool created by `defineAuth`. This can be accomplished with the following overrides. ```ts title="amplify/backend.ts" diff --git a/src/pages/[platform]/build-a-backend/add-aws-services/predictions/set-up-predictions/index.mdx b/src/pages/[platform]/build-a-backend/add-aws-services/predictions/set-up-predictions/index.mdx index 53e25ffa6d1..871404467a0 100644 --- a/src/pages/[platform]/build-a-backend/add-aws-services/predictions/set-up-predictions/index.mdx +++ b/src/pages/[platform]/build-a-backend/add-aws-services/predictions/set-up-predictions/index.mdx @@ -26,12 +26,6 @@ export function getStaticProps(context) { }; } - - -**Under active development:** The `addOutput` method for Amplify Gen 2 is under active development. The experience may change between versions of `@aws-amplify/backend`. Try it out and provide feedback at https://github.com/aws-amplify/amplify-backend/issues/new/choose - - - ## Prerequisites @@ -446,7 +440,7 @@ Amplify configured with Auth and Predictions plugins -To install the Amplify library to use predictions features, run the following commands in your project’s root folder: +To install the Amplify library to use predictions features, run the following commands in your project's root folder: ```bash title="Terminal" showLineNumbers={false} npm add aws-amplify diff --git a/src/pages/[platform]/build-a-backend/data/customize-authz/grant-lambda-function-access-to-api/index.mdx b/src/pages/[platform]/build-a-backend/data/customize-authz/grant-lambda-function-access-to-api/index.mdx index 6e52ac00f17..51fa0797d19 100644 --- a/src/pages/[platform]/build-a-backend/data/customize-authz/grant-lambda-function-access-to-api/index.mdx +++ b/src/pages/[platform]/build-a-backend/data/customize-authz/grant-lambda-function-access-to-api/index.mdx @@ -86,12 +86,6 @@ Function access can only be configured on the schema object. It cannot be config ## Access the API using `aws-amplify` - - -**Under active development:** Configuring the `aws-amplify` data client is under active development. The current experience has rough edges and may change between versions of `@aws-amplify/backend`. Try it out and provide feedback at https://github.com/aws-amplify/amplify-backend/issues/new/choose - - - In the handler file for your function, configure the Amplify data client ```ts title="amplify/functions/data-access.ts" From 7a88c3916cffcb18a11acc16af0731806c3dfbc4 Mon Sep 17 00:00:00 2001 From: Chris Bonifacio Date: Thu, 2 May 2024 12:48:08 -0400 Subject: [PATCH 03/17] Cbonif/review-auth-rules (#7439) * corrections to data modeling page * review of auth rules --- .../data/customize-authz/multi-user-data-access/index.mdx | 4 ++-- .../data/customize-authz/public-data-access/index.mdx | 6 +++--- .../customize-authz/signed-in-user-data-access/index.mdx | 8 ++++---- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/pages/[platform]/build-a-backend/data/customize-authz/multi-user-data-access/index.mdx b/src/pages/[platform]/build-a-backend/data/customize-authz/multi-user-data-access/index.mdx index 172e3bd589f..df8a81958d3 100644 --- a/src/pages/[platform]/build-a-backend/data/customize-authz/multi-user-data-access/index.mdx +++ b/src/pages/[platform]/build-a-backend/data/customize-authz/multi-user-data-access/index.mdx @@ -33,7 +33,7 @@ The `ownersDefinedIn` rule grants a set of users access to a record by automatic ## Add multi-user authorization rule -If you want to grant a set of users access to a record, you use the `ownersDefinedIn` rule. This automatically creates a `owner: a.string().array()` field to store the allowed owners. +If you want to grant a set of users access to a record, you use the `ownersDefinedIn` rule. This automatically creates a `owners: a.string().array()` field to store the allowed owners. ```ts title="amplify/data/resource.ts" const schema = a.schema({ @@ -70,7 +70,7 @@ const { errors, data: newTodo } = await client.models.Todo.create( await client.models.Todo.update( { id: newTodo.id, - owner: [...(newTodo.owner as string[]), otherUserId], + owners: [...(newTodo.owners as string[]), otherUserId], }, // highlight-start { diff --git a/src/pages/[platform]/build-a-backend/data/customize-authz/public-data-access/index.mdx b/src/pages/[platform]/build-a-backend/data/customize-authz/public-data-access/index.mdx index 2c564e0a437..37d75288f49 100644 --- a/src/pages/[platform]/build-a-backend/data/customize-authz/public-data-access/index.mdx +++ b/src/pages/[platform]/build-a-backend/data/customize-authz/public-data-access/index.mdx @@ -81,16 +81,16 @@ const schema = a.schema({ In your application, you can perform CRUD operations against the model using `client.models.` with the `iam` auth mode. -If you're not using the auto-generated **amplifyconfiguration.json** file, then you must set the Amplify Library resource configuration's `allowGuestAccess` flag to `true`. This lets the Amplify Library use the unauthenticated role from your Cognito identity pool when your user isn't logged in. +If you're not using the auto-generated **amplify_outputs.json** file, then you must set the Amplify Library resource configuration's `allowGuestAccess` flag to `true`. This lets the Amplify Library use the unauthenticated role from your Cognito identity pool when your user isn't logged in. ```ts title="src/App.tsx" import { Amplify } from "aws-amplify"; -import config from "../amplifyconfiguration.json"; +import outputs from "../amplify_outputs.json"; Amplify.configure( { - ...config, + ...outputs, Auth: { Cognito: { identityPoolId: config.aws_cognito_identity_pool_id, diff --git a/src/pages/[platform]/build-a-backend/data/customize-authz/signed-in-user-data-access/index.mdx b/src/pages/[platform]/build-a-backend/data/customize-authz/signed-in-user-data-access/index.mdx index b0b914a8a30..0b647a5f8b6 100644 --- a/src/pages/[platform]/build-a-backend/data/customize-authz/signed-in-user-data-access/index.mdx +++ b/src/pages/[platform]/build-a-backend/data/customize-authz/signed-in-user-data-access/index.mdx @@ -28,14 +28,14 @@ export function getStaticProps(context) { }; } -The `private` authorization strategy restricts record access to only signed-in users authenticated through IAM, Cognito, or OpenID Connect, applying the authorization rule to all users. It provides a simple way to make data private to all authenticated users. +The `authenticated` authorization strategy restricts record access to only signed-in users authenticated through IAM, Cognito, or OpenID Connect, applying the authorization rule to all users. It provides a simple way to make data private to all authenticated users. ## Add signed-in user authorization rule -You can use the `private` authorization strategy to restrict a record's access to every signed-in user. +You can use the `authenticated` authorization strategy to restrict a record's access to every signed-in user. -**Note:** If you want to restrict a record's access to a specific user, see [Per-user/per-owner data access](/[platform]/build-a-backend/data/customize-authz/per-user-per-owner-data-access/). The `private` authorization strategy detailed on this page applies the authorization rule for data access to **every** signed-in user. +**Note:** If you want to restrict a record's access to a specific user, see [Per-user/per-owner data access](/[platform]/build-a-backend/data/customize-authz/per-user-per-owner-data-access/). The `authenticated` authorization strategy detailed on this page applies the authorization rule for data access to **every** signed-in user. In the example below, anyone with a valid JWT token from the Cognito user pool is allowed access to all Todos. @@ -109,4 +109,4 @@ const { errors, data: newTodo } = await client.models.Todo.create( ); ``` -In addition, you can also use OpenID Connect with `private` authorization. See [OpenID Connect as an authorization provider](/[platform]/build-a-backend/data/customize-authz/using-oidc-authorization-provider/). +In addition, you can also use OpenID Connect with `authenticated` authorization. See [OpenID Connect as an authorization provider](/[platform]/build-a-backend/data/customize-authz/using-oidc-authorization-provider/). From 23dd0524763cd1908fb4f7e7660abea0956574f6 Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Thu, 2 May 2024 13:26:03 -0400 Subject: [PATCH 04/17] fix(geo): remove android and swift platforms from geofence page (#7450) --- .../add-aws-services/geo/configure-geofencing/index.mdx | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/pages/[platform]/build-a-backend/add-aws-services/geo/configure-geofencing/index.mdx b/src/pages/[platform]/build-a-backend/add-aws-services/geo/configure-geofencing/index.mdx index 14a90b78983..fd7c4220bf3 100644 --- a/src/pages/[platform]/build-a-backend/add-aws-services/geo/configure-geofencing/index.mdx +++ b/src/pages/[platform]/build-a-backend/add-aws-services/geo/configure-geofencing/index.mdx @@ -4,12 +4,10 @@ export const meta = { title: 'Configure a geofence collection', description: 'Create and manage collections of Geofences', platforms: [ - 'android', 'angular', 'javascript', 'nextjs', 'react', - 'swift', 'vue' ] }; @@ -100,7 +98,7 @@ backend.addOutput({ ## Geofence Collection Pricing Plan -The pricing plan for the Geofence Collection will be set to `RequestBasedUsage`. We advice you to go through the [location service pricing](https://aws.amazon.com/location/pricing/) along with the [location service terms](https://aws.amazon.com/service-terms/) (_82.5 section_) to learn more about the pricing plan. +The pricing plan for the Geofence Collection will be set to `RequestBasedUsage`. We advice you to go through the [location service pricing](https://aws.amazon.com/location/pricing/) along with the [location service terms](https://aws.amazon.com/service-terms/) (_82.5 section_) to learn more about the pricing plan. #### Group access From fdaeab6e3d7e3c5f1bc66aa03b9d3ca8191f3f40 Mon Sep 17 00:00:00 2001 From: Michael Law <1365977+lawmicha@users.noreply.github.com> Date: Thu, 2 May 2024 13:30:41 -0400 Subject: [PATCH 05/17] fix(swift): refactor swift getting started (#7445) --- .../[platform]/start/quickstart/index.mdx | 340 ++++++++++-------- 1 file changed, 193 insertions(+), 147 deletions(-) diff --git a/src/pages/[platform]/start/quickstart/index.mdx b/src/pages/[platform]/start/quickstart/index.mdx index 2106a49f428..749602c6891 100644 --- a/src/pages/[platform]/start/quickstart/index.mdx +++ b/src/pages/[platform]/start/quickstart/index.mdx @@ -1572,42 +1572,34 @@ struct MyApp: App { var body: some Scene { WindowGroup { - Authenticator { state in - VStack { - Button("Sign out") { - Task { - await state.signOut() - } - } - Spacer() - Button(action: { - Task { - await createTodo() - await listTodos() - } - }) { - HStack { - Text("Add a New Todo") - Image(systemName: "plus") - } - } - .accessibilityLabel("New Todo") - } - } + ContentView() } } +} +``` - func createTodo() async { - } +Update `ContentView` with the following code: +```swift +import Amplify +import Authenticator - func listTodo() async { +struct ContentView: View { + var body: some View { + Authenticator { state in + VStack { + Button("Sign out") { + Task { + await state.signOut() + } + } + } + } } } ``` The Authenticator component auto-detects your auth backend settings and renders the correct UI state based on the auth backend's authentication flow. - Run your application in your local environment again. You should be presented with a login experience now. -The code above will fetch the todos once the VStack is shown. It will also create a todo and update the todo list each time a todo is created. +The code will create a todo and update the todo list each time a todo is created. -Next step is to update and delete the todos. For that, create `updateTodo` and `deleteTodo` functions in the `MyAmplifyAppApp.swift` file with the following code: +Next step is to update and delete the todos. For that, create `updateTodo` and `deleteTodo` functions in the `TodoViewModel.swift` file with the following code: -```swift -func deleteTodo(todo: Todo) async { - do { - let result = try await Amplify.API.mutate(request: .delete(todo)) - switch result { - case .success(let todo): - print("Successfully deleted todo: \(todo)") - case .failure(let error): - print("Got failed result with \(error.errorDescription)") +```swift title="TodoViewModel.swift" +@MainActor +class TodoViewModel: ObservableObject { + @Published var todos: [Todo] = [] + + func createTodo() { + // ... + } + + func listTodos() { + // ... + } + + func deleteTodos(indexSet: IndexSet) { + for index in indexSet { + let todo = todos[index] + Task { + do { + let result = try await Amplify.API.mutate(request: .delete(todo)) + switch result { + case .success(let todo): + print("Successfully deleted todo: \(todo)") + case .failure(let error): + print("Got failed result with \(error.errorDescription)") + } + } catch let error as APIError { + print("Failed to deleted todo: ", error) + } catch { + print("Unexpected error: \(error)") + } + } } - } catch let error as APIError { - print("Failed to deleted todo: ", error) - } catch { - print("Unexpected error: \(error)") } -} -func updateTodo(todo: Todo) async { - do { - let result = try await Amplify.API.mutate(request: .update(todo)) - switch result { - case .success(let todo): - print("Successfully updated todo: \(todo)") - case .failure(let error): - print("Got failed result with \(error.errorDescription)") + func updateTodo(todo: Todo) { + Task { + do { + let result = try await Amplify.API.mutate(request: .update(todo)) + switch result { + case .success(let todo): + print("Successfully updated todo: \(todo)") + case .failure(let error): + print("Got failed result with \(error.errorDescription)") + } + } catch let error as APIError { + print("Failed to updated todo: ", error) + } catch { + print("Unexpected error: \(error)") + } } - } catch let error as APIError { - print("Failed to updated todo: ", error) - } catch { - print("Unexpected error: \(error)") } } + ``` -Lastly, update the `List` in the `MyAmplifyAppApp.swift` file with the following code: +Update the `List` in the `ContentView.swift` file with the following code: -```swift -List(todos, id: \.id) { todo in - @State var isToggled = todo.isDone! - Toggle(isOn: $isToggled - ) { - Text(todo.content!) - }.onTapGesture { - var updatedTodo = todos.first {$0.id == todo.id}! - updatedTodo.isDone = !todo.isDone! - Task { - await updateTodo(todo: updatedTodo) - await listTodos() +```swift title="ContentView.swift" +struct ContentView: View { + @StateObject var vm = TodoViewModel() + + var body: some View { + Authenticator { state in + VStack { + // ... Sign out Button + List { + ForEach($vm.todos, id: \.id) { todo in + TodoRow(vm: vm, todo: todo) + }.onDelete { indexSet in + vm.deleteTodos(indexSet: indexSet) + vm.listTodos() + } + } + // ... Add new Todo button + } } } - .onChange(of: isToggled) { oldValue, newValue in - var updatedTodo = todos.first {$0.id == todo.id}! - updatedTodo.isDone = newValue - Task { - await updateTodo(todo: updatedTodo) - await listTodos() +} +``` + +Lastly, create a new file called `TodoRow.swift` with the following code: + +```swift title="TodoRow.swift" +struct TodoRow: View { + @ObservedObject var vm: TodoViewModel + @Binding var todo: Todo + + var body: some View { + Toggle(isOn: $todo.isDone) { + Text(todo.content ?? "") } - } - .toggleStyle(.switch) - .onLongPressGesture { - Task { - await deleteTodo(todo: todo) - await listTodos() + .toggleStyle(SwitchToggleStyle()) + .onChange(of: todo.isDone) { _, newValue in + var updatedTodo = todo + updatedTodo.isDone = newValue + vm.updateTodo(todo: updatedTodo) + vm.listTodos() } } } ``` -This will update the UI to show a toggle to update the todo and a long press gesture to delete the todo. Now if you run the application you should see the following flow. +This will update the UI to show a toggle to update the todo `isDone` and a swipe to delete the todo. Now if you run the application you should see the following flow. ## Set up Analytics backend -Use the [AWS CDK](https://docs.aws.amazon.com/cdk/latest/guide/home.html) to create an analytics resource powered by [Amazon Pinpoint](https://aws.amazon.com/pinpoint/). +Use the [AWS CDK](https://docs.aws.amazon.com/cdk/latest/guide/home.html) to create an analytics resource powered by [Amazon Pinpoint](https://aws.amazon.com/pinpoint/). ```ts title="amplify/backend.ts" import { auth } from "./auth/resource"; @@ -85,9 +85,9 @@ import { CfnApp } from "aws-cdk-lib/aws-pinpoint"; import { Stack } from "aws-cdk-lib/core"; const backend = defineBackend({ - auth, + auth, data, - // additional resources + // additional resources }); const analyticsStack = backend.createStack("analytics-stack"); @@ -195,7 +195,7 @@ Amplify.configure({ ``` - + ```js title="pages/_app.tsx" import { Amplify } from 'aws-amplify'; import { record } from 'aws-amplify/analytics'; @@ -230,7 +230,7 @@ init() { do { try Amplify.add(plugin: AWSCognitoAuthPlugin()) try Amplify.add(plugin: AWSPinpointAnalyticsPlugin()) - try Amplify.configure() + try Amplify.configure(with: .amplifyOutputs) print("Amplify configured with Auth and Analytics plugins") } catch { print("Failed to initialize Amplify with \(error)") @@ -260,7 +260,7 @@ func application( do { try Amplify.add(plugin: AWSCognitoAuthPlugin()) try Amplify.add(plugin: AWSPinpointAnalyticsPlugin()) - try Amplify.configure() + try Amplify.configure(with: .amplifyOutputs) print("Amplify configured with Auth and Analytics plugins") } catch { print("Failed to initialize Amplify with \(error)") @@ -367,7 +367,7 @@ Future main() async { class MyApp extends StatefulWidget { const MyApp({Key? key}): super(key: key); - + // ... } ``` @@ -428,7 +428,7 @@ import com.amplifyframework.analytics.pinpoint.AWSPinpointAnalyticsPlugin import com.amplifyframework.auth.cognito.AWSCognitoAuthPlugin import com.amplifyframework.core.Amplify import com.amplifyframework.core.configuration.AmplifyOutputs -``` +``` ```kotlin Amplify.addPlugin(AWSCognitoAuthPlugin()) diff --git a/src/pages/[platform]/build-a-backend/add-aws-services/geo/set-up-geo/index.mdx b/src/pages/[platform]/build-a-backend/add-aws-services/geo/set-up-geo/index.mdx index eed3f6c17c6..bca830964f4 100644 --- a/src/pages/[platform]/build-a-backend/add-aws-services/geo/set-up-geo/index.mdx +++ b/src/pages/[platform]/build-a-backend/add-aws-services/geo/set-up-geo/index.mdx @@ -101,12 +101,12 @@ backend.addOutput({ ## Configure your application - + To display a map in your application, you can use the [Amplify React MapView component](https://ui.docs.amplify.aws/react/components/geo) or the [MapLibre GL](https://github.com/maplibre/maplibre-gl-js) with `maplibre-gl-js-amplify` libraries are required. Install the necessary dependencies by running the following command: -```bash title="Terminal" showLineNumbers={false} +```bash title="Terminal" showLineNumbers={false} npm add aws-amplify @aws-amplify/geo ``` @@ -164,7 +164,7 @@ For a full example, please follow the [project setup walkthrough](/[platform]/st -visionOS support is currently in **preview** and can be used by targeting the [`visionos-preview`](https://github.com/aws-amplify/amplify-swift/tree/visionos-preview) branch. +visionOS support is currently in **preview** and can be used by targeting the [`visionos-preview`](https://github.com/aws-amplify/amplify-swift/tree/visionos-preview) branch. As new Xcode 15 beta versions are released, the branch will be updated with any necessary fixes on a best effort basis. For more information on how to use the `visionos-preview` branch, see [Platform Support](https://github.com/aws-amplify/amplify-swift/tree/visionos-preview#platform-support). @@ -331,7 +331,7 @@ func configureAmplify() { do { try Amplify.add(plugin: AWSCognitoAuthPlugin()) try Amplify.add(plugin: AWSLocationGeoPlugin()) - try Amplify.configure() + try Amplify.configure(with: .amplifyOutputs) print("Initialized Amplify"); } catch { print("Could not initialize Amplify: \(error)") @@ -382,7 +382,7 @@ Initialized Amplify -**Notes:** +**Notes:** - If you want to use existing Amazon Location Service resources [follow this guide](/[platform]/build-a-backend/add-aws-services/geo/existing-resources/) instead. - If you want to use Amazon Location Service APIs not directly supported by Geo, use the [escape hatch](/[platform]/build-a-backend/add-aws-services/geo/amazon-location-sdk/) to access the Amazon Location Service SDK. diff --git a/src/pages/[platform]/build-a-backend/add-aws-services/logging/change-local-storage/index.mdx b/src/pages/[platform]/build-a-backend/add-aws-services/logging/change-local-storage/index.mdx index 24cf12be44e..53881e4fc94 100644 --- a/src/pages/[platform]/build-a-backend/add-aws-services/logging/change-local-storage/index.mdx +++ b/src/pages/[platform]/build-a-backend/add-aws-services/logging/change-local-storage/index.mdx @@ -90,7 +90,7 @@ do { let loggingConfiguration = AWSCloudWatchLoggingPluginConfiguration(logGroupName: "", region: "", localStoreMaxSizeInMB: 2) let loggingPlugin = AWSCloudWatchLoggingPlugin(loggingPluginConfiguration: loggingConfiguration) try Amplify.add(plugin: loggingPlugin) - try Amplify.configure() + try Amplify.configure(with: .amplifyOutputs) } catch { assert(false, "Error initializing Amplify: \(error)") } diff --git a/src/pages/[platform]/build-a-backend/add-aws-services/logging/flush-logs/index.mdx b/src/pages/[platform]/build-a-backend/add-aws-services/logging/flush-logs/index.mdx index 514d5e80e69..41c867d902a 100644 --- a/src/pages/[platform]/build-a-backend/add-aws-services/logging/flush-logs/index.mdx +++ b/src/pages/[platform]/build-a-backend/add-aws-services/logging/flush-logs/index.mdx @@ -122,7 +122,7 @@ do { let loggingConfiguration = AWSCloudWatchLoggingPluginConfiguration(logGroupName: "", region: "", flushIntervalInSeconds: 120) let loggingPlugin = AWSCloudWatchLoggingPlugin(loggingPluginConfiguration: loggingConfiguration) try Amplify.add(plugin: loggingPlugin) - try Amplify.configure() + try Amplify.configure(with: .amplifyOutputs) } catch { assert(false, "Error initializing Amplify: \(error)") } @@ -145,7 +145,7 @@ You can choose at anytime to flush the log messages that are saved locally on th - + @@ -227,7 +227,7 @@ import AWSCloudWatchLoggingPlugin Execute the flush log function from the plugin. ```swift -let cloudWatchPlugin = try Amplify.Logging.getPlugin(for: "awsCloudWatchLoggingPlugin") as? AWSCloudWatchLoggingPlugin +let cloudWatchPlugin = try Amplify.Logging.getPlugin(for: "awsCloudWatchLoggingPlugin") as? AWSCloudWatchLoggingPlugin try await cloudWatchPlugin?.flushLogs() ``` diff --git a/src/pages/[platform]/build-a-backend/add-aws-services/logging/remote-configuration/index.mdx b/src/pages/[platform]/build-a-backend/add-aws-services/logging/remote-configuration/index.mdx index 30b7859328d..60fe13c743f 100644 --- a/src/pages/[platform]/build-a-backend/add-aws-services/logging/remote-configuration/index.mdx +++ b/src/pages/[platform]/build-a-backend/add-aws-services/logging/remote-configuration/index.mdx @@ -316,7 +316,7 @@ do { let remoteConfigProvider = DefaultRemoteLoggingConstraintsProvider(endpoint: endpointUrl, region: "") let loggingPlugin = AWSCloudWatchLoggingPlugin(remoteLoggingConstraintsProvider: remoteConfigProvider) try Amplify.add(plugin: loggingPlugin) - try Amplify.configure() + try Amplify.configure(with: .amplifyOutputs) } catch { assert(false, "Error initializing Amplify: \(error)") } diff --git a/src/pages/[platform]/build-a-backend/add-aws-services/logging/set-up-logging/index.mdx b/src/pages/[platform]/build-a-backend/add-aws-services/logging/set-up-logging/index.mdx index ae9ad3dad1d..d0aee6b2bf7 100644 --- a/src/pages/[platform]/build-a-backend/add-aws-services/logging/set-up-logging/index.mdx +++ b/src/pages/[platform]/build-a-backend/add-aws-services/logging/set-up-logging/index.mdx @@ -53,7 +53,7 @@ For a full example, please follow the [mobile support walkthrough](/swift/start/ -visionOS support is currently in **preview** and can be used by targeting the [`visionos-preview`](https://github.com/aws-amplify/amplify-swift/tree/visionos-preview) branch. +visionOS support is currently in **preview** and can be used by targeting the [`visionos-preview`](https://github.com/aws-amplify/amplify-swift/tree/visionos-preview) branch. As new Xcode 15 beta versions are released, the branch will be updated with any necessary fixes on a best effort basis. For more information on how to use the `visionos-preview` branch, see [Platform Support](https://github.com/aws-amplify/amplify-swift/tree/visionos-preview#platform-support). @@ -274,7 +274,7 @@ public class MyAmplifyApp extends Application { {' '} - + To use the Amplify Logger and Amplify Auth categories in your app, you need to create and configure their corresponding plugins by calling the `Amplify.addPlugin()` and `Amplify.configure()` methods. Add the following imports to the top of your main `Application` file: @@ -446,7 +446,7 @@ init() { do { try Amplify.add(plugin: AWSCognitoAuthPlugin()) try Amplify.add(plugin: AWSCloudWatchLoggingPlugin()) - try Amplify.configure() + try Amplify.configure(with: .amplifyOutputs) } catch { assert(false, "Error initializing Amplify: \(error)") } @@ -468,7 +468,7 @@ import AWSCognitoAuthPlugin import AWSCloudWatchLoggingPlugin ``` -Add the following code to its initializer. If there is none, you can create a default `init`. The `` and `` are values you specified in the CDK construct as part of provisioning your backend resources. These values can also be found at the end of the output logs when deploying the sample CDK construct. +Add the following code to its initializer. If there is none, you can create a default `init`. The `` and `` are values you specified in the CDK construct as part of provisioning your backend resources. These values can also be found at the end of the output logs when deploying the sample CDK construct. The example below configures the logging plugin to automatically send all logs at log level `ERROR` at 60 seconds interval and store logs locally up to 1MB. ```swift @@ -477,7 +477,7 @@ init() { let loggingConfiguration = AWSCloudWatchLoggingPluginConfiguration(logGroupName: "", region: "", localStoreMaxSizeInMB: 1, flushIntervalInSeconds: 60) let loggingPlugin = AWSCloudWatchLoggingPlugin(loggingPluginConfiguration: loggingConfiguration) try Amplify.add(plugin: loggingPlugin) - try Amplify.configure() + try Amplify.configure(with: .amplifyOutputs) } catch { assert(false, "Error initializing Amplify: \(error)") } diff --git a/src/pages/[platform]/build-a-backend/add-aws-services/rest-api/customize-authz/index.mdx b/src/pages/[platform]/build-a-backend/add-aws-services/rest-api/customize-authz/index.mdx index 3e494b9db13..b5ea0a20f97 100644 --- a/src/pages/[platform]/build-a-backend/add-aws-services/rest-api/customize-authz/index.mdx +++ b/src/pages/[platform]/build-a-backend/add-aws-services/rest-api/customize-authz/index.mdx @@ -317,7 +317,7 @@ class MyOIDCAuthProvider : AmplifyOIDCAuthProvider { throw error } } - + throw AuthError.unknown("Could not retrieve Cognito token") } } diff --git a/src/pages/[platform]/build-a-backend/add-aws-services/rest-api/set-up-rest-api/index.mdx b/src/pages/[platform]/build-a-backend/add-aws-services/rest-api/set-up-rest-api/index.mdx index eecf2f96c62..cfa9fecef99 100644 --- a/src/pages/[platform]/build-a-backend/add-aws-services/rest-api/set-up-rest-api/index.mdx +++ b/src/pages/[platform]/build-a-backend/add-aws-services/rest-api/set-up-rest-api/index.mdx @@ -34,7 +34,7 @@ To setup and configure your application with REST API or HTTP API to make reques ## Set up REST API with Lambda Function Create a new directory and a resource file, `amplify/functions/api-function/resource.ts`. Then, define the function with `defineFunction`: - + ```ts title="amplify/functions/api-function/resource.ts" import { defineFunction } from "@aws-amplify/backend"; @@ -173,7 +173,7 @@ backend.addOutput({ ## Set up HTTP API with Lambda Function Create a new directory and a resource file, `amplify/functions/api-function/resource.ts`. Then, define the function with `defineFunction`: - + ```ts title="amplify/functions/api-function/resource.ts" import { defineFunction } from "@aws-amplify/backend"; @@ -327,7 +327,7 @@ backend.addOutput({ Use the package manager of your choice to install the amplify JS library. For example, with `npm`: -```bash title="Terminal" showLineNumbers={false} +```bash title="Terminal" showLineNumbers={false} npm add aws-amplify ``` @@ -346,7 +346,7 @@ Use the package manager of your choice to install the amplify JS library. For ex -```bash title="Terminal" showLineNumbers={false} +```bash title="Terminal" showLineNumbers={false} npm add aws-amplify @aws-amplify/react-native ``` @@ -394,7 +394,7 @@ dependencies: sdk: flutter amplify_flutter: ^1.0.0 amplify_api: ^1.0.0 - amplify_auth_cognito: ^1.0.0 + amplify_auth_cognito: ^1.0.0 ``` @@ -497,7 +497,7 @@ func application( do { try Amplify.add(plugin: AWSCognitoAuthPlugin()) try Amplify.add(plugin: AWSAPIPlugin()) - try Amplify.configure() + try Amplify.configure(with: .amplifyOutputs) print("Amplify configured with API and Auth plugin") } catch { print("Failed to initialize Amplify with \(error)") diff --git a/src/pages/[platform]/build-a-backend/auth/set-up-auth/index.mdx b/src/pages/[platform]/build-a-backend/auth/set-up-auth/index.mdx index ab64c2cdd78..232b6d4dddf 100644 --- a/src/pages/[platform]/build-a-backend/auth/set-up-auth/index.mdx +++ b/src/pages/[platform]/build-a-backend/auth/set-up-auth/index.mdx @@ -306,7 +306,7 @@ npx pod-install ``` -For calling native libraries and platform dependencies from Expo, you need to run the prebuild command for generating the folders for related platforms. +For calling native libraries and platform dependencies from Expo, you need to run the prebuild command for generating the folders for related platforms. ```bash title="Terminal" showLineNumbers={false} npx expo prebuild @@ -365,7 +365,7 @@ flutter pub add amplify_auth_cognito flutter pub add amplify_authenticator ``` -or you can update your `pubspec.yaml` file with the following +or you can update your `pubspec.yaml` file with the following ```yaml environment: @@ -492,10 +492,10 @@ dependencies { ```groovy dependencies { - dependencies { + dependencies { // Authenticator dependency implementation 'com.amplifyframework.ui:authenticator:ANDROID_AUTHENTICATOR_VERSION' - + // Support for Java 8 features coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.0.3' } @@ -595,7 +595,7 @@ An application with Amplify libraries integrated and a minimum target of any of -visionOS support is currently in **preview** and can be used by targeting the [`visionos-preview`](https://github.com/aws-amplify/amplify-swift/tree/visionos-preview) branch. +visionOS support is currently in **preview** and can be used by targeting the [`visionos-preview`](https://github.com/aws-amplify/amplify-swift/tree/visionos-preview) branch. As new Xcode 15 beta versions are released, the branch will be updated with any necessary fixes on a best effort basis. For more information on how to use the `visionos-preview` branch, see [Platform Support](https://github.com/aws-amplify/amplify-swift/tree/visionos-preview#platform-support). @@ -647,7 +647,7 @@ struct MyApp: App { init() { do { try Amplify.add(plugin: AWSCognitoAuthPlugin()) - try Amplify.configure() + try Amplify.configure(with: .amplifyOutputs) } catch { print("Unable to configure Amplify \(error)") } diff --git a/src/pages/[platform]/build-a-backend/data/connect-to-API/index.mdx b/src/pages/[platform]/build-a-backend/data/connect-to-API/index.mdx index 56f64107fee..a543a688482 100644 --- a/src/pages/[platform]/build-a-backend/data/connect-to-API/index.mdx +++ b/src/pages/[platform]/build-a-backend/data/connect-to-API/index.mdx @@ -417,7 +417,7 @@ final lambdaResponse = await Amplify.API.query(request: lambdaRequest).response; ## Set custom request headers -When working with the Amplify Data endpoint, you may need to set request headers for authorization purposes or to pass additional metadata from your frontend to the backend API. +When working with the Amplify Data endpoint, you may need to set request headers for authorization purposes or to pass additional metadata from your frontend to the backend API. @@ -618,7 +618,7 @@ struct CustomInterceptor: URLRequestInterceptor { } let apiPlugin = try AWSAPIPlugin() try Amplify.addPlugin(apiPlugin) -try Amplify.configure() +try Amplify.configure(with: .amplifyOutputs) try apiPlugin.add(interceptor: CustomInterceptor(), for: AWSAPIPlugin.defaultGraphQLAPI) ``` diff --git a/src/pages/[platform]/build-a-backend/data/optimistic-ui/index.mdx b/src/pages/[platform]/build-a-backend/data/optimistic-ui/index.mdx index b4d8019c560..7946cea3726 100644 --- a/src/pages/[platform]/build-a-backend/data/optimistic-ui/index.mdx +++ b/src/pages/[platform]/build-a-backend/data/optimistic-ui/index.mdx @@ -1162,7 +1162,7 @@ struct OptimisticUIApp: App { do { Amplify.Logging.logLevel = .verbose try Amplify.add(plugin: AWSAPIPlugin(modelRegistration: AmplifyModels())) - try Amplify.configure() + try Amplify.configure(with: .amplifyOutputs) print("Amplify configured with API, Storage, and Auth plugins!") } catch { print("Failed to initialize Amplify with \(error)") diff --git a/src/pages/[platform]/build-a-backend/data/set-up-data/index.mdx b/src/pages/[platform]/build-a-backend/data/set-up-data/index.mdx index c6cd691ccaf..f0af72a15da 100644 --- a/src/pages/[platform]/build-a-backend/data/set-up-data/index.mdx +++ b/src/pages/[platform]/build-a-backend/data/set-up-data/index.mdx @@ -251,7 +251,7 @@ struct MyAmplifyApp: App { let awsApiPlugin = AWSAPIPlugin(modelRegistration: AmplifyModels()) do { try Amplify.add(plugin: awsApiPlugin) - try Amplify.configure() + try Amplify.configure(with: .amplifyOutputs) print("Initialized Amplify"); } catch { // simplified error handling for the tutorial diff --git a/src/pages/[platform]/build-a-backend/storage/set-up-storage/index.mdx b/src/pages/[platform]/build-a-backend/storage/set-up-storage/index.mdx index 744450b51cb..af9679dfa77 100644 --- a/src/pages/[platform]/build-a-backend/storage/set-up-storage/index.mdx +++ b/src/pages/[platform]/build-a-backend/storage/set-up-storage/index.mdx @@ -53,7 +53,7 @@ export const storage = defineStorage({ }); ``` -Import your storage definition in your `amplify/backend.ts` file that contains your backend definition. Add storage to `defineBackend`. +Import your storage definition in your `amplify/backend.ts` file that contains your backend definition. Add storage to `defineBackend`. ```ts title="amplify/backend.ts" import { defineBackend } from '@aws-amplify/backend'; @@ -81,12 +81,12 @@ git push By default, no users or other project resources have access to any files in the storage bucket. Access must be explicitly granted within `defineStorage` using the `access` callback. -The access callback returns an object where each key in the object is a file path and each value in the object is an array of access rules that apply to that path. +The access callback returns an object where each key in the object is a file path and each value in the object is an array of access rules that apply to that path. -The following example shows you how you can set up your file storage structure for a generic photo sharing app. Here, +The following example shows you how you can set up your file storage structure for a generic photo sharing app. Here, 1. Guests have access to see all profile pictures and only the users that uploaded the profile picture can replace or delete them. Users are identified by their Identity Pool ID in this case i.e. identityID. -2. There's also a general pool where all users can submit pictures. +2. There's also a general pool where all users can submit pictures. [Learn more about customizing access to file path](/[platform]/build-a-backend/storage/authorization/). @@ -148,7 +148,7 @@ For a full example, please follow the [project setup walkthrough](/[platform]/st {/* is the visionOS support callout relevant here? */} -visionOS support is currently in **preview** and can be used by targeting the [`visionos-preview`](https://github.com/aws-amplify/amplify-swift/tree/visionos-preview) branch. +visionOS support is currently in **preview** and can be used by targeting the [`visionos-preview`](https://github.com/aws-amplify/amplify-swift/tree/visionos-preview) branch. As new Xcode 15 beta versions are released, the branch will be updated with any necessary fixes on a best effort basis. For more information on how to use the `visionos-preview` branch, see [Platform Support](https://github.com/aws-amplify/amplify-swift/tree/visionos-preview#platform-support). @@ -191,11 +191,11 @@ struct MyAmplifyApp: App { } } - init() { + init() { do { try Amplify.add(plugin: AWSCognitoAuthPlugin()) try Amplify.add(plugin: AWSS3StoragePlugin()) - try Amplify.configure() + try Amplify.configure(with: .amplifyOutputs) print("Amplify configured with Auth and Storage plugins") } catch { print("Failed to initialize Amplify with \(error)") @@ -226,7 +226,7 @@ func application( do { try Amplify.add(plugin: AWSCognitoAuthPlugin()) try Amplify.add(plugin: AWSS3StoragePlugin()) - try Amplify.configure() + try Amplify.configure(with: .amplifyOutputs) print("Amplify configured with Auth and Storage plugins") } catch { print("Failed to initialize Amplify with \(error)") @@ -523,8 +523,8 @@ upload.addEventListener("click", () => { console.log("Complete File read successfully!", event.target.result); try { await uploadData({ - data: event.target.result, - path: `picture-submissions/${file.files[0].name}` + data: event.target.result, + path: `picture-submissions/${file.files[0].name}` }); } catch (e) { console.log("error", e); From fb3657330c3c102de2d277308ce6948b589510ac Mon Sep 17 00:00:00 2001 From: Mo Malaka Date: Thu, 2 May 2024 11:37:31 -0700 Subject: [PATCH 10/17] fix broken links (#7455) --- src/directory/directory.mjs | 3 +++ .../build-a-backend/auth/advanced-workflows/index.mdx | 6 +++--- .../[platform]/build-ui/formbuilder/lifecycle/index.mdx | 4 ++-- .../build-ui/formbuilder/special-inputs/index.mdx | 4 ++-- 4 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/directory/directory.mjs b/src/directory/directory.mjs index a3839af64e4..ab55076eb7e 100644 --- a/src/directory/directory.mjs +++ b/src/directory/directory.mjs @@ -161,6 +161,9 @@ export const directory = { }, { path: 'src/pages/[platform]/build-a-backend/auth/moving-to-production/index.mdx' + }, + { + path: 'src/pages/[platform]/build-a-backend/auth/advanced-workflows/index.mdx' } ] }, diff --git a/src/pages/[platform]/build-a-backend/auth/advanced-workflows/index.mdx b/src/pages/[platform]/build-a-backend/auth/advanced-workflows/index.mdx index 2e883cbce6f..e365cf82809 100644 --- a/src/pages/[platform]/build-a-backend/auth/advanced-workflows/index.mdx +++ b/src/pages/[platform]/build-a-backend/auth/advanced-workflows/index.mdx @@ -115,7 +115,7 @@ final session = await cognitoPlugin.federateToIdentityPool( ## Subscribing Events -You can take specific actions when users sign-in or sign-out by subscribing to authentication events in your app. Please see our [Hub Module Developer Guide](/[platform]/build-a-backend/utilities/hub/) for more information. +You can take specific actions when users sign-in or sign-out by subscribing to authentication events in your app. Please see our [Hub Module Developer Guide](/[platform]/build-a-backend/auth/connect-your-frontend/listen-to-auth-events/) for more information. ## Identity Pool Federation @@ -283,7 +283,7 @@ val options = FederateToIdentityPoolOptions.builder() ## Subscribing Events -You can take specific actions when users sign-in or sign-out by subscribing authentication events in your app. Please see our [Hub Module Developer Guide](/[platform]/build-a-backend/utilities/hub/) for more information. +You can take specific actions when users sign-in or sign-out by subscribing authentication events in your app. Please see our [Hub Module Developer Guide](/[platform]/build-a-backend/auth/connect-your-frontend/listen-to-auth-events/) for more information. ## Identity Pool Federation @@ -379,7 +379,7 @@ func federateToIdentityPoolsUsingCustomIdentityId() async throws { ## Subscribing to Events -You can take specific actions when users sign-in or sign-out by subscribing to authentication events in your app. Please see our [Hub Module Developer Guide](/[platform]/build-a-backend/utilities/hub/) for more information. +You can take specific actions when users sign-in or sign-out by subscribing to authentication events in your app. Please see our [Hub Module Developer Guide](/[platform]/build-a-backend/auth/connect-your-frontend/listen-to-auth-events/) for more information. ## Identity Pool Federation diff --git a/src/pages/[platform]/build-ui/formbuilder/lifecycle/index.mdx b/src/pages/[platform]/build-ui/formbuilder/lifecycle/index.mdx index bc977dffb03..3eb1a8be997 100644 --- a/src/pages/[platform]/build-ui/formbuilder/lifecycle/index.mdx +++ b/src/pages/[platform]/build-ui/formbuilder/lifecycle/index.mdx @@ -58,7 +58,7 @@ Hook into the form's lifecycle events to customize user input before submission, ## Get form data as your user inputs data - onChange -In some cases, you want to get the form data in real-time as the user is filling the form. The `onChange` event provides you the form data in the `fields` parameter. We recommend you to use `onChange` if you opted to [hide all form action buttons](/gen1/[platform]/build-ui/formbuilder/call-to-action/#toggle-visibility-for-submit-cancel-clear-and-reset-buttons) (Submit, Cancel, Clear, Reset). +In some cases, you want to get the form data in real-time as the user is filling the form. The `onChange` event provides you the form data in the `fields` parameter. ```jsx import { useState } from 'react' @@ -75,7 +75,7 @@ function App() { ## Extend validation rules in code - onValidate -With the `onValidate` event, you can extend the validation rules in code. Learn more about [How to add validation rules](/gen1/[platform]/build-ui/formbuilder/validations/). +With the `onValidate` event, you can extend the validation rules in code. Learn more about [How to add validation rules](/[platform]/build-ui/formbuilder/validations/). ## Handle form data submissions - onSubmit diff --git a/src/pages/[platform]/build-ui/formbuilder/special-inputs/index.mdx b/src/pages/[platform]/build-ui/formbuilder/special-inputs/index.mdx index 04691236c22..10648a52901 100644 --- a/src/pages/[platform]/build-ui/formbuilder/special-inputs/index.mdx +++ b/src/pages/[platform]/build-ui/formbuilder/special-inputs/index.mdx @@ -28,12 +28,12 @@ export function getStaticProps(context) { ## Storage Manager -[**Storage Manager**](https://ui.docs.amplify.aws/react/connected-components/storage/storagemanager) fields allow your forms to accept file uploads, which are stored in an Amazon S3 bucket connected to your Amplify app. After uploading, that file's S3 key is stored in your data model, allowing for systematic retrieval using the [Amplify JS library](/gen1/[platform]/build-a-backend/storage/download/). +[**Storage Manager**](https://ui.docs.amplify.aws/react/connected-components/storage/storagemanager) fields allow your forms to accept file uploads, which are stored in an Amazon S3 bucket connected to your Amplify app. After uploading, that file's S3 key is stored in your data model, allowing for systematic retrieval using the [Amplify JS library](/[platform]/build-a-backend/storage/download-files/). ### Prerequisites -In order to use the Storage Manager field, your Amplify app must have an Amplify app with [Authentication](react/build-a-backend/auth/set-up-auth/) and [Storage](react/build-a-backend/storage/define-storage/) enabled. +In order to use the Storage Manager field, your Amplify app must have an Amplify app with [Authentication](/[platform]/build-a-backend/auth/set-up-auth/) and [Storage](/[platform]/build-a-backend/storage/set-up-storage/) enabled. ### How it works From d070fc2ff8992ac3ef597bc5f5e67958b4f3c79e Mon Sep 17 00:00:00 2001 From: Tim Nguyen <54393192+timngyn@users.noreply.github.com> Date: Thu, 2 May 2024 11:40:18 -0700 Subject: [PATCH 11/17] Merge main into next-release/main (#7454) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Minor edits to Vite + React quickstart (#6926) * Updates to Vite + React quickstart * Update src/fragments/gen2/quickstart/build-a-backend.mdx Co-authored-by: Kevin Old * Update build-a-backend.mdx * Update build-a-backend.mdx * Update build-a-backend.mdx --------- Co-authored-by: Kevin Old * fix: Fix incorrect auth import path in migration guide. (#6934) * fix: Update incorrect `updateMFAPreference` parameter in JS v6 migration guide. (#6935) * Amplify Android Release 2.14.11 (#6933) * chore: refactor .layout-header into separate component (#6826) * platform typed as optional * refactor init * remove commented code * remove angry useEffect * fix typing * added layoutcontext so mobile menu closes on navigation * move import --------- Co-authored-by: katiegoines * fix: Nesting of auth cli templates (#6932) * fix: change config variable name (#6923) * Guide to support Amplify v2 with AWS Android SDK (#6927) * Update puppeteer (#6949) * Update index.mdx (#6950) * Update CODEOWNERS with correct PM alignment (#6951) * fix(flutter, js): scope "connect existing cdk" guide to respective platform (#6947) Co-authored-by: Tim Nguyen <54393192+timngyn@users.noreply.github.com> * Revert "fix(flutter, js): scope "connect existing cdk" guide to respective pl…" (#6955) This reverts commit 5998b22f18cada98ba7c6d1f35c3f6b378637476. * chore: remove duplicated logic between Layout and LayoutHeader (#6954) * chore: more layout refactoring * remove unused prop, alphabetize props * improve oauth docs (#6961) * fixed gen 2 getting started guide (#6968) * Update redirects for deleted hidden pages (#6944) * Update manual installation to point to @beta tag (#6972) * include usage for multi-page apps (#6964) * include usage for multi-page apps * improve multi-page app docs * use Hub syntax * update imports in examples * chore: Clean up broken Amplify JS API reference links (#6976) * chore: Clean up broken Amplify JS API reference links. * Cleaned up language. * Update build image instructions for Gen 2 (#6978) * update build image settings for Gen 2 * remove callout and add fragment to vite guide * chore: add unit test for YoutubeEmbed component (#6983) * chore: add unit test for YoutubeEmbed component * add code coverage stats --------- Co-authored-by: katiegoines * chore: add unit tests for Accordion component (#6981) * chore: add unit tests for Accordion component * issue with window properties * fixed tracking test * working on animation issue * accordion tests * fix testing errors * added test for closing accordion * add code coverage stats --------- Co-authored-by: katiegoines * Update index.mdx (#6986) * Add env variables for algolia (#6957) * Add algolia env vars to next.config * Remove extra code string * fix(data): update REST API docs to document correct error response type (#6989) * fix(data): update React Native minimum iOS deployment target guidance; add build step to docs (#6970) * fix(data): update React Native minimum iOS deployment target; add build step to docs * address PR feedback * remove deployment target guidance * add React Native version deployment target callout * fix unrecognized syntax * replace callout with accordion * move 'upgrading' callout * Clarify behavior of forgetDevice() API regarding device tracking (#6985) * Clarify behavior of forgetDevice() API regarding device tracking This commit updates the documentation to clarify that using the forgetDevice() API results in the device being neither remembered nor tracked. Previously, the documentation suggested that forgotten devices might still be tracked, leading to confusion about the API's behavior. The revised wording aligns with the detailed description under the "Forgotten" section, ensuring consistency and eliminating ambiguity about how forgotten devices are handled. * Clarify behavior of forgetDevice() API regarding device tracking * Support for enum value listing (#6885) * Support for enum value listing * Update src/pages/gen2/build-a-backend/data/data-modeling/add-fields/index.mdx * CDK updates v2 (#6990) * Add padding to bottom of nav menu (#6991) * Adding secondary index to Gen 2 (#6996) * Adding secondary index docs * fixed some formatting for custom query fields * extend config to show addOuput (#6963) * extend config * modify wording * modify example * improve wording * Update index.mdx (#6995) * Update index.mdx * add guest access support to docs * chore: add unit tests for NextPrevious component (#7003) Co-authored-by: katiegoines * chore: add unit tests for LinkCards and LinkCard components (#7006) Co-authored-by: katiegoines * chore: add unit tests for GetStartedPopover component (#7005) Co-authored-by: katiegoines * fix: [Storage] Configure Access (#6948) Co-authored-by: Tim Nguyen <54393192+timngyn@users.noreply.github.com> * fix(Swift): update data use policy info's tracking to false (#6938) * fix(Swift): update data use policy info's tracking to false * Update data-information.mdx * chore: add callouts and troubleshooting guide for configuration (#6967) * fix: resolve in-content broken links (#7011) * re-platforming * remove reference to mocking and testing for android & swift * remove reference to mocking and testing for android & swift * filtered out reference to optimistic ui for react native --------- Co-authored-by: katiegoines * update gen2 storage and function docs (#7009) * update gen2 storage and function docs * add resource access links and example * revisions, update code snippet titles * Update CODEOWNERS (#7014) * updated steps for extending components in code (#6827) Co-authored-by: Aditya Shahani * Custom business logic support as of March @beta (#7019) * Enhanced custom business logic DX * addressed tim's comments * Added custom subscription configuration worfklow * removed in-development areas * added titles * added links for deep dive material * Update src/pages/gen2/build-a-backend/data/custom-business-logic/index.mdx Co-authored-by: josef * Update src/pages/gen2/build-a-backend/data/custom-business-logic/index.mdx Co-authored-by: josef * Update src/pages/gen2/build-a-backend/data/custom-business-logic/index.mdx Co-authored-by: Kethan sai * Update src/pages/gen2/build-a-backend/data/custom-business-logic/index.mdx Co-authored-by: Kethan sai * Update src/pages/gen2/build-a-backend/data/custom-business-logic/index.mdx Co-authored-by: josef * Update src/pages/gen2/build-a-backend/data/custom-business-logic/index.mdx * added client method for clarity. * Update src/pages/gen2/build-a-backend/data/custom-business-logic/index.mdx Co-authored-by: Kethan sai * Apply suggestions from code review Co-authored-by: josef --------- Co-authored-by: josef Co-authored-by: Kethan sai * add storage trigger docs (#7020) * storage trigger docs * Apply suggestions from code review Co-authored-by: josef * add storage access actions --------- Co-authored-by: josef * update link checker to wait for each call to complete before making t… (#6993) * update link checker to wait for each call to complete before making the next and remove # from urls being checked * update logging to show how many links found on each page * Update tasks/link-checker.js --------- Co-authored-by: Jacob Logan Co-authored-by: katiegoines Co-authored-by: Scott Rees <6165315+reesscot@users.noreply.github.com> * custom examples (#6979) * custom examples * fix: broken link, missing / at start (#7026) Co-authored-by: katiegoines * validate and fix code snippets in Data section (#6975) * Update sandbox --dir-to-watch description (#7031) * Update index.mdx (#7035) * Fix link (#7028) * add docs to auth resource access pattern (#7032) * fix: type platform as optional in Breadcrumbs component & add unit tests (#6912) * platform typed as optional * chore: add unit tests for Breadcrumbs * testing to include platform optional * fix: type platform as optional * add tests for override values --------- Co-authored-by: katiegoines * fix: proper variable naming conventions for storage (#7033) fix: proper variable naming conventions for storage * remove explicit file extension from gen2 imports (#6946) Co-authored-by: Tim Nguyen <54393192+timngyn@users.noreply.github.com> * fix: Update diff code blocks to TypeScript with code highlights (#6905) * add docs on granting defineFunction access to defineData (#7029) * standardize Gen 2 wording (#7036) * Update index.mdx (#6906) * Modify_Amplify_resources (#7018) * fix code snippets on read data page * code snippet updates * updated the code snippets * updated code snippets. * custom business page rollback * Update maplibre links (#7040) * chore: add unit tests for PlatformNavigator (#6980) * chore: add unit tests for PlatformNavigator * add code coverage * simplify * simplify --------- Co-authored-by: katiegoines * Update links to expo docs (#7044) * Update links to expo docs * Update src/pages/[platform]/prev/build-a-backend/auth/add-social-provider/index.mdx Co-authored-by: josef * Update src/pages/[platform]/prev/build-a-backend/auth/add-social-provider/index.mdx Co-authored-by: josef --------- Co-authored-by: josef * chore: add unit tests for InternalLinkButton (#7000) Co-authored-by: katiegoines * chore: add addtl unit test for Block component (#6982) * chore: add addtl unit test for Block component * add code coverage stats * remove superfluous Block component --------- Co-authored-by: katiegoines * chore: add unit tests for TOC (#6984) * chore: add unit tests for TOC * add code coverage * hardcode expected hash --------- Co-authored-by: katiegoines * chore: add unit tests for ExternalLink (#6915) * chore: add unit tests for ExternalLink * fixing tracking test --------- Co-authored-by: katiegoines * chore: add unit tests for ExternalLinkButton (#6914) * chore: add unit tests for ExternalLinkButton * Update ExternalLinkButton.test.tsx triggering checks --------- Co-authored-by: katiegoines * chore: add unit tests for Footer component (#6999) Co-authored-by: katiegoines * chore: add unit tests for MigrationAlert component (#7004) * chore: add unit tests for MigrationAlert component * chore: add unit tests for MigrationAlert component --------- Co-authored-by: katiegoines * chore: add unit test for Overview component (#7002) Co-authored-by: katiegoines * chore: upgrade docsearch/react to 3.6 (#7046) * added utility type content (#7047) * chore: add unit tests for PageLastUpdated (#7001) Co-authored-by: katiegoines * chore: add unit tests for Commands and Columns (#6916) * chore: add unit test for CLICommands * chore: add unit test for Columns * Update Command.test.tsx triggering checks --------- Co-authored-by: katiegoines * Update resolution for follow-redirects (#7055) * Update relative urls (#7048) * Update relative urls * Update url * Updating link checker (#7052) * Updating link checker to account for duplicate urls from different pages and link text * Update slack formatting * Remove console.log * Add comments to function * Remove extra console.logs() * chore: update redirects list (#6969) * update redirects * updated redirects --------- Co-authored-by: katiegoines * remove allowlist role names for appsync console access page (#7081) * Add JavaScript resolver code sample to Gen 1 (#7087) * fix(JS): Update v5 JS libraries installation guides. (#7090) * fix(v5): update aws-amplify v5 dependency * chore: remove extra '0' number from versions * chore: remove vue2 block * chore: update version reference * Cbonif/field-level-auth-support-for-sql (#7091) * chore(gen2-data): update .secondaryIndexes example to match the latest interface (#7095) * update setup auth client example with correct props (#7106) * update auth with correct props * Change generated function env package name (#7096) * Update typo in url for localhost (#7110) * update next config to use a static build Id (#7102) Co-authored-by: Jacob Logan * chore: Add callout on Analytics buffer persistence in Amplify JS (#7115) * chore: Add callout on Analytics buffer persistence in Amplify JS. * PR feedback. * Custom subscription docs to Gen 2 (#7120) * Add playsInline to videos (#7125) * autoSignIn position correction in v6 migration docs (#7059) * fix(next-release/main): update home page h1 and code block font size (#7117) (#7126) * update font sizes * add text-size-adjust * add webkit prefix, add comment * update text-size-adjust fix --------- Co-authored-by: Tim Nguyen <54393192+timngyn@users.noreply.github.com> * remove parenthesis from "Amplify (Gen 2)" (#7113) * change "NPM" to "npm" (#7112) * remove explicit ".js" extension from gen2 resource imports (#7134) * remove leading slash from storage access paths (#7116) * remove unnecessary "Angular" mention in auth getting started (#7139) Removed 'Angular' from the app description. It is not necessarily an angular app. * Gen 2 Quickstart: Fix amplify console link (#7141) * fix amplify console link * fix text from AWS Console to Amplify Console * updated alt text for Amplify console * Update src/fragments/gen2/quickstart/deploy-and-host.mdx Co-authored-by: Scott Rees <6165315+reesscot@users.noreply.github.com> * Update src/pages/gen2/deploy-and-host/fullstack-branching/branch-deployments/index.mdx Co-authored-by: Scott Rees <6165315+reesscot@users.noreply.github.com> --------- Co-authored-by: Scott Rees <6165315+reesscot@users.noreply.github.com> * Add Favicon and apple-touch icons to root (#7137) * add 96x96 favicons * add favicon and apple-touch to root * updated icons --------- Co-authored-by: Jacob Logan * docs(migration): fixes mislabeling notification enable snippet (#7135) the v5 snippet was labeled as v6 and the v6 was labeled as v5 Co-authored-by: derrik.fleming * edits to custom business logic (#7129) * remove console.log (#7147) * fix: copied code no longer includes markdown comments (#7146) * fix: copied code no longer includes markdown comments * minor cleanup * splite prepareCopyText to it's own export for easier testing * fix MDXCode mock * chore(react-native): Add callouts for dropped Expo Go support (#7160) * Update index.mdx (#7165) * Update github link to maplibre repo (#7162) * Cbonif/add-sql-support-for-secrets-manager (#7104) * add image example for secrets manager key/value * add documentation for creating secrets in secrets manager and configuring db details on the construct * adjust order of paragraphs, moving relevant text closer to image and make alt text more descriptive * Fixed typo in amplifyconfiguration.json for predictions (#7185) * fix swift docs to use the `.update` call (#7191) * Update index.mdx (#7164) * Added documentation on updated IAM behavior (#7056) * Added documentation on updated IAM behavior * Update src/pages/[platform]/tools/cli/migration/iam-auth-updates-for-cdk-construct/index.mdx Co-authored-by: Kamil Sobol * Update src/pages/[platform]/build-a-backend/graphqlapi/customize-authorization-rules/index.mdx Co-authored-by: Kamil Sobol * Update src/pages/[platform]/build-a-backend/graphqlapi/customize-authorization-rules/index.mdx * Update src/pages/[platform]/tools/cli/migration/iam-auth-updates-for-cdk-construct/index.mdx * Update src/pages/[platform]/tools/cli/migration/iam-auth-updates-for-cdk-construct/index.mdx Co-authored-by: Tim Schmelter * addressed comments * Updated to reflect changes to Gen 2 content * Update src/pages/[platform]/build-a-backend/graphqlapi/customize-authorization-rules/index.mdx --------- Co-authored-by: Kamil Sobol Co-authored-by: Tim Schmelter * Added Metadata section in Storage (#7152) * Cbonif/edits-to-secondary-indexes-page (#7179) * edits to custom business logic * update secondary index code examples * Add client examples of accessing models with specific auth modes (#7080) * add client side code for public access * add client side code for signed in user access * add client side code for multi user access * add client side code for per user/owner access * add client side code for custom id & group claims * add client side code for custom access * add client side code for user pool group access * add client side code for oidc access * Update src/pages/gen2/build-a-backend/data/customize-authz/signed-in-user-data-access/index.mdx Co-authored-by: Rene Brandel <4989523+renebrandel@users.noreply.github.com> * add info callout and configuration code to public/private iam examples * move callout up * remove "**note**" from callouts --------- Co-authored-by: Rene Brandel <4989523+renebrandel@users.noreply.github.com> * Updated Gen 2 relationship behavior (#7222) * Added new relationship behavior doc * fixed typos * fix(predictions): fix wrong reference of swfit/android predictions use aws sdk page (#7220) * fix(predictions): fix wrong reference of swfit/android predictions use aws sdk page * fix(predictions): update Use AWS SDK description * Update amplify/data/increment-like.js syntax (#7229) The correct DynamoDB syntax requires semicolon in both expression and expressionValues * Graphql generate client code (#7176) * updated generate-client-code section * updated graphql-client-code section * updated the description * removed workflow * Update src/pages/gen2/reference/cli-commands/index.mdx Co-authored-by: Rene Brandel <4989523+renebrandel@users.noreply.github.com> * Update src/pages/gen2/reference/cli-commands/index.mdx Co-authored-by: Rene Brandel <4989523+renebrandel@users.noreply.github.com> * added Supported GraphQL client code combinations * fixed the spell * fixed the format * fixed the syntax * Update src/pages/gen2/reference/cli-commands/index.mdx Co-authored-by: josef * Update src/pages/gen2/reference/cli-commands/index.mdx Co-authored-by: josef * Update src/pages/gen2/reference/cli-commands/index.mdx Co-authored-by: josef * Update src/pages/gen2/reference/cli-commands/index.mdx Co-authored-by: josef * updated the stack name --------- Co-authored-by: Rene Brandel <4989523+renebrandel@users.noreply.github.com> Co-authored-by: josef * use latest tag for Gen2 apps (#7256) * Updated Data Gen 2 authorization rules to use the new syntax (#7252) * Updated authorization rules to use the new syntax * Update src/pages/gen2/build-a-backend/data/customize-authz/signed-in-user-data-access/index.mdx Co-authored-by: Hui Zhao <10602282+HuiSF@users.noreply.github.com> --------- Co-authored-by: Hui Zhao <10602282+HuiSF@users.noreply.github.com> * Update index.mdx (#7253) Modified link for "Serverless APIs" points to the correct URL. * Add tests to inline filter component for nested inline filters (#7274) * [Gen 2][Bugfix] Update the flutter mobile support doc. (#7245) * Update the flutter mobile support doc. * Add file name. * Add Safe Area. * chore(main): replace Twitter logo with X logo (#7295) * chore(main): replace Twitter logo with X logo * update tests,snapshots, use x.com link instead of twitter.com * Fix gen-1 storage code (#7284) * fix(main): allow code elements to work in h2/h3 headings with anchor links (#7292) * fix: allow code elements to work in h2/h3 headings with anchor links * update test * add comments to describe logic * fix(main): allow tablist in Blockswitcher to be scrollable (#7294) * allow tablist to be scrollable * add scroll padding * Remove scroll padding because firefox hates it * chore(main): update X icon name (#7324) * [Gen2][Backend] Update casing of MFA mode. (#7218) * fix(main): update overflow background color in dark mode (#7316) * fix(main): update background color in darkmode * fix darkmode when system default is used * StoragePath Documentation for Gen1 (#7279) * storage: update swift storage with storage path * chore: update swift storage docs with storage path * chore: update storage getting started content * chore: add callout warning to file access level * chore: update gen2 callout * chore: convert fragments to inline filter * update storage path example * Android Gen2 Storage * remove upload from getting started * Add Using Storagepath * add content to storage path page * Expand storagepath * improve doc * update callout message * modify file access level callout * add accidental remove * gramatical issues * Update src/pages/[platform]/build-a-backend/storage/download/index.mdx Co-authored-by: Jordan Nelson * Update src/pages/[platform]/build-a-backend/storage/upload/index.mdx Co-authored-by: Jordan Nelson * Update src/pages/[platform]/build-a-backend/storage/storagepath/index.mdx Co-authored-by: Jordan Nelson * Update src/pages/[platform]/build-a-backend/storage/list/index.mdx Co-authored-by: Jordan Nelson * Update src/pages/[platform]/build-a-backend/storage/remove/index.mdx Co-authored-by: Jordan Nelson * Bump Android version --------- Co-authored-by: Tuan Pham Co-authored-by: Jordan Nelson * Update npx amplify generate config -> outputs - Gen2 doc (#7344) npx amplify generate config is throwing >>Unknown command: config Generates post deployment artifacts Commands: amplify generate outputs Generates amplify outputs amplify generate forms Generates UI forms amplify generate graphql-client-code Generates graphql API code amplify generate schema-from-database Generates typescript data schema from a SQL database * chore: add kotlin update to docs and formatting changes for flutter (#7023) * chore: add kotlin update to docs and formatting changes for new flutter build.gradle creation * chore: remove steps for apps created with flutter 3.16 and earlier * JS Gen2 Storage Docs (#7323) * [Gen2 Storage JS] DownloadData doc updates (#7049) * [JS] Update migration docs to use path (#7143) * [JS] Storage API - path update (#7145) * [Gen2 Storage JS] Update version and path strings (#7307) * fix missed $ in string --------- Co-authored-by: Jim Blanchard * update sandbox secret management (#7108) * update sandbox secret management * Update src/pages/gen2/deploy-and-host/sandbox-environments/features/index.mdx * Update src/pages/gen2/deploy-and-host/sandbox-environments/features/index.mdx * Update src/pages/gen2/deploy-and-host/sandbox-environments/features/index.mdx * Update src/pages/gen2/deploy-and-host/sandbox-environments/features/index.mdx * Update src/pages/gen2/deploy-and-host/sandbox-environments/features/index.mdx --------- Co-authored-by: josef * add angular specific code snippet (#7353) * add angular specific code snippet * update dist directory path * chore(gen2): replace authMode 'iam' with 'identityPool' (#7370) * fix: Typos in JS Auth migration & getting started guides (#7371) * amplifyconfiguration.json -> amplify_outputs.json (#7346) * amplifyconfiguration.json -> amplify_outputs.json * configuration file -> outputs file * update all references to "import *config" to "import outputs" * Update src/pages/gen2/build-a-backend/server-side-rendering/index.mdx Co-authored-by: Amplifiyer <51211245+Amplifiyer@users.noreply.github.com> --------- Co-authored-by: Amplifiyer <51211245+Amplifiyer@users.noreply.github.com> * re add action to check for console errors (#6471) * re add action to check for console errors * add get sitemap links script * update console error scripts * remove http-server action and using python server instead * revert change to pr broken links action * use LOCALHOST constant * check console errors * upgrade node * upgrade github-script * update * change filetype to .mjs * fix reference * . * working * . * back to js * . * catch error * merge conflicts * . * upgrade checkout script * upgrade checkout script * run on prod build, exclude addtl marketing script * exclude more scripts * . * . * remove image * add photo back in * change name of problem image * change filename --------- Co-authored-by: Jacob Logan Co-authored-by: katiegoines * Add resolution for ejs (#7413) * Chore: JS List API doc (#7408) * minor doc fix * Apply suggestions from code review Co-authored-by: Scott Rees <6165315+reesscot@users.noreply.github.com> --------- Co-authored-by: Scott Rees <6165315+reesscot@users.noreply.github.com> * Fix merge conflict * Fix merge conflict * Remove file that should only exist in gen1 * Remove file that should only exist in gen1 * Undo changes that shouldn't be there --------- Co-authored-by: Jim Eagan <84857865+hibler13@users.noreply.github.com> Co-authored-by: Kevin Old Co-authored-by: Jim Blanchard Co-authored-by: Ankit Shah <22114629+ankpshah@users.noreply.github.com> Co-authored-by: Katie Goines <30757403+katiegoines@users.noreply.github.com> Co-authored-by: katiegoines Co-authored-by: Dan Kiuna Co-authored-by: Kihara, Takuya Co-authored-by: Tyler Roach Co-authored-by: Rene Brandel <4989523+renebrandel@users.noreply.github.com> Co-authored-by: Elijah Quartey Co-authored-by: Heather Buchel Co-authored-by: John Corser Co-authored-by: Heather Pundt <119376175+heatheramz@users.noreply.github.com> Co-authored-by: Nikhil Swaminathan <2429410+swaminator@users.noreply.github.com> Co-authored-by: Jay Raval Co-authored-by: David McAfee Co-authored-by: Kethan sai Co-authored-by: Michael Law <1365977+lawmicha@users.noreply.github.com> Co-authored-by: erinleigh90 <106691284+erinleigh90@users.noreply.github.com> Co-authored-by: Edward Foyle Co-authored-by: Adi <34354177+the1adi@users.noreply.github.com> Co-authored-by: Aditya Shahani Co-authored-by: josef Co-authored-by: jacoblogan Co-authored-by: Jacob Logan Co-authored-by: Scott Rees <6165315+reesscot@users.noreply.github.com> Co-authored-by: Chris Bonifacio Co-authored-by: Roshane Pascual Co-authored-by: Charles Shin Co-authored-by: Ujjwol Shrestha Co-authored-by: Gen Tamura Co-authored-by: dwittle <72715628+dwittle@users.noreply.github.com> Co-authored-by: Anil Maktala Co-authored-by: israx <70438514+israx@users.noreply.github.com> Co-authored-by: Hui Zhao <10602282+HuiSF@users.noreply.github.com> Co-authored-by: Nairi Areg <51801223+NairiAreg@users.noreply.github.com> Co-authored-by: spivakov83 Co-authored-by: Harshita Daddala Co-authored-by: derrik Co-authored-by: derrik.fleming Co-authored-by: Chris F <5827964+cshfang@users.noreply.github.com> Co-authored-by: Kamil Sobol Co-authored-by: Tim Schmelter Co-authored-by: yuhengshs <94558971+yuhengshs@users.noreply.github.com> Co-authored-by: Di Wu Co-authored-by: Guy Pavlov Co-authored-by: abhisuma02 Co-authored-by: Muhammed Salih Guler Co-authored-by: Danny Banks Co-authored-by: Amplifiyer <51211245+Amplifiyer@users.noreply.github.com> Co-authored-by: Tuan Pham Co-authored-by: Jordan Nelson Co-authored-by: Susmitha Co-authored-by: Kha Truong <64438356+khatruong2009@users.noreply.github.com> Co-authored-by: ashika112 <155593080+ashika112@users.noreply.github.com> Co-authored-by: Ivan Artemiev <29709626+iartemiev@users.noreply.github.com> --- .github/CODEOWNERS | 1 + .../workflows/check_for_console_errors.yml | 38 ++++++ cspell.json | 2 +- package.json | 3 +- ...licauthreadonly.png => 7_authreadonly.png} | Bin .../__tests__/BlockSwitcher.test.tsx | 8 +- .../auth/set-up-auth/index.mdx | 2 +- .../data/set-up-data/index.mdx | 8 +- .../server-side-rendering/index.mdx | 14 +-- .../index.mdx | 8 +- .../cross-account-deployments/index.mdx | 4 +- .../custom-pipelines/index.mdx | 4 +- .../mono-and-multi-repos/index.mdx | 10 +- .../share-resources/index.mdx | 2 +- .../reference/cli-commands/index.mdx | 2 +- .../storage/configure-access/index.mdx | 2 +- .../build-a-backend/storage/list/index.mdx | 4 + .../build-a-backend/storage/path/index.mdx | 3 +- .../tools/console/authz/permissions/index.mdx | 2 +- tasks/console-errors.js | 109 ++++++++++++++++++ tasks/get-sitemap-links.js | 42 +++++++ yarn.lock | 13 +-- 22 files changed, 236 insertions(+), 45 deletions(-) create mode 100644 .github/workflows/check_for_console_errors.yml rename public/images/console/{7_publicauthreadonly.png => 7_authreadonly.png} (100%) create mode 100644 tasks/console-errors.js create mode 100644 tasks/get-sitemap-links.js diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 4bc3e60d1b8..e1ea17fb3d4 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -104,6 +104,7 @@ /src/themes @aws-amplify/documentation-team /src/utils @aws-amplify/documentation-team /tasks @aws-amplify/documentation-team +.github @aws-amplify/documentation-team #Protected Content /src/protected @reesscot @srquinn21 @Milan-Shah @swaminator diff --git a/.github/workflows/check_for_console_errors.yml b/.github/workflows/check_for_console_errors.yml new file mode 100644 index 00000000000..e3852ba97a0 --- /dev/null +++ b/.github/workflows/check_for_console_errors.yml @@ -0,0 +1,38 @@ +name: CheckConsoleErrors +on: + pull_request: + branches: [main] + types: [opened, synchronize] +permissions: + contents: read +jobs: + CheckConsoleErrors: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.2 https://github.com/actions/checkout/commit/b4ffde65f46336ab88eb53be808477a3936bae11 + - name: Setup Node.js 20.x + uses: actions/setup-node@e33196f7422957bea03ed53f6fbb155025ffc7b8 # v3.7.0 https://github.com/actions/setup-node/commit/e33196f7422957bea03ed53f6fbb155025ffc7b8 + with: + node-version: 20.x + - name: Install Dependencies + run: yarn + - name: Run Build + run: yarn build:release + env: + NODE_OPTIONS: --max_old_space_size=4096 + - name: Run Server + run: | + python -m http.server 3000 -d ${{ vars.BUILD_DIR }} & + sleep 5 + - name: Run Console Errors + id: consoleErrors + uses: actions/github-script@d7906e4ad0b1822421a7e6a35d5ca353c962f410 # v6.4.1 https://github.com/actions/github-script/commit/d7906e4ad0b1822421a7e6a35d5ca353c962f410 + with: + result-encoding: string + script: | + const { consoleErrors } = require('./tasks/console-errors.js'); + return await consoleErrors(); + - name: Fail if console errors have been found + if: ${{ steps.consoleErrors.outputs.result }} + run: exit 1 diff --git a/cspell.json b/cspell.json index b97dae7ded7..69817bdd7eb 100644 --- a/cspell.json +++ b/cspell.json @@ -1520,7 +1520,7 @@ "privatesaccess", "menudetaileditors", "editorgroupaccess", - "publicauthreadonly", + "authreadonly", "envs", "Onetoone", "onetomany", diff --git a/package.json b/package.json index 73ee7d22885..7cb97565ea8 100644 --- a/package.json +++ b/package.json @@ -91,7 +91,8 @@ "@adobe/css-tools": "4.3.2", "follow-redirects": "^1.15.6", "ip": "2.0.1", - "sharp": "0.32.6" + "sharp": "0.32.6", + "ejs": "3.1.10" }, "scripts": { "clean": "rm -rf node_modules yarn.lock", diff --git a/public/images/console/7_publicauthreadonly.png b/public/images/console/7_authreadonly.png similarity index 100% rename from public/images/console/7_publicauthreadonly.png rename to public/images/console/7_authreadonly.png diff --git a/src/components/BlockSwitcher/__tests__/BlockSwitcher.test.tsx b/src/components/BlockSwitcher/__tests__/BlockSwitcher.test.tsx index 7c9989f7d91..eae43ec719c 100644 --- a/src/components/BlockSwitcher/__tests__/BlockSwitcher.test.tsx +++ b/src/components/BlockSwitcher/__tests__/BlockSwitcher.test.tsx @@ -21,12 +21,12 @@ describe('BlockSwitcher', () => { const blockSwitcher = await screen.findByText(blockAContent); expect(blockSwitcher).toBeInTheDocument(); }); - + it('should have more than one Block', async () => { render(component); expect(component.props.children.length).toBeGreaterThan(1); }); - + it('should show the first Block as default', async () => { render(component); const tabs = await screen.getAllByRole('tab'); @@ -39,7 +39,7 @@ describe('BlockSwitcher', () => { expect(panels[1]).not.toHaveClass('amplify-tabs__panel--active'); expect(panels[2]).not.toHaveClass('amplify-tabs__panel--active'); }); - + it('should load all Blocks to the DOM', async () => { render(component); const blockA = await screen.findByText(blockAContent); @@ -49,7 +49,7 @@ describe('BlockSwitcher', () => { expect(blockB).toBeInTheDocument(); expect(blockC).toBeInTheDocument(); }); - + it('should switch tabs upon click', async () => { render(component); const tabs = await screen.getAllByRole('tab'); diff --git a/src/pages/[platform]/build-a-backend/auth/set-up-auth/index.mdx b/src/pages/[platform]/build-a-backend/auth/set-up-auth/index.mdx index 232b6d4dddf..6274837684d 100644 --- a/src/pages/[platform]/build-a-backend/auth/set-up-auth/index.mdx +++ b/src/pages/[platform]/build-a-backend/auth/set-up-auth/index.mdx @@ -92,7 +92,7 @@ npx ampx sandbox -After a successful deployment, this command also generates a configuration file (`amplify_outputs.json`) to enable your frontend app to connect to your backend resources. The values you configure in your backend authentication resource are set in the generated configuration file to automatically configure the frontend [`Authenticator connected component`](https://ui.docs.amplify.aws/react/connected-components/authenticator). +After a successful deployment, this command also generates an outputs file (`amplify_outputs.json`) to enable your frontend app to connect to your backend resources. The values you configure in your backend authentication resource are set in the generated outputs file to automatically configure the frontend [`Authenticator connected component`](https://ui.docs.amplify.aws/react/connected-components/authenticator). ## Connect your application code to your auth resource diff --git a/src/pages/[platform]/build-a-backend/data/set-up-data/index.mdx b/src/pages/[platform]/build-a-backend/data/set-up-data/index.mdx index f0af72a15da..307d1958169 100644 --- a/src/pages/[platform]/build-a-backend/data/set-up-data/index.mdx +++ b/src/pages/[platform]/build-a-backend/data/set-up-data/index.mdx @@ -113,11 +113,11 @@ npx ampx sandbox --outputs-format dart --outputs-out-dir lib ## Connect your application code to the data backend -Once the cloud sandbox is up and running, it will also create an `amplifyconfiguration.json` file, which includes the relevant connection information to your data backend, like your API endpoint URL and API key. +Once the cloud sandbox is up and running, it will also create an `amplify_outputs.json` file, which includes the relevant connection information to your data backend, like your API endpoint URL and API key. To connect your frontend code to your backend, you need to: -1. configure the Amplify library with the Amplify client configuration file +1. configure the Amplify library with the Amplify client configuration file (`amplify_outputs.json`) 2. generate a new API client from the Amplify library 3. make an API request with end-to-end type-safety @@ -133,9 +133,9 @@ In your app's entry point, typically **main.tsx** for React apps created using V ```tsx title="src/main.tsx" import { Amplify } from 'aws-amplify'; -import config from '../amplifyconfiguration.json'; +import outputs from '../amplify_outputs.json'; -Amplify.configure(config); +Amplify.configure(outputs); ``` diff --git a/src/pages/[platform]/build-a-backend/server-side-rendering/index.mdx b/src/pages/[platform]/build-a-backend/server-side-rendering/index.mdx index 8d83a5d21dd..56f3e58bae5 100644 --- a/src/pages/[platform]/build-a-backend/server-side-rendering/index.mdx +++ b/src/pages/[platform]/build-a-backend/server-side-rendering/index.mdx @@ -46,16 +46,16 @@ npm add aws-amplify @aws-amplify/adapter-nextjs You will need to create a `runWithAmplifyServerContextRunner` function to use Amplify APIs on the server-side of your Next.js app. -You can create an `amplifyServerUtils.ts` file under a `utils` folder in your codebase. In this file, you will import the Amplify configuration object from the `amplifyconfiguration.json` file that is generated by the Amplify CLI, and use the `createServerRunner` function to create the `runWithAmplifyServerContextRunner` function. +You can create an `amplifyServerUtils.ts` file under a `utils` folder in your codebase. In this file, you will import the Amplify backend outputs from the `amplify_outputs.json` file that is generated by the Amplify CLI, and use the `createServerRunner` function to create the `runWithAmplifyServerContextRunner` function. For example, the `utils/amplifyServerUtils.ts` file may contain the following content: ```typescript import { createServerRunner } from '@aws-amplify/adapter-nextjs'; -import config from '@/amplifyconfiguration.json'; +import outputs from '@/amplify_outputs.json'; export const { runWithAmplifyServerContext } = createServerRunner({ - config + outputs }); ``` @@ -78,10 +78,10 @@ When you use the Amplify library on the client-side of your Next.js app, you wil ```typescript 'use client'; -import config from '@/amplifyconfiguration.json'; +import outputs from '@/amplify_outputs.json'; import { Amplify } from 'aws-amplify'; -Amplify.configure(config, { +Amplify.configure(outputs, { ssr: true // required when using Amplify with Next.js }); @@ -110,9 +110,9 @@ If you're using the Next.js App Router, you can create a client component to con 'use client'; import { Amplify } from 'aws-amplify'; -import config from '../amplifyconfiguration.json'; +import outputs from '../amplify_outputs.json'; -Amplify.configure(config, { ssr: true }); +Amplify.configure(outputs, { ssr: true }); export default function ConfigureAmplifyClientSide() { return null; diff --git a/src/pages/[platform]/build-a-backend/server-side-rendering/nextjs-app-router-server-components/index.mdx b/src/pages/[platform]/build-a-backend/server-side-rendering/nextjs-app-router-server-components/index.mdx index 86bb3e049c4..b225f35fdc2 100644 --- a/src/pages/[platform]/build-a-backend/server-side-rendering/nextjs-app-router-server-components/index.mdx +++ b/src/pages/[platform]/build-a-backend/server-side-rendering/nextjs-app-router-server-components/index.mdx @@ -61,9 +61,9 @@ Next, create a `components` folder in the root of your project and copy the cont import { Amplify } from "aws-amplify"; -import config from "@/amplifyconfiguration.json"; +import outputs from "@/amplify_outputs.json"; -Amplify.configure(config, { ssr: true }); +Amplify.configure(outputs, { ssr: true }); export default function ConfigureAmplifyClientSide() { return null; @@ -123,10 +123,10 @@ import { generateServerClientUsingCookies } from "@aws-amplify/adapter-nextjs/ap import { getCurrentUser } from "aws-amplify/auth/server"; import { type Schema } from "@/amplify/data/resource"; -import config from "@/amplifyconfiguration.json"; +import outputs from "@/amplify_outputs.json"; export const { runWithAmplifyServerContext } = createServerRunner({ - config, + outputs, }); export const cookiesClient = generateServerClientUsingCookies({ diff --git a/src/pages/[platform]/deploy-and-host/fullstack-branching/cross-account-deployments/index.mdx b/src/pages/[platform]/deploy-and-host/fullstack-branching/cross-account-deployments/index.mdx index 96a2d2cfede..68254b42a6a 100644 --- a/src/pages/[platform]/deploy-and-host/fullstack-branching/cross-account-deployments/index.mdx +++ b/src/pages/[platform]/deploy-and-host/fullstack-branching/cross-account-deployments/index.mdx @@ -53,7 +53,7 @@ Please refer to this Amazon CodeCatalyst [guide](https://docs.aws.amazon.com/cod ### Step 3: Update build specification -Add the `npx ampx generate outputs --branch $AWS_BRANCH --app-id $AWS_APP_ID` command to the build spec and comment out the `npx ampx pipeline-deploy --branch $AWS_BRANCH --app-id $AWS_APP_ID` command. `ampx pipeline-deploy` runs a script to deploy backend updates, while `amplify generate config` fetches the latest `amplifyconfiguration.json` for the specified environment. +Add the `npx amplify generate config --branch $AWS_BRANCH --app-id $AWS_APP_ID` command to the build spec and comment out the `npx amplify pipeline-deploy --branch $AWS_BRANCH --app-id $AWS_APP_ID` command. `amplify pipeline-deploy` runs a script to deploy backend updates, while `amplify generate config` fetches the latest `amplify_outputs.json` for the specified environment. ![Screenshot of Build image settings section in AWS Amplify Gen 2 console, with details about the app build specification](images/gen2/cross-account-deployments/pipeline10.png) @@ -183,4 +183,4 @@ Next, you can review the result of the workflow run from the **Runs** tab: ![Screenshot of CodeCatalyst console showing the Workflows section, focusing on the Runs tab](images/gen2/cross-account-deployments/pipeline11.png) -Done! You have successfully set up a custom cross-account pipeline to deploy your frontend and backend for apps built using Amplify Gen 2. To summarize, this custom pipeline will enable you to deploy your backend initially with your `staging` environment using `ampx pipeline-deploy` in the CodeCatalyst workflow and `amplify generate config` will generate the `amplifyconfiguration.json` file for the `main` branch. Amplify Hosting will not deploy backend resources as part of the build and instead will use the deployed backend resources from the `main` branch. Once the staging environment deploys successfully, a similar process will be followed to deploy your `production` environment in a different AWS account. +Done! You have successfully set up a custom cross-account pipeline to deploy your frontend and backend for apps built using Amplify Gen 2. To summarize, this custom pipeline will enable you to deploy your backend initially with your `staging` environment using `amplify pipeline-deploy` in the CodeCatalyst workflow and `amplify generate config` will generate the `amplify_outputs.json` file for the `main` branch. Amplify Hosting will not deploy backend resources as part of the build and instead will use the deployed backend resources from the `main` branch. Once the staging environment deploys successfully, a similar process will be followed to deploy your `production` environment in a different AWS account. diff --git a/src/pages/[platform]/deploy-and-host/fullstack-branching/custom-pipelines/index.mdx b/src/pages/[platform]/deploy-and-host/fullstack-branching/custom-pipelines/index.mdx index fee4774aa8f..e65f045d97e 100644 --- a/src/pages/[platform]/deploy-and-host/fullstack-branching/custom-pipelines/index.mdx +++ b/src/pages/[platform]/deploy-and-host/fullstack-branching/custom-pipelines/index.mdx @@ -43,7 +43,7 @@ You can set up your backend deployments using the following steps: -3. Update the Amplify build-spec to add `npx ampx generate outputs --branch $AWS_BRANCH --app-id $AWS_APP_ID` and comment out the `pipeline-deploy` script. `ampx pipeline-deploy` runs a script to deploy backend updates, while `amplify generate config` fetches the latest `amplifyconfiguration.json` for the specified environment. +3. Update the Amplify build-spec to add `npx amplify generate config --branch $AWS_BRANCH --app-id $AWS_APP_ID` and comment out the `pipeline-deploy` script. `amplify pipeline-deploy` runs a script to deploy backend updates, while `amplify generate config` fetches the latest `amplify_outputs.json` for the specified environment. ![custom-ci](/images/gen2/fullstack-branching/custom-ci.png) @@ -114,4 +114,4 @@ aws amplify create-webhook --app-id AMPLIFY-APPID --branch-name main --region R -H "Content-Type:application/json"; fi ``` -4. This should trigger a build in your Amplify app. Amplify CI will build and first generate the `amplifyconfiguration.json` for the branch and then build, deploy, and host the frontend. +4. This should trigger a build in your Amplify app. Amplify CI will build and first generate the `amplify_outputs.json` for the branch and then build, deploy, and host the frontend. diff --git a/src/pages/[platform]/deploy-and-host/fullstack-branching/mono-and-multi-repos/index.mdx b/src/pages/[platform]/deploy-and-host/fullstack-branching/mono-and-multi-repos/index.mdx index 7922a04d84d..dd0b8ed6729 100644 --- a/src/pages/[platform]/deploy-and-host/fullstack-branching/mono-and-multi-repos/index.mdx +++ b/src/pages/[platform]/deploy-and-host/fullstack-branching/mono-and-multi-repos/index.mdx @@ -65,11 +65,11 @@ npm add @aws-amplify/backend-cli aws-amplify @aws-amplify/ui-react npx ampx generate outputs --branch main --app-id BACKEND-APPID ``` -This will generate the `amplifyconfiguration.json` file that contains all the information about your backend at the root of your project. +This will generate the `amplify_outputs.json` file that contains all the information about your backend at the root of your project. Screenshot of project folder contents with amplifyconfiguration.json file highlighted @@ -79,13 +79,13 @@ This will generate the `amplifyconfiguration.json` file that contains all the in // pages/_app.tsx import { withAuthenticator } from '@aws-amplify/ui-react'; import { Amplify } from 'aws-amplify'; -import config from '@/amplifyconfiguration.json'; +import outputs from '@/amplify_outputs.json'; import '@aws-amplify/ui-react/styles.css'; import '@/styles/globals.css'; import type { AppProps } from 'next/app'; -// configure the Amplify client library with the configuration generated by `ampx sandbox` -Amplify.configure(config); +// configure the Amplify client library with the configuration generated by `amplify sandbox` +Amplify.configure(outputs); function App({ Component, pageProps }: AppProps) { return ; diff --git a/src/pages/[platform]/deploy-and-host/fullstack-branching/share-resources/index.mdx b/src/pages/[platform]/deploy-and-host/fullstack-branching/share-resources/index.mdx index c4d872f8e63..45d6a6841d2 100644 --- a/src/pages/[platform]/deploy-and-host/fullstack-branching/share-resources/index.mdx +++ b/src/pages/[platform]/deploy-and-host/fullstack-branching/share-resources/index.mdx @@ -37,7 +37,7 @@ You can update your app build settings to share resources across branches. From ![The build specification YAML file on the Build settings page in Amplify console.](/images/gen2/fullstack-branching/build-settings.png) -Update the build settings for the `backend` phase to run `npx ampx generate outputs --branch dev app-id $AWS_APP_ID` to generate the `amplifyconfiguration.json` file for all branches other than `main` or `dev`. After this update, any new deployed branches will not deploy backend resources as part of the build and instead will use the deployed backend resources from the `dev` branch. +Update the build settings for the `backend` phase to run `npx amplify generate config --branch dev app-id $AWS_APP_ID` to generate the `amplify_outputs.json` file for all branches other than `main` or `dev`. After this update, any new deployed branches will not deploy backend resources as part of the build and instead will use the deployed backend resources from the `dev` branch. ```yaml title="amplify.yml" version: 1 diff --git a/src/pages/[platform]/reference/cli-commands/index.mdx b/src/pages/[platform]/reference/cli-commands/index.mdx index 7ef866523b6..23eaaaf61dc 100644 --- a/src/pages/[platform]/reference/cli-commands/index.mdx +++ b/src/pages/[platform]/reference/cli-commands/index.mdx @@ -225,7 +225,7 @@ npx ampx generate outputs --stack amplify-nextamplifygen2-josef-sandbox-ca85e108 #### Use with mobile applications -Similar to `sandbox`, you can specify an alternate configuration file format by using `--format`: +Similar to `sandbox`, you can specify an alternate outputs file format by using `--format`: ```bash title="Terminal" showLineNumbers={false} npx ampx generate outputs --stack amplify-nextamplifygen2-josef-sandbox-ca85e1081b diff --git a/src/pages/gen1/[platform]/build-a-backend/storage/configure-access/index.mdx b/src/pages/gen1/[platform]/build-a-backend/storage/configure-access/index.mdx index e42414f412d..92d95900ab0 100644 --- a/src/pages/gen1/[platform]/build-a-backend/storage/configure-access/index.mdx +++ b/src/pages/gen1/[platform]/build-a-backend/storage/configure-access/index.mdx @@ -44,7 +44,7 @@ import common_configureaccess from '/src/fragments/lib/storage/native_common/con We recommend using the new [Amplify Gen2](https://docs.amplify.aws/gen2/build-a-backend/storage/) experience when defining file access permissions as it offers a more flexible approach to customize access to files. -Note: `accessLevel` parameter is deprecated and maybe removed in next major version. +Note: `accessLevel` parameter is deprecated and may be removed in the next major version. Storage module can manage files with three different access levels; `guest`, `protected` and `private`. The Amplify CLI configures three different access levels on the storage bucket: guest, protected and private. When you run `amplify add storage`, the CLI will configure appropriate IAM policies on the bucket using a Cognito identity pool Role. You will have the option of adding CRUD (Create/Update, Read and Delete) based permissions as well, so that Authenticated and Guest users will be granted limited permissions within these levels. diff --git a/src/pages/gen1/[platform]/build-a-backend/storage/list/index.mdx b/src/pages/gen1/[platform]/build-a-backend/storage/list/index.mdx index 8039f3658d6..737f01bec5e 100644 --- a/src/pages/gen1/[platform]/build-a-backend/storage/list/index.mdx +++ b/src/pages/gen1/[platform]/build-a-backend/storage/list/index.mdx @@ -250,4 +250,8 @@ const loadNextPage = async () => { Note: The range of pageSize can be from 0 - 1000. +## List with no prefix (Deprecated) + +The usage of the `list` API without a specified prefix `await list()` or with an empty string as the prefix `await list({ prefix: "" })` is now deprecated and may be removed in the next major version. + diff --git a/src/pages/gen1/[platform]/build-a-backend/storage/path/index.mdx b/src/pages/gen1/[platform]/build-a-backend/storage/path/index.mdx index 23f9c4627a8..e99205a0874 100644 --- a/src/pages/gen1/[platform]/build-a-backend/storage/path/index.mdx +++ b/src/pages/gen1/[platform]/build-a-backend/storage/path/index.mdx @@ -42,7 +42,8 @@ export function getStaticProps(context) { You can now use the `path` parameter in the API to access any path within your S3 bucket. This provides more flexibility than the predefined `protected`, `private`, or `guest` folder access levels, allowing you to create and manage a storage structure tailored to your needs. -Note : `path` parameter can not be empty or start with a '/' (leading slash) +Note: `path` parameter can not be empty or start with a '/' (leading slash) + The sections below explain how to use existing `guest`, `protected`, and `private` resources with path-based APIs. ## Using Guest accessLevel diff --git a/src/pages/gen1/[platform]/tools/console/authz/permissions/index.mdx b/src/pages/gen1/[platform]/tools/console/authz/permissions/index.mdx index 55ffd5832bf..28c1372be93 100644 --- a/src/pages/gen1/[platform]/tools/console/authz/permissions/index.mdx +++ b/src/pages/gen1/[platform]/tools/console/authz/permissions/index.mdx @@ -71,4 +71,4 @@ If you want your data model to be publicly accessible, switch to API_KEY or IAM 1. Using the *Books* data model that you created in the [Create a data model example](/gen1/[platform]/tools/console/data/data-model/#Create-a-data-model-example), set the authorization mode to **API Key**. 2. In the **Model** pane on the right, expand the **Anyone** window. Choose **Read** to specify that any signed in user has read access to the data in the *Book* model. -![](/images/console/7_publicauthreadonly.png) +![](/images/console/7_authreadonly.png) diff --git a/tasks/console-errors.js b/tasks/console-errors.js new file mode 100644 index 00000000000..cdc750fe460 --- /dev/null +++ b/tasks/console-errors.js @@ -0,0 +1,109 @@ +const puppeteer = require('puppeteer'); // eslint-disable-line +const { getSitemapUrls } = require('./get-sitemap-links'); // eslint-disable-line + +// Here we are excluding shortbread errors because these are domain specific and are expected to fail in a local environment +const excludedErrors = [ + { + type: 'Shortbread', + errorText: + "Shortbread failed to set user's cookie preference because the domain name that was passed" + } +]; + +const excludedScripts = [ + 'prod.assets.shortbread.aws', + 'prod.tools.shortbread.aws', + 'prod.tools.shortbread.aws.dev', + 'aa0.awsstatic.com', + 'alpha.d2c.marketing.aws.dev', + 'vs-alpha.aws.amazon.com' +]; + +const LOCALHOST = 'http://localhost:3000'; + +const checkPage = async (url) => { + const errorsFound = []; + const browser = await puppeteer.launch({ headless: 'new' }); + + const page = await browser.newPage(); + + await page.setRequestInterception(true); + + page + .on('pageerror', (message) => { + const errorText = message.message; + const excluded = excludedErrors.some((excludedError) => { + return errorText.includes(excludedError.errorText); + }); + + if (!excluded) { + errorsFound.push({ + page: url, + message: errorText + }); + } + }) + .on('console', (message) => { + if (message.type().toLowerCase() === 'error') { + const errorText = message.text(); + const callingScript = message.location().url; + const excludedFromError = excludedErrors.some((excludedError) => { + return errorText.includes(excludedError.errorText); + }); + const excludedFromScript = excludedScripts.some((excludedScript) => { + return callingScript.includes(excludedScript); + }); + const excluded = excludedFromError || excludedFromScript; + + if (!excluded) { + errorsFound.push({ + page: url, + message: errorText, + stackTrace: message.stackTrace() + }); + } + } + }) + + .on('request', (interceptedRequest) => { + const excludedFromScript = excludedScripts.some((excludedScript) => { + return interceptedRequest.url().includes(excludedScript); + }); + if (excludedFromScript) { + interceptedRequest.abort(); + } else interceptedRequest.continue(); + }); + + await page.goto(url, { waitUntil: 'domcontentloaded' }); + + await browser.close(); + + return errorsFound; +}; + +const consoleErrors = async (domain) => { + const pagesToCheck = await getSitemapUrls(domain); + let errorMessage = ''; + for (let i = 0; i < pagesToCheck.length; i++) { + const url = pagesToCheck[i]; + console.log(`checking page ${url}`); + const errorsFound = await checkPage(url); + errorsFound.forEach((error) => { + errorMessage += `${error.message} found on ${error.page}\n`; + }); + } + if (errorMessage != '') { + console.log( + `--------- Console errors have been found and need to be resolved in order to merge. ------- + ------- Please note that these errors could be on pages that were not edited in this PR. ---------` + ); + console.log(errorMessage); + } + return errorMessage; +}; + +module.exports = { + consoleErrors: async (domain = LOCALHOST) => { + return await consoleErrors(domain); + } +}; diff --git a/tasks/get-sitemap-links.js b/tasks/get-sitemap-links.js new file mode 100644 index 00000000000..8e40ac783a2 --- /dev/null +++ b/tasks/get-sitemap-links.js @@ -0,0 +1,42 @@ +const puppeteer = require('puppeteer'); // eslint-disable-line + +const DOMAIN = 'https://docs.amplify.aws'; +const SITEMAP_URL = 'https://docs.amplify.aws/sitemap.xml'; + +const getSitemapUrls = async (localDomain) => { + let browser = await puppeteer.launch({ headless: 'new' }); + + const page = await browser.newPage(); + + let siteMap = localDomain ? `${localDomain}/sitemap.xml` : SITEMAP_URL; + let response = await page.goto(siteMap); + + const siteMapUrls = []; + + if (response && response.status() && response.status() === 200) { + const urlTags = await page.evaluateHandle(() => { + return document.getElementsByTagName('loc'); + }); + const numOfLinks = await page.evaluate((e) => e.length, urlTags); + for (let i = 0; i < numOfLinks; i++) { + let url = await page.evaluate( + (urlTags, i) => urlTags[i].innerHTML, + urlTags, + i + ); + if (localDomain) { + // Currently the sitemap is always generated with the prod docs domain so we need to replace this with localhost + url = url.replace(DOMAIN, localDomain); + } + siteMapUrls.push(url); + } + } + browser.close(); + return siteMapUrls; +}; + +module.exports = { + getSitemapUrls: async (domain) => { + return await getSitemapUrls(domain); + } +}; diff --git a/yarn.lock b/yarn.lock index 2dec273099d..33e00175b74 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5105,10 +5105,10 @@ eastasianwidth@^0.2.0: resolved "https://registry.yarnpkg.com/eastasianwidth/-/eastasianwidth-0.2.0.tgz#696ce2ec0aa0e6ea93a397ffcf24aa7840c827cb" integrity sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA== -ejs@^3.1.7: - version "3.1.9" - resolved "https://registry.yarnpkg.com/ejs/-/ejs-3.1.9.tgz#03c9e8777fe12686a9effcef22303ca3d8eeb361" - integrity sha512-rC+QVNMJWv+MtPgkt0y+0rVEIdbtxVADApW9JXrUVlzHetgcyczP/E7DJmWJ4fJCZF2cPcBk0laWO9ZHMG3DmQ== +ejs@3.1.10, ejs@^3.1.7: + version "3.1.10" + resolved "https://registry.yarnpkg.com/ejs/-/ejs-3.1.10.tgz#69ab8358b14e896f80cc39e62087b88500c3ac3b" + integrity sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA== dependencies: jake "^10.8.5" @@ -5170,11 +5170,6 @@ enquirer@^2.3.6: ansi-colors "^4.1.1" strip-ansi "^6.0.1" -entities@^4.2.0, entities@^4.4.0: - version "4.5.0" - resolved "https://registry.yarnpkg.com/entities/-/entities-4.5.0.tgz#5d268ea5e7113ec74c4d033b79ea5a35a488fb48" - integrity sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw== - env-paths@^2.2.1: version "2.2.1" resolved "https://registry.yarnpkg.com/env-paths/-/env-paths-2.2.1.tgz#420399d416ce1fbe9bc0a07c62fa68d67fd0f8f2" From 406d1caab20cd7327920fea90fc1ed4dbd9006d3 Mon Sep 17 00:00:00 2001 From: Muhammed Salih Guler Date: Thu, 2 May 2024 20:41:10 +0200 Subject: [PATCH 12/17] [Gen 2] Add the feedback for custom sign in. (#7443) * Add the feedback. * Update the title. * Add docs to custom_auth. * Add the missing docs. * Update the sentence. --- .../custom-auth-flows/index.mdx | 148 ++---------------- 1 file changed, 13 insertions(+), 135 deletions(-) diff --git a/src/pages/[platform]/build-a-backend/auth/customize-auth-lifecycle/custom-auth-flows/index.mdx b/src/pages/[platform]/build-a-backend/auth/customize-auth-lifecycle/custom-auth-flows/index.mdx index bba14684a30..5dadf1e6cd6 100644 --- a/src/pages/[platform]/build-a-backend/auth/customize-auth-lifecycle/custom-auth-flows/index.mdx +++ b/src/pages/[platform]/build-a-backend/auth/customize-auth-lifecycle/custom-auth-flows/index.mdx @@ -6,14 +6,8 @@ export const meta = { 'Use Amazon Cognito Auth plugin to sign in a user into Amazon Cognito User Pool using user defined custom flow', platforms: [ 'android', - // 'angular', 'flutter', - // 'javascript', - // 'nextjs', - // 'react', - // 'react-native', 'swift', - // 'vue' ], }; @@ -41,7 +35,7 @@ An application with Amplify libraries integrated and a minimum target of any of - **watchOS 9.0**, using **Xcode 14.3** or later. - **visionOS 1.0**, using **Xcode 15 beta 2** or later. (Preview support - see below for more details.) -For a full example, please follow the [project setup walkthrough](/[platform]/start/project-setup/prerequisites/). +For a full example, please follow the [project setup walkthrough](/[platform]/start/quickstart/). @@ -66,7 +60,7 @@ For more information on adding capabilities to your application, see [Xcode Capa The custom auth flow can be [configured manually](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-challenge.html). -If you have already configured custom auth, you can use the custom auth flow by changing the `authenticationFlowType` value in your [Amplify configuration](/[platform]/build-a-backend/auth/existing-resources/) to `CUSTOM_AUTH`. +If you have already configured custom auth, you can use the custom auth flow by changing the `authenticationFlowType` value in your Amplify configuration to `CUSTOM_AUTH`. For more information on authentication flow types, you can check out the [Cognito documentation](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html). ## Register a user @@ -244,7 +238,7 @@ Since this is a custom authentication flow with a challenge, the result of the s ## Confirm sign in with custom challenge -Get the custom challenge (`1234` in this case) from the user and pass it to the `confirmSignin()` api. +To get a custom challenge from the user, create an appropriate UI for the user to submit the required value, and pass that value into the `confirmSignin()` API. @@ -294,9 +288,9 @@ Confirm sign in succeeded ### Lambda Trigger Setup -AWS Amplify now supports creating functions as part of its new backend experience. For more information on the Functions and how to start with them check out [Functions documentation](/[platform]/build-a-backend/functions/). In addition, more information on available triggers can be found in the [Cognito documentation](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-challenge.html). +AWS Amplify now supports creating functions as part of its new backend experience. For more information on the Functions and how to start with them check out [Functions documentation](/[platform]/build-a-backend/functions/). In addition, more information on available triggers can be found in the [Cognito documentation](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html). -### Custom Auth Flow with SRP +### Custom Auth Flow with Secure Remote Password (SRP) Cognito User Pool allows to start the custom authentication flow with SRP as the first step. If you would like to use this flow, setup Define Auth Lambda trigger to handle SRP_A as the first challenge as shown below: @@ -337,64 +331,6 @@ let signInResult = try await Amplify.Auth.signIn( options: .init(pluginOptions: options)) ``` -### CAPTCHA-based authentication - -Here is the sample for creating a CAPTCHA challenge with a Lambda Trigger. - -The `Create Auth Challenge Lambda Trigger` creates a CAPTCHA as a challenge to the user. The URL for the CAPTCHA image and the expected answer is added to the private challenge parameters: - -```javascript -export const handler = async (event) => { - if (!event.request.session || event.request.session.length === 0) { - event.response.publicChallengeParameters = { - captchaUrl: , - }; - event.response.privateChallengeParameters = { - answer: , - }; - event.response.challengeMetadata = "CAPTCHA_CHALLENGE"; - } - return event; -}; -``` - -This `Define Auth Challenge Lambda Trigger` defines a custom challenge: - -```javascript -export const handler = async (event) => { - if (!event.request.session || event.request.session.length === 0) { - // If we don't have a session or it is empty then send a CUSTOM_CHALLENGE - event.response.challengeName = "CUSTOM_CHALLENGE"; - event.response.failAuthentication = false; - event.response.issueTokens = false; - } else if (event.request.session.length === 1 && event.request.session[0].challengeResult === true) { - // If we passed the CUSTOM_CHALLENGE then issue token - event.response.failAuthentication = false; - event.response.issueTokens = true; - } else { - // Something is wrong. Fail authentication - event.response.failAuthentication = true; - event.response.issueTokens = false; - } - - return event; -}; -``` - -The `Verify Auth Challenge Response Lambda Trigger` is used to verify a challenge answer: - -```javascript -export const handler = async (event, context) => { - if (event.request.privateChallengeParameters.answer === event.request.challengeAnswer) { - event.response.answerCorrect = true; - } else { - event.response.answerCorrect = false; - } - - return event; -}; -``` - The Auth category can be configured to perform a [custom authentication flow](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-challenge.html) defined by you. The following guide shows how to setup a simple passwordless authentication flow. @@ -402,13 +338,13 @@ The Auth category can be configured to perform a [custom authentication flow](ht ## Prerequisites * An Android application targeting at least Android SDK API level 24 with Amplify libraries integrated - * For a full example of creating Android project, please follow the [project setup walkthrough](/[platform]/start/project-setup/create-application/) + * For a full example of creating Android project, please follow the [project setup walkthrough](/[platform]/start/quickstart/) ## Configure Auth The custom auth flow can be [configured manually](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-challenge.html). -If you have already configured custom auth, you can use the custom auth flow by changing the `authenticationFlowType` value in your [Amplify configuration](/[platform]/build-a-backend/auth/existing-resources/) to `CUSTOM_AUTH`. +If you have already configured custom auth, you can use the custom auth flow by changing the `authenticationFlowType` value in your Amplify configuration to `CUSTOM_AUTH`. For more information on authentication flow types, you can check out the [Cognito documentation](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html). ## Register a user @@ -683,9 +619,9 @@ Confirm sign in succeeded ### Lambda Trigger Setup -AWS Amplify now supports creating functions as part of the AWS Amplify. For more information on the Functions and how to start with them check out [Functions documentation](/[platform]/build-a-backend/functions/). In addition, more information on available triggers can be found in the [Cognito documentation](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-challenge.html). +AWS Amplify now supports creating functions as part of the AWS Amplify. For more information on the Functions and how to start with them check out [Functions documentation](/[platform]/build-a-backend/functions/). In addition, more information on available triggers can be found in the [Cognito documentation](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html). -### Custom Auth Flow with SRP +### Custom Auth Flow with Secure Remote Password (SRP) Cognito User Pool allows to start the custom authentication flow with SRP as the first step. If you would like to use this flow, setup Define Auth Lambda trigger to handle SRP_A as the first challenge as shown below: @@ -793,64 +729,6 @@ RxAmplify.Auth.signIn("username", "password", options) -### CAPTCHA-based authentication - -Here is the sample for creating a CAPTCHA challenge with a Lambda Trigger. - -The `Create Auth Challenge Lambda Trigger` creates a CAPTCHA as a challenge to the user. The URL for the CAPTCHA image and the expected answer are added to the private challenge parameters: - -```javascript -export const handler = async (event) => { - if (!event.request.session || event.request.session.length === 0) { - event.response.publicChallengeParameters = { - captchaUrl: , - }; - event.response.privateChallengeParameters = { - answer: , - }; - event.response.challengeMetadata = "CAPTCHA_CHALLENGE"; - } - return event; -}; -``` - -This `Define Auth Challenge Lambda Trigger` defines a custom challenge: - -```javascript -export const handler = async (event) => { - if (!event.request.session || event.request.session.length === 0) { - // If we don't have a session or it is empty then send a CUSTOM_CHALLENGE - event.response.challengeName = "CUSTOM_CHALLENGE"; - event.response.failAuthentication = false; - event.response.issueTokens = false; - } else if (event.request.session.length === 1 && event.request.session[0].challengeResult === true) { - // If we passed the CUSTOM_CHALLENGE then issue token - event.response.failAuthentication = false; - event.response.issueTokens = true; - } else { - // Something is wrong. Fail authentication - event.response.failAuthentication = true; - event.response.issueTokens = false; - } - - return event; -}; -``` - -The `Verify Auth Challenge Response Lambda Trigger` is used to verify a challenge answer: - -```javascript -export const handler = async (event, context) => { - if (event.request.privateChallengeParameters.answer === event.request.challengeAnswer) { - event.response.answerCorrect = true; - } else { - event.response.answerCorrect = false; - } - - return event; -}; -``` - @@ -859,13 +737,13 @@ The Auth category can be configured to perform a [custom authentication flow](ht ## Prerequisites A Flutter application targeting Flutter SDK >= 3.3.0 with Amplify libraries integrated. -Amplify requires a minimum target platform for iOS (13.0), Android (API level 24), and macOS (10.15). Additional setup is required for some target platforms. Please see the [platform setup](/[platform]/start/project-setup/platform-setup/) guide for more details on platform specific setup. +Amplify requires a minimum target platform for iOS (13.0), Android (API level 24), and macOS (10.15). Additional setup is required for some target platforms. Please see the [platform setup](/[platform]/build-a-backend/auth/connect-your-frontend/sign-in/#platform-setup) for more details on platform specific setup. ## Configure Auth The custom auth flow can be [configured manually](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-challenge.html). -If you have already configured custom auth, you can use the custom auth flow by changing the `authenticationFlowType` value in your [Amplify configuration](/[platform]/build-a-backend/auth/existing-resources/) to `CUSTOM_AUTH`. +If you have already configured custom auth, you can use the custom auth flow by changing the `authenticationFlowType` value in your Amplify configuration to `CUSTOM_AUTH`. For more information on authentication flow types, you can check out the [Cognito documentation](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html). ## Register a user @@ -946,7 +824,7 @@ user has already signed in and a valid session is active. You must first call ## Confirm sign in with custom challenge -Get the custom challenge (`1234` in this case) from the user and pass it to the `confirmSignin()` api. +To get a custom challenge from the user, create an appropriate UI for the user to submit the required value, and pass that value into the `confirmSignin()` API. ```dart Future confirmSignIn(String generatedNumber) async { @@ -977,7 +855,7 @@ Exception: `NotAuthorizedException` with a message `Invalid session for the user The example in this documentation demonstrates the passwordless custom authentication flow. However, it is also possible to require that users supply a valid password as part of the custom authentication flow. -To require a valid password, you can alter the `DefineAuthChallenge` code to handle a `PASSWORD_VERIFIER` step: +To require a valid password, you can alter the [DefineAuthChallenge](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-define-auth-challenge.html) code to handle a `PASSWORD_VERIFIER` step: ```js exports.handler = async (event) => { From 73b0a7420c96a43da46044bc9482e677586504df Mon Sep 17 00:00:00 2001 From: Muhammed Salih Guler Date: Thu, 2 May 2024 20:53:48 +0200 Subject: [PATCH 13/17] [Gen 2][Android] Update the calls for Amplify.configure for Gen 2 docs. (#7368) * Update the calls for Amplify.configure for Gen 2 docs. * Update the callout, add the updates for Java and RxJava. * Remove unnecessary empty line. * Update the callouts. * Update the last sentence of callout. * Update the generate command * Update the generate config terminal. * Apply suggestions from code review Co-authored-by: josef --------- Co-authored-by: josef --- .../analytics/set-up-analytics/index.mdx | 10 ++++++++++ .../add-aws-services/geo/set-up-geo/index.mdx | 10 ++++++++++ .../logging/set-up-logging/index.mdx | 11 +++++++++++ .../rest-api/set-up-rest-api/index.mdx | 16 +++++++++++++--- .../build-a-backend/auth/set-up-auth/index.mdx | 12 +++++++++++- .../build-a-backend/data/set-up-data/index.mdx | 13 +++++++++++-- .../storage/set-up-storage/index.mdx | 13 +++++++++++-- .../branch-deployments/index.mdx | 2 +- .../sandbox-environments/features/index.mdx | 2 +- src/pages/[platform]/start/quickstart/index.mdx | 12 +++++++++++- 10 files changed, 90 insertions(+), 11 deletions(-) diff --git a/src/pages/[platform]/build-a-backend/add-aws-services/analytics/set-up-analytics/index.mdx b/src/pages/[platform]/build-a-backend/add-aws-services/analytics/set-up-analytics/index.mdx index 13245341e63..694f336806f 100644 --- a/src/pages/[platform]/build-a-backend/add-aws-services/analytics/set-up-analytics/index.mdx +++ b/src/pages/[platform]/build-a-backend/add-aws-services/analytics/set-up-analytics/index.mdx @@ -378,6 +378,16 @@ To initialize the Amplify Auth and Analytics categories you call `Amplify.addPlu Add the following code to your `onCreate()` method in your application class: + +Before calling the `Amplify.configure` function, make sure to either download the `amplify_outputs.json` file from the console, or generate it with the following command: + +```bash title="Terminal" showLineNumbers={false} +npx ampx generate outputs --app-id --branch main --out-dir app/src/main/res/raw +``` + +Next, be sure the file you generated or downloaded is in the appropriate resource directory for your application (for example, `app/src/main/res/raw`) in your Android project. Otherwise, you will not be able to compile your application. + + diff --git a/src/pages/[platform]/build-a-backend/add-aws-services/geo/set-up-geo/index.mdx b/src/pages/[platform]/build-a-backend/add-aws-services/geo/set-up-geo/index.mdx index bca830964f4..556ee8a4ece 100644 --- a/src/pages/[platform]/build-a-backend/add-aws-services/geo/set-up-geo/index.mdx +++ b/src/pages/[platform]/build-a-backend/add-aws-services/geo/set-up-geo/index.mdx @@ -219,6 +219,16 @@ To initialize Amplify Geo, use the `Amplify.addPlugin()` method to add the AWS L Add the following code to your `onCreate()` method in your application class: + +Before calling the `Amplify.configure` function, make sure to either download the `amplify_outputs.json` file from the console, or generate it with the following command: + +```bash title="Terminal" showLineNumbers={false} +npx ampx generate outputs --app-id --branch main --out-dir app/src/main/res/raw +``` + +Next, be sure the file you generated or downloaded is in the appropriate resource directory for your application (for example, `app/src/main/res/raw`) in your Android project. Otherwise, you will not be able to compile your application. + + diff --git a/src/pages/[platform]/build-a-backend/add-aws-services/logging/set-up-logging/index.mdx b/src/pages/[platform]/build-a-backend/add-aws-services/logging/set-up-logging/index.mdx index d0aee6b2bf7..ce24f145492 100644 --- a/src/pages/[platform]/build-a-backend/add-aws-services/logging/set-up-logging/index.mdx +++ b/src/pages/[platform]/build-a-backend/add-aws-services/logging/set-up-logging/index.mdx @@ -156,6 +156,17 @@ The `` and `` is the value you specified in the CDK cons To use the Amplify Logger and Amplify Auth categories in your app, you need to create and configure their corresponding plugins by calling the `Amplify.addPlugin()` and `Amplify.configure()` methods. Add the following imports to the top of your main `Application` file: + + +Before calling the `Amplify.configure` function, make sure to either download the `amplify_outputs.json` file from the console, or generate it with the following command: + +```bash title="Terminal" showLineNumbers={false} +npx ampx generate outputs --app-id --branch main --out-dir app/src/main/res/raw +``` + +Next, be sure the file you generated or downloaded is in the appropriate resource directory for your application (for example, `app/src/main/res/raw`) in your Android project. Otherwise, you will not be able to compile your application. + + diff --git a/src/pages/[platform]/build-a-backend/add-aws-services/rest-api/set-up-rest-api/index.mdx b/src/pages/[platform]/build-a-backend/add-aws-services/rest-api/set-up-rest-api/index.mdx index cfa9fecef99..cb10bfeab1a 100644 --- a/src/pages/[platform]/build-a-backend/add-aws-services/rest-api/set-up-rest-api/index.mdx +++ b/src/pages/[platform]/build-a-backend/add-aws-services/rest-api/set-up-rest-api/index.mdx @@ -523,6 +523,16 @@ To initialize the Amplify Auth and API categories you call `Amplify.addPlugin()` Add the following code to your `onCreate()` method in your application class: + +Before calling the `Amplify.configure` function, make sure to either download the `amplify_outputs.json` file from the console, or generate it with the following command: + +```bash title="Terminal" showLineNumbers={false} +npx ampx generate outputs --app-id --branch main --out-dir app/src/main/res/raw +``` + +Next, be sure the file you generated or downloaded is in the appropriate resource directory for your application (for example, `app/src/main/res/raw`) in your Android project. Otherwise, you will not be able to compile your application. + + @@ -543,7 +553,7 @@ public class MyAmplifyApp extends Application { // Add these lines to add the `AWSApiPlugin` and `AWSCognitoAuthPlugin` Amplify.addPlugin(new AWSApiPlugin()); Amplify.addPlugin(new AWSCognitoAuthPlugin()); - Amplify.configure(getApplicationContext()); + Amplify.configure(AmplifyOutputs.fromResource(R.raw.amplify_outputs), getApplicationContext()); Log.i("MyAmplifyApp", "Initialized Amplify."); } catch (AmplifyException error) { @@ -572,7 +582,7 @@ class MyAmplifyApp : Application() { // Add these lines to add the `AWSApiPlugin` and `AWSCognitoAuthPlugin` Amplify.addPlugin(AWSApiPlugin()) Amplify.addPlugin(AWSCognitoAuthPlugin()) - Amplify.configure(applicationContext) + Amplify.configure(AmplifyOutputs(R.raw.amplify_outputs), applicationContext) Log.i("MyAmplifyApp", "Initialized Amplify.") } catch (error: AmplifyException) { @@ -602,7 +612,7 @@ public class MyAmplifyApp extends Application { // Add these lines to add the `AWSApiPlugin` and `AWSCognitoAuthPlugin` RxAmplify.addPlugin(new AWSApiPlugin()); RxAmplify.addPlugin(new AWSCognitoAuthPlugin()); - RxAmplify.configure(getApplicationContext()); + RxAmplify.configure(AmplifyOutputs.fromResource(R.raw.amplify_outputs), getApplicationContext()); Log.i("MyAmplifyApp", "Initialized Amplify."); } catch (AmplifyException error) { diff --git a/src/pages/[platform]/build-a-backend/auth/set-up-auth/index.mdx b/src/pages/[platform]/build-a-backend/auth/set-up-auth/index.mdx index 6274837684d..e13050f74ec 100644 --- a/src/pages/[platform]/build-a-backend/auth/set-up-auth/index.mdx +++ b/src/pages/[platform]/build-a-backend/auth/set-up-auth/index.mdx @@ -505,6 +505,16 @@ dependencies { + +Before calling the `Amplify.configure` function, make sure to either download the `amplify_outputs.json` file from the console, or generate it with the following command: + +```bash title="Terminal" showLineNumbers={false} +npx ampx generate outputs --app-id --branch main --out-dir app/src/main/res/raw +``` + +Next, be sure the file you generated or downloaded is in the appropriate resource directory for your application (for example, `app/src/main/res/raw`) in your Android project. Otherwise, you will not be able to compile your application. + + ```kotlin title="MyAmplifyApp.kt" import android.app.Application import android.util.Log @@ -520,7 +530,7 @@ class MyAmplifyApp: Application() { try { // highlight-next-line Amplify.addPlugin(AWSCognitoAuthPlugin()) - Amplify.configure(AmplifyOutputs.fromResource(R.raw.amplify_outputs), applicationContext) + Amplify.configure(AmplifyOutputs(R.raw.amplify_outputs), applicationContext) Log.i("MyAmplifyApp", "Initialized Amplify") } catch (error: AmplifyException) { Log.e("MyAmplifyApp", "Could not initialize Amplify", error) diff --git a/src/pages/[platform]/build-a-backend/data/set-up-data/index.mdx b/src/pages/[platform]/build-a-backend/data/set-up-data/index.mdx index 307d1958169..eb6b57ff583 100644 --- a/src/pages/[platform]/build-a-backend/data/set-up-data/index.mdx +++ b/src/pages/[platform]/build-a-backend/data/set-up-data/index.mdx @@ -160,6 +160,16 @@ Next, configure the Amplify client library with the generated `amplifyconfigurat Create a new `MyAmplifyApp` class that inherits from `Application` with the following code: + +Before calling the `Amplify.configure` function, make sure to either download the `amplify_outputs.json` file from the console, or generate it with the following command: + +```bash title="Terminal" showLineNumbers={false} +npx ampx generate outputs --app-id --branch main --out-dir app/src/main/res/raw +``` + +Next, be sure the file you generated or downloaded is in the appropriate resource directory for your application (for example, `app/src/main/res/raw`) in your Android project. Otherwise, you will not be able to compile your application. + + ```kt package com.example.myapplication @@ -180,8 +190,7 @@ class MyAmplifyApp : Application() { Amplify.addPlugin(AWSApiPlugin()) // Configures the client library to be aware of your backend API // endpoint and authorization modes. - Amplify.configure(AmplifyOutputs.fromResource(R.raw.amplify_outputs), applicationContext) - + Amplify.configure(AmplifyOutputs(R.raw.amplify_outputs), applicationContext) Log.i("Tutorial", "Initialized Amplify") } catch (error: AmplifyException) { Log.e("Tutorial", "Could not initialize Amplify", error) diff --git a/src/pages/[platform]/build-a-backend/storage/set-up-storage/index.mdx b/src/pages/[platform]/build-a-backend/storage/set-up-storage/index.mdx index af9679dfa77..248b285b6e9 100644 --- a/src/pages/[platform]/build-a-backend/storage/set-up-storage/index.mdx +++ b/src/pages/[platform]/build-a-backend/storage/set-up-storage/index.mdx @@ -277,6 +277,16 @@ Initialize Amplify Storage by calling `Amplify.addPlugin()`. To complete initial Add the following code to your `onCreate()` method in your application class: + +Before calling the `Amplify.configure` function, make sure to either download the `amplify_outputs.json` file from the console, or generate it with the following command: + +```bash title="Terminal" showLineNumbers={false} +npx ampx generate outputs --app-id --branch main --out-dir app/src/main/res/raw +``` + +Next, be sure the file you generated or downloaded is in the appropriate resource directory for your application (for example, `app/src/main/res/raw`) in your Android project. Otherwise, you will not be able to compile your application. + + @@ -342,8 +352,7 @@ class MyAmplifyApp : Application() { // Add these lines to add the AWSCognitoAuthPlugin and AWSS3StoragePlugin plugins Amplify.addPlugin(AWSCognitoAuthPlugin()) Amplify.addPlugin(AWSS3StoragePlugin()) - Amplify.configure(AmplifyOutputs.fromResource(R.raw.amplify_outputs), applicationContext) - + Amplify.configure(AmplifyOutputs(R.raw.amplify_outputs), applicationContext) Log.i("MyAmplifyApp", "Initialized Amplify") } catch (error: AmplifyException) { Log.e("MyAmplifyApp", "Could not initialize Amplify", error) diff --git a/src/pages/[platform]/deploy-and-host/fullstack-branching/branch-deployments/index.mdx b/src/pages/[platform]/deploy-and-host/fullstack-branching/branch-deployments/index.mdx index 5c0b2a51995..fc700488fcd 100644 --- a/src/pages/[platform]/deploy-and-host/fullstack-branching/branch-deployments/index.mdx +++ b/src/pages/[platform]/deploy-and-host/fullstack-branching/branch-deployments/index.mdx @@ -91,7 +91,7 @@ npx ampx generate outputs --app-id --branch main --out-dir ```bash title="Terminal" showLineNumbers={false} -npx ampx generate config --app-id --branch main --out-dir app/src/main/res/raw +npx ampx generate outputs --app-id --branch main --out-dir app/src/main/res/raw ``` diff --git a/src/pages/[platform]/deploy-and-host/sandbox-environments/features/index.mdx b/src/pages/[platform]/deploy-and-host/sandbox-environments/features/index.mdx index c143ee7e1f6..1fae0711111 100644 --- a/src/pages/[platform]/deploy-and-host/sandbox-environments/features/index.mdx +++ b/src/pages/[platform]/deploy-and-host/sandbox-environments/features/index.mdx @@ -234,7 +234,7 @@ npx ampx generate config --app-id --branch main --format dart --out-dir ```bash title="Terminal" showLineNumbers={false} -npx ampx generate config --app-id --branch main --format json-mobile --out-dir app/src/main/res/raw +npx ampx generate outputs --app-id --branch main --out-dir app/src/main/res/raw ``` diff --git a/src/pages/[platform]/start/quickstart/index.mdx b/src/pages/[platform]/start/quickstart/index.mdx index 749602c6891..40f83c25d89 100644 --- a/src/pages/[platform]/start/quickstart/index.mdx +++ b/src/pages/[platform]/start/quickstart/index.mdx @@ -2020,6 +2020,16 @@ dependencies { Afterwards create a `MyAmplifyApp` class that extends `Application` and add the following code: + +Before calling the `Amplify.configure` function, make sure to either download the `amplify_outputs.json` file from the console, or generate it with the following command: + +```bash title="Terminal" showLineNumbers={false} +npx ampx generate outputs --app-id --branch main --out-dir app/src/main/res/raw +``` + +Next, be sure the file you generated or downloaded is in the appropriate resource directory for your application (for example, `app/src/main/res/raw`) in your Android project. Otherwise, you will not be able to compile your application. + + ```kotlin title="MyAmplifyApp.kt" import android.app.Application import android.util.Log @@ -2034,7 +2044,7 @@ class MyAmplifyApp: Application() { try { Amplify.addPlugin(AWSCognitoAuthPlugin()) - Amplify.configure(AmplifyOutputs.fromResource(R.raw.amplify_outputs), applicationContext) + Amplify.configure(AmplifyOutputs(R.raw.amplify_outputs), applicationContext) Log.i("MyAmplifyApp", "Initialized Amplify") } catch (error: AmplifyException) { Log.e("MyAmplifyApp", "Could not initialize Amplify", error) From 2c339531416c68c7aa1d4535d2fd1b0cca93e1d2 Mon Sep 17 00:00:00 2001 From: Ali Spittel Date: Thu, 2 May 2024 12:55:06 -0600 Subject: [PATCH 14/17] remove a few sections for mobile (#7428) --- src/pages/[platform]/index.tsx | 218 +++++++++++++++++++++------------ 1 file changed, 138 insertions(+), 80 deletions(-) diff --git a/src/pages/[platform]/index.tsx b/src/pages/[platform]/index.tsx index 9d568f0cacf..6485de157b6 100644 --- a/src/pages/[platform]/index.tsx +++ b/src/pages/[platform]/index.tsx @@ -53,6 +53,10 @@ export function getStaticProps() { const Gen2Overview = () => { const currentPlatform = useCurrentPlatform(); + const isMobilePlatform = ['swift', 'android', 'flutter'].includes( + currentPlatform + ); + const isFlutter = currentPlatform == 'flutter'; return ( @@ -60,12 +64,29 @@ const Gen2Overview = () => { Amplify Documentation for {PLATFORM_DISPLAY_NAMES[currentPlatform]} - - AWS Amplify is everything frontend developers need to develop and - deploy cloud-powered fullstack applications without hassle. Easily - connect your frontend to the cloud for data modeling, authentication, - storage, serverless functions, SSR app deployment, and more. - + {isFlutter ? ( + + AWS Amplify is everything Flutter developers need to develop + cloud-powered fullstack applications without hassle. Easily connect + your Flutter applications to the cloud for data modeling, + authentication, storage, serverless functions, and more. + + ) : isMobilePlatform ? ( + + AWS Amplify is everything mobile developers need to develop + cloud-powered fullstack applications without hassle. Easily connect + your cross-platform applications to the cloud for data modeling, + authentication, storage, serverless functions, and more. + + ) : ( + + AWS Amplify is everything frontend developers need to develop and + deploy cloud-powered fullstack applications without hassle. Easily + connect your frontend to the cloud for data modeling, + authentication, storage, serverless functions, SSR app deployment, + and more. + + )} { Features - - - - Code-first DX - - - The fullstack TypeScript developer experience lets you focus on - your app code instead of infrastructure. - - - + {isMobilePlatform ? ( + + + + Code-first DX + + + The new code-first developer experience lets you define your + infrastructure with TypeScript. + + + + ) : ( + + + + Code-first DX + + + The fullstack TypeScript developer experience lets you focus + on your app code instead of infrastructure. + + + + )} @@ -139,47 +174,66 @@ const Gen2Overview = () => { Develop - @@ -222,18 +278,20 @@ const Gen2Overview = () => { /> - - Deploy Next.js, Nuxt, React, Vue.js, Angular (and more) apps by - simply connecting your Git repository. - + {!isMobilePlatform && ( + + Deploy Next.js, Nuxt, React, Vue.js, Angular (and more) apps by + simply connecting your Git repository. + + )} Date: Thu, 2 May 2024 12:13:10 -0700 Subject: [PATCH 15/17] clean up remaining commands (#7458) * first pass * second pass --- .../cross-account-deployments/index.mdx | 4 ++-- .../fullstack-branching/custom-pipelines/index.mdx | 2 +- .../fullstack-branching/mono-and-multi-repos/index.mdx | 7 +++---- .../fullstack-branching/share-resources/index.mdx | 2 +- .../sandbox-environments/features/index.mdx | 6 +++--- src/pages/[platform]/reference/amplify_outputs/index.mdx | 2 +- 6 files changed, 11 insertions(+), 12 deletions(-) diff --git a/src/pages/[platform]/deploy-and-host/fullstack-branching/cross-account-deployments/index.mdx b/src/pages/[platform]/deploy-and-host/fullstack-branching/cross-account-deployments/index.mdx index 68254b42a6a..23e8d0a5896 100644 --- a/src/pages/[platform]/deploy-and-host/fullstack-branching/cross-account-deployments/index.mdx +++ b/src/pages/[platform]/deploy-and-host/fullstack-branching/cross-account-deployments/index.mdx @@ -53,7 +53,7 @@ Please refer to this Amazon CodeCatalyst [guide](https://docs.aws.amazon.com/cod ### Step 3: Update build specification -Add the `npx amplify generate config --branch $AWS_BRANCH --app-id $AWS_APP_ID` command to the build spec and comment out the `npx amplify pipeline-deploy --branch $AWS_BRANCH --app-id $AWS_APP_ID` command. `amplify pipeline-deploy` runs a script to deploy backend updates, while `amplify generate config` fetches the latest `amplify_outputs.json` for the specified environment. +Add the `npx ampx generate outputs --branch $AWS_BRANCH --app-id $AWS_APP_ID` command to the build spec and comment out the `npx ampx pipeline-deploy --branch $AWS_BRANCH --app-id $AWS_APP_ID` command. `ampx pipeline-deploy` runs a script to deploy backend updates, while `ampx generate outputs` fetches the latest `amplify_outputs.json` for the specified environment. ![Screenshot of Build image settings section in AWS Amplify Gen 2 console, with details about the app build specification](images/gen2/cross-account-deployments/pipeline10.png) @@ -183,4 +183,4 @@ Next, you can review the result of the workflow run from the **Runs** tab: ![Screenshot of CodeCatalyst console showing the Workflows section, focusing on the Runs tab](images/gen2/cross-account-deployments/pipeline11.png) -Done! You have successfully set up a custom cross-account pipeline to deploy your frontend and backend for apps built using Amplify Gen 2. To summarize, this custom pipeline will enable you to deploy your backend initially with your `staging` environment using `amplify pipeline-deploy` in the CodeCatalyst workflow and `amplify generate config` will generate the `amplify_outputs.json` file for the `main` branch. Amplify Hosting will not deploy backend resources as part of the build and instead will use the deployed backend resources from the `main` branch. Once the staging environment deploys successfully, a similar process will be followed to deploy your `production` environment in a different AWS account. +Done! You have successfully set up a custom cross-account pipeline to deploy your frontend and backend for apps built using Amplify Gen 2. To summarize, this custom pipeline will enable you to deploy your backend initially with your `staging` environment using `ampx pipeline-deploy` in the CodeCatalyst workflow and `ampx generate outputs` will generate the `amplify_outputs.json` file for the `main` branch. Amplify Hosting will not deploy backend resources as part of the build and instead will use the deployed backend resources from the `main` branch. Once the staging environment deploys successfully, a similar process will be followed to deploy your `production` environment in a different AWS account. diff --git a/src/pages/[platform]/deploy-and-host/fullstack-branching/custom-pipelines/index.mdx b/src/pages/[platform]/deploy-and-host/fullstack-branching/custom-pipelines/index.mdx index e65f045d97e..8c2ef598412 100644 --- a/src/pages/[platform]/deploy-and-host/fullstack-branching/custom-pipelines/index.mdx +++ b/src/pages/[platform]/deploy-and-host/fullstack-branching/custom-pipelines/index.mdx @@ -43,7 +43,7 @@ You can set up your backend deployments using the following steps: -3. Update the Amplify build-spec to add `npx amplify generate config --branch $AWS_BRANCH --app-id $AWS_APP_ID` and comment out the `pipeline-deploy` script. `amplify pipeline-deploy` runs a script to deploy backend updates, while `amplify generate config` fetches the latest `amplify_outputs.json` for the specified environment. +3. Update the Amplify build-spec to add `npx ampx generate outputs --branch $AWS_BRANCH --app-id $AWS_APP_ID` and comment out the `pipeline-deploy` script. `ampx pipeline-deploy` runs a script to deploy backend updates, while `ampx generate outputs` fetches the latest `amplify_outputs.json` for the specified environment. ![custom-ci](/images/gen2/fullstack-branching/custom-ci.png) diff --git a/src/pages/[platform]/deploy-and-host/fullstack-branching/mono-and-multi-repos/index.mdx b/src/pages/[platform]/deploy-and-host/fullstack-branching/mono-and-multi-repos/index.mdx index dd0b8ed6729..02e537473d6 100644 --- a/src/pages/[platform]/deploy-and-host/fullstack-branching/mono-and-multi-repos/index.mdx +++ b/src/pages/[platform]/deploy-and-host/fullstack-branching/mono-and-multi-repos/index.mdx @@ -75,8 +75,7 @@ This will generate the `amplify_outputs.json` file that contains all the informa 4. To validate that your frontend can connect to the backend, add the `Authenticator` login form to your app. -```ts -// pages/_app.tsx +```ts title="pages/_app.tsx" import { withAuthenticator } from '@aws-amplify/ui-react'; import { Amplify } from 'aws-amplify'; import outputs from '@/amplify_outputs.json'; @@ -84,7 +83,7 @@ import '@aws-amplify/ui-react/styles.css'; import '@/styles/globals.css'; import type { AppProps } from 'next/app'; -// configure the Amplify client library with the configuration generated by `amplify sandbox` +// configure the Amplify client library with the configuration generated by `ampx sandbox` Amplify.configure(outputs); function App({ Component, pageProps }: AppProps) { @@ -150,7 +149,7 @@ aws amplify create-webhook --app-id FRONTEND-APPID --branch-name main --region 1. Now update the build settings for the `backend-app` to include the `curl` command to trigger a frontend build any time there are changes to the backend. -``` yaml +```yaml title="amplify.yml" version: 1 backend: phases: diff --git a/src/pages/[platform]/deploy-and-host/fullstack-branching/share-resources/index.mdx b/src/pages/[platform]/deploy-and-host/fullstack-branching/share-resources/index.mdx index 45d6a6841d2..c6fe255617b 100644 --- a/src/pages/[platform]/deploy-and-host/fullstack-branching/share-resources/index.mdx +++ b/src/pages/[platform]/deploy-and-host/fullstack-branching/share-resources/index.mdx @@ -37,7 +37,7 @@ You can update your app build settings to share resources across branches. From ![The build specification YAML file on the Build settings page in Amplify console.](/images/gen2/fullstack-branching/build-settings.png) -Update the build settings for the `backend` phase to run `npx amplify generate config --branch dev app-id $AWS_APP_ID` to generate the `amplify_outputs.json` file for all branches other than `main` or `dev`. After this update, any new deployed branches will not deploy backend resources as part of the build and instead will use the deployed backend resources from the `dev` branch. +Update the build settings for the `backend` phase to run `npx ampx generate outputs --branch dev app-id $AWS_APP_ID` to generate the `amplify_outputs.json` file for all branches other than `main` or `dev`. After this update, any new deployed branches will not deploy backend resources as part of the build and instead will use the deployed backend resources from the `dev` branch. ```yaml title="amplify.yml" version: 1 diff --git a/src/pages/[platform]/deploy-and-host/sandbox-environments/features/index.mdx b/src/pages/[platform]/deploy-and-host/sandbox-environments/features/index.mdx index 1fae0711111..236e28ce044 100644 --- a/src/pages/[platform]/deploy-and-host/sandbox-environments/features/index.mdx +++ b/src/pages/[platform]/deploy-and-host/sandbox-environments/features/index.mdx @@ -219,12 +219,12 @@ Alternatively, if you want to generate the config for a branch environment to te For Web and React Native, generating the config with the default format and output directory. ```bash title="Terminal" showLineNumbers={false} -npx ampx generate config --app-id --branch main +npx ampx generate outputs --app-id --branch main ``` ```bash title="Terminal" showLineNumbers={false} -npx ampx generate config --app-id --branch main --format dart --out-dir lib +npx ampx generate outputs --app-id --branch main --format dart --out-dir lib ``` @@ -240,7 +240,7 @@ npx ampx generate outputs --app-id --branch main --out-dir app/src/main ```bash title="Terminal" showLineNumbers={false} -npx ampx generate config --app-id --format json-mobile +npx ampx generate outputs --app-id --format json-mobile ``` Once the sandbox environment is running, it will generate the backend outputs file for your frontend application. However, Xcode won't be able to recognize them. For recognizing the files, you need to drag and drop the generated files to your project. diff --git a/src/pages/[platform]/reference/amplify_outputs/index.mdx b/src/pages/[platform]/reference/amplify_outputs/index.mdx index aaf518698f9..1719e0dd0d3 100644 --- a/src/pages/[platform]/reference/amplify_outputs/index.mdx +++ b/src/pages/[platform]/reference/amplify_outputs/index.mdx @@ -31,7 +31,7 @@ export async function getStaticProps() { In Amplify Gen 2, the CLI will generate an `amplify_outputs.json` file with your backend's outputs such as your Data endpoint and Auth metadata. This file -- also known as the "client configuration file" -- is used to configure the client libraries in order to interact with your backend resources. Locally, this file is created while using `ampx sandbox`. In Amplify's CI/CD, this is created automatically for you based on the current Amplify app ID and git branch. -You can also manually create this file for a specified Amplify app ID and branch, or an AWS CloudFormation stack name with [`ampx generate config`](/[platform]/reference/cli-commands#npx-ampx-generate-config). +You can also manually create this file for a specified Amplify app ID and branch, or an AWS CloudFormation stack name with [`ampx generate outputs`](/[platform]/reference/cli-commands#npx-ampx-generate-outputs). {/* @TODO full type/interface to reference */} From 7f3cf3dccb019057c800157922ada9601ee541aa Mon Sep 17 00:00:00 2001 From: josef Date: Thu, 2 May 2024 12:23:37 -0700 Subject: [PATCH 16/17] amplifyconfiguration.json -> amplify_outputs.json (#7438) --- .../analytics/existing-resources/index.mdx | 4 ++-- .../analytics/record-events/index.mdx | 8 ++++---- .../analytics/set-up-analytics/index.mdx | 8 ++++---- .../geo/amazon-location-sdk/index.mdx | 4 ++-- .../geo/existing-resources/index.mdx | 10 +++++----- .../add-aws-services/geo/geofences/index.mdx | 12 ++++++------ .../geo/google-migration/index.mdx | 8 ++++---- .../add-aws-services/geo/maps/index.mdx | 10 +++++----- .../add-aws-services/geo/set-up-geo/index.mdx | 8 ++++---- .../integrate-application/index.mdx | 8 ++++---- .../set-up-in-app-messaging/index.mdx | 8 ++++---- .../interactions/set-up-interactions/index.mdx | 4 ++-- .../logging/set-up-logging/index.mdx | 4 ++-- .../rest-api/customize-authz/index.mdx | 14 +++++++------- .../rest-api/existing-resources/index.mdx | 6 +++--- .../rest-api/set-up-rest-api/index.mdx | 12 ++++++------ .../build-a-backend/auth/set-up-auth/index.mdx | 2 +- .../nuxtjs-server-runtime/index.mdx | 12 ++++++------ .../build-a-backend/data/connect-to-API/index.mdx | 4 ++-- .../connect-amazon-rekognition/index.mdx | 4 ++-- .../connect-amazon-translate/index.mdx | 4 ++-- .../connect-bedrock/index.mdx | 4 ++-- .../build-a-backend/data/set-up-data/index.mdx | 8 ++++---- .../build-a-backend/data/subscribe-data/index.mdx | 2 +- .../storage/set-up-storage/index.mdx | 2 +- .../[platform]/build-ui/formbuilder/index.mdx | 4 ++-- .../cross-account-deployments/index.mdx | 4 ++-- .../fullstack-branching/custom-pipelines/index.mdx | 2 +- .../fullstack-branching/pr-previews/index.mdx | 2 +- .../configuration/amplify-compatibility/index.mdx | 2 +- src/pages/[platform]/start/quickstart/index.mdx | 14 +++++++------- .../nextjs-app-router-client-components/index.mdx | 2 +- .../start/quickstart/nextjs-pages-router/index.mdx | 2 +- 33 files changed, 101 insertions(+), 101 deletions(-) diff --git a/src/pages/[platform]/build-a-backend/add-aws-services/analytics/existing-resources/index.mdx b/src/pages/[platform]/build-a-backend/add-aws-services/analytics/existing-resources/index.mdx index 9bd6f377cc9..2d38978a8c1 100644 --- a/src/pages/[platform]/build-a-backend/add-aws-services/analytics/existing-resources/index.mdx +++ b/src/pages/[platform]/build-a-backend/add-aws-services/analytics/existing-resources/index.mdx @@ -114,7 +114,7 @@ Note that before you can add an AWS resource to your application, the applicatio -Existing Amazon Pinpoint resources can be used with the Amplify Libraries by referencing your **Application ID** and **Region** in your `amplifyconfiguration.json` file. +Existing Amazon Pinpoint resources can be used with the Amplify Libraries by referencing your **Application ID** and **Region** in your `amplify_outputs.json` file. ```json { @@ -139,7 +139,7 @@ Note that before you can add an AWS resource to your application, the applicatio -Existing Amazon Pinpoint resources can be used with the Amplify Libraries by referencing your **Application ID** and **Region** in your `amplifyconfiguration.json` file. +Existing Amazon Pinpoint resources can be used with the Amplify Libraries by referencing your **Application ID** and **Region** in your `amplify_outputs.json` file. ```json { diff --git a/src/pages/[platform]/build-a-backend/add-aws-services/analytics/record-events/index.mdx b/src/pages/[platform]/build-a-backend/add-aws-services/analytics/record-events/index.mdx index 6986ee9884b..770cf8e3e5c 100644 --- a/src/pages/[platform]/build-a-backend/add-aws-services/analytics/record-events/index.mdx +++ b/src/pages/[platform]/build-a-backend/add-aws-services/analytics/record-events/index.mdx @@ -92,7 +92,7 @@ However, it can take upwards of 30 minutes for the event to display in the Filte ## Flush events -Events have a default configuration to flush out to the network every 30 seconds. If you would like to change this, update `amplifyconfiguration.json` with the value in milliseconds you would like for `autoFlushEventsInterval`. This configuration will flush events every 10 seconds: +Events have a default configuration to flush out to the network every 30 seconds. If you would like to change this, update `amplify_outputs.json` with the value in milliseconds you would like for `autoFlushEventsInterval`. This configuration will flush events every 10 seconds: ```json { @@ -157,7 +157,7 @@ You can report authentication events by doing either of the following: - Managing user sign-up and sign-in with Amazon Cognito user pools. - Cognito user pools are user directories that make it easier to add sign-up and sign-in to your app. As users authenticate with your app, Cognito reports authentication events to Pinpoint. For more information, see [Using Amazon Pinpoint Analytics with Amazon Cognito User Pools](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-pinpoint-integration.html) in the _Amazon Cognito Developer Guide_. Also update **amplifyconfiguration.json** by adding the `PinpointAppId` key under `CognitoUserPool`. + Cognito user pools are user directories that make it easier to add sign-up and sign-in to your app. As users authenticate with your app, Cognito reports authentication events to Pinpoint. For more information, see [Using Amazon Pinpoint Analytics with Amazon Cognito User Pools](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-pinpoint-integration.html) in the _Amazon Cognito Developer Guide_. Also update **amplify_outputs.json** by adding the `PinpointAppId` key under `CognitoUserPool`. ```json "CognitoUserPool": { @@ -416,7 +416,7 @@ However, it can take upwards of 30 minutes for the event to display in the Filte By default, events are automatically flushed out to the network every 60 seconds. -If you would like to change this, update `amplifyconfiguration.json` and set the value you would prefer under `autoFlushEventsInterval`, expressed in seconds: +If you would like to change this, update `amplify_outputs.json` and set the value you would prefer under `autoFlushEventsInterval`, expressed in seconds: ```json { @@ -463,7 +463,7 @@ You can report authentication events by doing either of the following: - Managing user sign-up and sign-in with Amazon Cognito user pools. - Cognito user pools are user directories that make it easier to add sign-up and sign-in to your app. As users authenticate with your app, Cognito reports authentication events to Pinpoint. For more information, see [Using Amazon Pinpoint Analytics with Amazon Cognito User Pools](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-pinpoint-integration.html) in the _Amazon Cognito Developer Guide_. Also update **amplifyconfiguration.json** by adding the `PinpointAppId` key under `CognitoUserPool`. + Cognito user pools are user directories that make it easier to add sign-up and sign-in to your app. As users authenticate with your app, Cognito reports authentication events to Pinpoint. For more information, see [Using Amazon Pinpoint Analytics with Amazon Cognito User Pools](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-pinpoint-integration.html) in the _Amazon Cognito Developer Guide_. Also update **amplify_outputs.json** by adding the `PinpointAppId` key under `CognitoUserPool`. ```json "CognitoUserPool": { diff --git a/src/pages/[platform]/build-a-backend/add-aws-services/analytics/set-up-analytics/index.mdx b/src/pages/[platform]/build-a-backend/add-aws-services/analytics/set-up-analytics/index.mdx index 694f336806f..f4ff0a66bae 100644 --- a/src/pages/[platform]/build-a-backend/add-aws-services/analytics/set-up-analytics/index.mdx +++ b/src/pages/[platform]/build-a-backend/add-aws-services/analytics/set-up-analytics/index.mdx @@ -186,7 +186,7 @@ Import and load the configuration file in your app. It's recommended you add the ```js title="src/index.js" import { Amplify } from 'aws-amplify'; import { record } from 'aws-amplify/analytics'; -import amplifyconfig from '../amplifyconfiguration.json'; +import outputs from '../amplify_outputs.json'; Amplify.configure({ ...Amplify.getConfig(), @@ -199,7 +199,7 @@ Amplify.configure({ ```js title="pages/_app.tsx" import { Amplify } from 'aws-amplify'; import { record } from 'aws-amplify/analytics'; -import amplifyconfig from '@/amplifyconfiguration.json'; +import outputs from '@/amplify_outputs.json'; Amplify.configure({ ...Amplify.getConfig(), @@ -323,7 +323,7 @@ Future _configureAmplify() async { // Once Plugins are added, configure Amplify // Note: Amplify can only be configured once. try { - await Amplify.configure(amplifyconfig); + await Amplify.configure(outputs); } on AmplifyAlreadyConfiguredException { safePrint( 'Tried to reconfigure Amplify; this can occur when your app restarts on Android.', @@ -351,7 +351,7 @@ Future _configureAmplify() async { // Once Plugins are added, configure Amplify // Note: Amplify can only be configured once. try { - await Amplify.configure(amplifyconfig); + await Amplify.configure(outputs); } on AmplifyAlreadyConfiguredException { safePrint( 'Tried to reconfigure Amplify; this can occur when your app restarts on Android.', diff --git a/src/pages/[platform]/build-a-backend/add-aws-services/geo/amazon-location-sdk/index.mdx b/src/pages/[platform]/build-a-backend/add-aws-services/geo/amazon-location-sdk/index.mdx index 0edc958c4e2..2102dae200c 100644 --- a/src/pages/[platform]/build-a-backend/add-aws-services/geo/amazon-location-sdk/index.mdx +++ b/src/pages/[platform]/build-a-backend/add-aws-services/geo/amazon-location-sdk/index.mdx @@ -63,8 +63,8 @@ import { LocationClient, AssociateTrackerConsumerCommand } from '@aws-sdk/client-location'; -import amplifyconfig from '../amplifyconfiguration.json'; -Amplify.configure(amplifyconfig); +import outputs from '../amplify_outputs.json'; +Amplify.configure(outputs); const createClient = async () => { const session = await fetchAuthSession(); diff --git a/src/pages/[platform]/build-a-backend/add-aws-services/geo/existing-resources/index.mdx b/src/pages/[platform]/build-a-backend/add-aws-services/geo/existing-resources/index.mdx index 069b8b3ef5e..e2abf809405 100644 --- a/src/pages/[platform]/build-a-backend/add-aws-services/geo/existing-resources/index.mdx +++ b/src/pages/[platform]/build-a-backend/add-aws-services/geo/existing-resources/index.mdx @@ -80,13 +80,13 @@ There are two roles created by Cognito: an `Auth_Role` that grants signed-in-use ## In your application -You can first import and configure the generated `amplifyconfiguration.json`. You can then manually configure Amplify Geo like this: +You can first import and configure the generated `amplify_outputs.json`. You can then manually configure Amplify Geo like this: ```js import { Amplify } from 'aws-amplify'; -import amplifyconfig from '../amplifyconfiguration.json'; +import outputs from '../amplify_outputs.json'; -Amplify.configure(amplifyconfig); +Amplify.configure(outputs); Amplify.configure({ ...Amplify.getConfig(), Geo: { @@ -121,7 +121,7 @@ Now you can proceed to [displaying a map](/[platform]/build-a-backend/add-aws-se ## In your app configuration -Amplify Geo is dependent on your Amplify Auth category. If it is not already configured, then you will have to manually configure it as well. In order to manually configure Amplify Geo category, you must edit `amplifyconfiguration.json` in your project's `src/main/res/raw` directory with your information from existing Amazon Cognito and Amazon Location Service resources. +Amplify Geo is dependent on your Amplify Auth category. If it is not already configured, then you will have to manually configure it as well. In order to manually configure Amplify Geo category, you must edit `amplify_outputs.json` in your project's `src/main/res/raw` directory with your information from existing Amazon Cognito and Amazon Location Service resources. ```json { @@ -177,7 +177,7 @@ Now you can proceed to [displaying a map](/[platform]/build-a-backend/add-aws-se Amplify Geo is dependent on your Amplify Auth category. If it is not already configured, then you will need to [configure it](/[platform]/build-a-backend/auth/set-up-auth/) as well. -Existing Amazon Location Service resources can be used with the Amplify Libraries by adding information about the resources to your `amplifyconfiguration.json` file. +Existing Amazon Location Service resources can be used with the Amplify Libraries by adding information about the resources to your `amplify_outputs.json` file. ```json { diff --git a/src/pages/[platform]/build-a-backend/add-aws-services/geo/geofences/index.mdx b/src/pages/[platform]/build-a-backend/add-aws-services/geo/geofences/index.mdx index d0ed9ee4de3..0a170a90b08 100644 --- a/src/pages/[platform]/build-a-backend/add-aws-services/geo/geofences/index.mdx +++ b/src/pages/[platform]/build-a-backend/add-aws-services/geo/geofences/index.mdx @@ -118,8 +118,8 @@ import { AmplifyGeofenceControl } from 'maplibre-gl-js-amplify'; import '@aws-amplify/ui-react/styles.css'; import '@aws-amplify/ui-react-geo/styles.css'; import 'maplibre-gl-js-amplify/dist/public/amplify-ctrl-geofence.css'; -import amplifyconfig from '../amplifyconfiguration.json'; -Amplify.configure(amplifyconfig); +import outputs from '../amplify_outputs.json'; +Amplify.configure(outputs); function Geofence() { useControl(() => new AmplifyGeofenceControl()); @@ -181,7 +181,7 @@ Geo.saveGeofences(geofences, options) => Promise; - `geofences` - can be a single geofence object, or an array of geofence objects to save to a collection. - `options` - optional options object for saving geofences - `collectionName` - the name of the collection to save geofences to. - - Defaults to the default collection listed in your `amplifyconfiguration.json` file after provisioning a geofence collection resource. + - Defaults to the default collection listed in your `amplify_outputs.json` file after provisioning a geofence collection resource. Geofence objects must have the following properties: @@ -260,7 +260,7 @@ Geo.getGeofence(geofenceId, options) => Promise; - `geofenceId` - the `id` of the geofence to get. - `options` - optional options object for getting a geofence - `collectionName` - the name of the collection to get geofence from. - - Defaults to the default collection listed in your `amplifyconfiguration.json` file after provisioning a geofence collection resource. + - Defaults to the default collection listed in your `amplify_outputs.json` file after provisioning a geofence collection resource. #### Return @@ -293,7 +293,7 @@ Geo.listGeofences(options) => Promise; - `nextToken` - the pagination token for the next page of geofences. - if no token is given, it will return the first page of geofences. - `collectionName` - the name of the collection to save geofences to. - - Defaults to the default collection listed in your `amplifyconfiguration.json` file after provisioning a geofence collection resource. + - Defaults to the default collection listed in your `amplify_outputs.json` file after provisioning a geofence collection resource. #### Return @@ -329,7 +329,7 @@ Geo.deleteGeofences(geofenceIds, options) => Promise; - `geofenceIds` - a single geofenceId or array of geofenceIds to delete - `options` - optional options object for saving geofences - `collectionName` - the name of the collection to save geofences to. - - Defaults to the default collection listed in your `amplifyconfiguration.json` file after provisioning a geofence collection resource. + - Defaults to the default collection listed in your `amplify_outputs.json` file after provisioning a geofence collection resource. #### Return diff --git a/src/pages/[platform]/build-a-backend/add-aws-services/geo/google-migration/index.mdx b/src/pages/[platform]/build-a-backend/add-aws-services/geo/google-migration/index.mdx index 06cfcbe41c1..ed666d9d7ab 100644 --- a/src/pages/[platform]/build-a-backend/add-aws-services/geo/google-migration/index.mdx +++ b/src/pages/[platform]/build-a-backend/add-aws-services/geo/google-migration/index.mdx @@ -46,7 +46,7 @@ A key difference to notice between using Amplify Geo and Google Maps is with Goo ### Authorization -When using Google Maps Platform or other similar services like Mapbox you will first be prompted to go to the Google Cloud Console to set up APIs and create an API key where you will then use the API key when requesting the Google Maps JS API. With Amplify Geo you will instead setup Amplify Auth and the `MapView` component will read the auth configuration from the `amplifyconfiguration.json` file. Behind the scenes Amplify Auth uses Amazon Cognito to set up client credentials with access to Location Service and Geo will use those credentials when making any location related API calls. More information on setting Amplify Auth and Geo can be found below in the `Setting Up Amplify` section. +When using Google Maps Platform or other similar services like Mapbox you will first be prompted to go to the Google Cloud Console to set up APIs and create an API key where you will then use the API key when requesting the Google Maps JS API. With Amplify Geo you will instead setup Amplify Auth and the `MapView` component will read the auth configuration from the `amplify_outputs.json` file. Behind the scenes Amplify Auth uses Amazon Cognito to set up client credentials with access to Location Service and Geo will use those credentials when making any location related API calls. More information on setting Amplify Auth and Geo can be found below in the `Setting Up Amplify` section. ## Create a webpage @@ -102,10 +102,10 @@ When using Google Maps Platform or other similar services like Mapbox you will f
@@ -119,7 +119,7 @@ This code imports the MapLibre GL JS library and CSS, one of the popular options ### Setting up Amplify 1. You will need to setup a [Geo Map resources](/[platform]/build-a-backend/add-aws-services/geo/set-up-geo/). Follow instructions for creating a map. -1. Once the workflow has completed you should have an `amplifyconfiguration.json` file in the same directory as your `index.html` file. +1. Once the workflow has completed you should have an `amplify_outputs.json` file in the same directory as your `index.html` file. 1. Save your `index.html` file. ## Display a map diff --git a/src/pages/[platform]/build-a-backend/add-aws-services/geo/maps/index.mdx b/src/pages/[platform]/build-a-backend/add-aws-services/geo/maps/index.mdx index 55b520bdb49..5c27c99058e 100644 --- a/src/pages/[platform]/build-a-backend/add-aws-services/geo/maps/index.mdx +++ b/src/pages/[platform]/build-a-backend/add-aws-services/geo/maps/index.mdx @@ -243,14 +243,14 @@ To display a map on your html website, add the following scripts to your html we ``` -Next, add a div element with id `map` anywhere in your webpage where you want to render the map. Include the following code snippet to configure Amplify (update the `amplifyconfiguration.json` file path accordingly) and instantiate the map. +Next, add a div element with id `map` anywhere in your webpage where you want to render the map. Include the following code snippet to configure Amplify (update the `amplify_outputs.json` file path accordingly) and instantiate the map. ```html + + +``` + +Add the following to `style.css` file: + +{/* cSpell:disable */} + +```css title="style.css" +body { + margin: 0; + background: linear-gradient(180deg, rgb(117, 81, 194), rgb(255, 255, 255)); + display: flex; + font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; + height: 100vh; + width: 100vw; + justify-content: center; + align-items: center; +} + +main { + display: flex; + flex-direction: column; + align-items: stretch; +} + +button { + border-radius: 8px; + border: 1px solid transparent; + padding: 0.6em 1.2em; + font-size: 1em; + font-weight: 500; + font-family: inherit; + background-color: #1a1a1a; + cursor: pointer; + transition: border-color 0.25s; + color: white; +} +button:hover { + border-color: #646cff; +} +button:focus, +button:focus-visible { + outline: 4px auto -webkit-focus-ring-color; +} + +ul { + padding-inline-start: 0; + margin-block-start: 0; + margin-block-end: 0; + list-style-type: none; + display: flex; + flex-direction: column; + margin: 8px 0; + border: 1px solid black; + gap: 1px; + background-color: black; + border-radius: 8px; + overflow: auto; +} + +li { + background-color: white; + padding: 8px; +} + +li:hover { + background: #dadbf9; +} + +a { + font-weight: 800; + text-decoration: none; +} +``` +{/* cSpell:enable */} + +In `main.js` remove the boilerplate code and leave it empty. Then refresh the browser to see the changes. + +## Create Backend + +The easiest way to get started with AWS Amplify is through npm with `create-amplify` command. You can run it from your base project directory. + +```bash title="Terminal" showLineNumbers={false} +npm create amplify@latest +? Where should we create your project? (.) # press enter +``` + +Running this command will scaffold Amplify backend files in your current project with the following files added: + +```text +β”œβ”€β”€ amplify/ +β”‚ β”œβ”€β”€ auth/ +β”‚ β”‚ └── resource.ts +β”‚ β”œβ”€β”€ data/ +β”‚ β”‚ └── resource.ts +β”‚ β”œβ”€β”€ backend.ts +β”‚ └── package.json +β”œβ”€β”€ node_modules/ +β”œβ”€β”€ index.html +β”œβ”€β”€ style.css +β”œβ”€β”€ .gitignore +β”œβ”€β”€ package-lock.json +β”œβ”€β”€ package.json +└── tsconfig.json +``` + +### Set up local AWS credentials + +To make backend updates, we are going to require AWS credentials to deploy backend updates from our local machine. + +**Skip ahead to step 8**, if you already have an AWS profile with credentials on your local machine, and your AWS profile has the `AmplifyBackendDeployFullAccess` permission policy. + +Otherwise, **[set up local AWS credentials](/[platform]/start/account-setup/)** that grant Amplify permissions to deploy backend updates from your local machine. + +### Deploy cloud sandbox + +To deploy your backend use Amplify's per-developer cloud sandbox. This feature provides a separate backend environment for every developer on a team, ideal for local development and testing. To run your application with a sandbox environment, you can run the following command: + +```bash title="Terminal" showLineNumbers={false} +npx ampx sandbox +``` + +Once the sandbox environment is deployed, it will create a GraphQL API, database, and auth service. All the deployed resources will be available in the `amplify_outputs.json`. However, Xcode won't be able to recognize them. For recognizing the files, you need to drag and drop the generated files to your project. + +## Connect frontend to backend + +The initial scaffolding already has a pre-configured data backend defined in the `amplify/data/resource.ts` file. The default example will create a Todo model with `content` field. Update your main.js file to create new to-do items. + +```typescript title="src/main.ts" +import { generateClient } from "aws-amplify/data"; +import type { Schema } from "../amplify/data/resource"; +import './style.css'; +import { Amplify } from 'aws-amplify'; +import outputs from '../amplify_outputs.json'; + +Amplify.configure(outputs); + + +const client = generateClient(); + +document.addEventListener("DOMContentLoaded", function () { + const todos: Array = []; + const todoList = document.getElementById("todoList") as HTMLUListElement; + const addTodoButton = document.getElementById("addTodo") as HTMLButtonElement; + + addTodoButton.addEventListener("click", createTodo); + + function updateUI() { + todoList.innerHTML = ''; + todos.forEach(todo => { + const li = document.createElement('li'); + li.textContent = todo.content ?? ''; + todoList.appendChild(li); + }); + } + + function createTodo() { + console.log('createTodo'); + const content = window.prompt("Todo content"); + if (content) { + client.models.Todo.create({ content }).then(response => { + if (response.data && !response.errors) { + todos.push(response.data); + updateUI(); + } else { + console.error('Error creating todo:', response.errors); + alert('Failed to create todo.'); + } + }).catch(error => { + console.error('Network or other error:', error); + alert('Failed to create todo due to a network or other error.'); + }); + } + } + + + client.models.Todo.observeQuery().subscribe({ + next: (data) => { + todos.splice(0, todos.length, ...data.items); + updateUI(); + } + }); +}); +``` + +
@@ -112,7 +352,7 @@ Let's take a tour of the project structure in this starter repository by opening In the Amplify Console, navigate to the Data manager to see the data entered in your database. -TK IMAGE +![Amplify data manager user interface showing the ToDo model with two to do instances](/images/gen2/getting-started/data-manager.png) ## Make frontend updates @@ -449,7 +689,7 @@ Let's take a tour of the project structure in this starter repository by opening In the Amplify Console, navigate to the Data manager to see the data entered in your database. -TK IMAGE +![Amplify data manager user interface showing the ToDo model with two to do instances](/images/gen2/getting-started/data-manager.png) ## Make frontend updates @@ -782,7 +1022,7 @@ Let's take a tour of the project structure in this starter repository by opening In the Amplify Console, navigate to the Data manager to see the data entered in your database. -TK IMAGE +![Amplify data manager user interface showing the ToDo model with two to do instances](/images/gen2/getting-started/data-manager.png) ## Make frontend updates @@ -1074,7 +1314,7 @@ flutter create my_amplify_app The easiest way to get started with AWS Amplify is through npm with `create-amplify` command. You can run it from your base project directory. ```bash title="Terminal" showLineNumbers={false} -npm create amplify@beta +npm create amplify@latest ? Where should we create your project? (.) # press enter ``` @@ -2698,15 +2938,7 @@ For publishing the changes to cloud, you need to create a remote git repository. - + ## πŸ₯³ Success