Set up Amplify Analytics
Amplify enables you to collect analytics data for your app. In order to use Analytics, you will enable Amazon Kinesis or Amazon Pinpoint using the AWS Cloud Development Kit (AWS CDK). The Analytics category uses Amazon Cognito identity pools to identify users in your app. Cognito allows you to receive data from authenticated, and unauthenticated users in your app.
Set up Analytics backend
Use the AWS CDK to create an analytics resource powered by Amazon Pinpoint.
import { defineBackend } from "@aws-amplify/backend"import { auth } from "./auth/resource";import { data } from "./data/resource";import { Policy, PolicyStatement } from "aws-cdk-lib/aws-iam";import { CfnApp } from "aws-cdk-lib/aws-pinpoint";import { Stack } from "aws-cdk-lib/core";
const backend = defineBackend({ auth, data, // additional resources});
const analyticsStack = backend.createStack("analytics-stack");
// create a Pinpoint appconst pinpoint = new CfnApp(analyticsStack, "Pinpoint", { name: "myPinpointApp",});
// create an IAM policy to allow interacting with Pinpointconst pinpointPolicy = new Policy(analyticsStack, "PinpointPolicy", { policyName: "PinpointPolicy", statements: [ new PolicyStatement({ actions: ["mobiletargeting:UpdateEndpoint", "mobiletargeting:PutEvents"], resources: [pinpoint.attrArn + "/*"], }), ],});
// apply the policy to the authenticated and unauthenticated rolesbackend.auth.resources.authenticatedUserIamRole.attachInlinePolicy(pinpointPolicy);backend.auth.resources.unauthenticatedUserIamRole.attachInlinePolicy(pinpointPolicy);
// patch the custom Pinpoint resource to the expected output configurationbackend.addOutput({ analytics: { amazon_pinpoint: { app_id: pinpoint.ref, aws_region: Stack.of(pinpoint).region, } },});
Install Amplify Libraries
First, install the aws-amplify
library:
npm add aws-amplify
Initialize Amplify Analytics
Import and load the configuration file in your app. It's recommended you add the Amplify configuration step to your app's root entry point.
import { Amplify } from 'aws-amplify';import { record } from 'aws-amplify/analytics';import outputs from '@/amplify_outputs.json';
Amplify.configure({ ...Amplify.getConfig(), Analytics: amplifyconfig.Analytics,});
Next Steps:
Congratulations! Now that you have Analytics' backend provisioned and Analytics library installed. Check out the following links to see Amplify Analytics use cases: