Add Analytics to our Bakery Web App.

Add Analytics to our Bakery Web App.

Let add Analytics to our Bakery Front end.

·

4 min read

Remember, our aim is not to have yet another web app, but to track user activity and demographics, convince them to buy and capture their details so that we can send them promotions.

We want to

  1. Send discount codes to subscribers.

  2. Track page views of each bakery item.

  3. Entice them to signup, and periodically send them discount codes (once a month).

How to convert from a Stranger to a Customer.

If you remember in the last session we created a graphql schema

It has the email, name and contact number as the fields. The AppSync also generated GraphQL queries and mutations for us.

When a guest user adds the email ID and subscriber, we'll insert it into Subscriber table, and also if it's successful, We'll update the endpoint in pinpoint.

Below is the dummy Subscriber Journey we would like to implement:

Now, Let's understand a few terminologies and APIs related to pinpoint & Analytics.

TerminologyMeaning
Endpointemail, phone no, device ID
ChannelEMAIL
Segmentgroup of endpoints sharing certain attributes.
Campaign
Journeys
Events
Funnel

We created below email template to send a welcome email with a 25% discount code.

If customers do not open the email within 24 hours, we'll send an email with 50% off.

Configure Amplify on Frontend

There is aws-export.js which has all configurations needed for front end, we need to configure the Frontend application to use it.

npm install @aws-amplify/core aws-amplify

In _app.js add the below code.

import Amplify, { Hub } from "@aws-amplify/core";
import awsconfig from "../aws-exports";
Amplify.configure(awsconfig);

Add pageViews to each product.

Let's create a utility function to auto-track the pageViews, here parameters are the page link and the timeout, suppose we want to record a page view only after the user spends 20 seconds on that page, we can have a different timeout for different

analyticsRecord.js

import { Analytics } from '@aws-amplify/analytics'

export async function recordPageView(pageLink, timeout) {
  setTimeout(() => {
    console.log('recordPageView page path   : ', pageLink)
    console.log('recordPageView page timeout   : ', timeout)

    Analytics.autoTrack('pageView', {
      // REQUIRED, turn on/off the auto tracking
      enable: true,
      // OPTIONAL, the event name, by default is 'pageView'
      eventName: 'pageView',
      attributes: {
        attr: 'attr',
      },
      type: 'multiPageApp',
      provider: 'AWSPinpoint',
      getUrl: () => {
        // the default function
        return pageLink
      },
    })
  }, timeout)
}

Let's add the below code in the pages we want to track the page views for.
1. src\pages\cakes\index.js, src\pages\cakes\[id].js
2. src\pages\bread-n-buns\index.js, src\pages\bread-n-buns\[id].js

window.LOG_LEVEL = 'VERBOSE' is required to see debug logs from AWS Analytics.

  useEffect(() => {
    if (typeof window !== 'undefined') {
      window.LOG_LEVEL = 'VERBOSE'
      let pageURL = window.location.origin + window.location.pathname
      console.log('page path : ', pageURL)
      recordPageView(pageURL, 20000)
    }
  }, [])

e.g. debug log

[DEBUG] 31:21.291 PageViewTracker - initialize pageview tracker with opts Object ConsoleLogger.js?aade:99

[DEBUG] 31:21.292 Hub - Dispatching to analytics with Object ConsoleLogger.js?aade:99 [DEBUG] 31:21.292 AnalyticsClass - on hub capsule analytics Object ConsoleLogger.js?aade:99

[DEBUG] 31:21.292 AWSPinpointProvider - _public record Object ConsoleLogger.js?aade:87

[DEBUG] 31:21.293 Credentials - getting credentials ConsoleLogger.js?aade:87 [DEBUG] 31:21.293 Credentials - picking up credentials ConsoleLogger.js?aade:87

[DEBUG] 31:21.293 Credentials - getting new cred promise

If all is fine, you will see active endpoints on pinpoint dashboard.

You can also see pageViews, i.e. bread-n-buns are listed here.

Add Events for subscription and create User Journey.

If you remember, we set email as the primaryKey in GraphQL Schema,

here we add a subscriberHooks.js, It'll

import { API, Auth } from "aws-amplify";

import * as mutations from "@/graphql/mutations";
import * as queries from "@/graphql/queries";

export const hookAddSubscribersNew = async (SubscribersNewToAdd) => {
  console.log(" hookAddSubscribersNew : ", SubscribersNewToAdd);
  try {
    const result = await API.graphql({
      query: mutations.createSubscribersNew,
      variables: {
        input: SubscribersNewToAdd,
      },
    });
    console.log(" hookAddSubscribersNew result: ", result);
    return result?.data?.createSubscribersNew;
  } catch (err) {
    console.log("CATCH ERROR hookAddSubscribersNew result: ", err);
    return null;
  }
};

In the SubscribeHere.jsx file we add below code to subscribe, and update the endpoint with ChannelType EMAIL, and it'll record event : SubscribedToFavouriteBakery

import { hookAddSubscribersNew } from "@/hooks/subscriberHooks";
import { Analytics } from "@aws-amplify/analytics";

const postData = await hookAddSubscribersNew({
        email: email,
        emailCopy: email,
      });

      if (postData) {
        // Update the endpoint
        const updatePoint = await Analytics.updateEndpoint({
          address: email,
          attributes: {
            /*name: name,
            contact: contact,*/
          },
          channelType: "EMAIL",
          optOut: "NONE",
        });
        console.log("Updating the Record, updated EndPoint ", updatePoint);

        // Send Subscribed event
        await Analytics.record({ name: "SubscribedToFavouriteBakery" });
      }
      console.log("Updating the Record ");

Now, you can subscribe to get a discount.

If everything works well, you'll get it message.

Now, you should If you don't open email within 1 hours, you should receive second email. If you open first email, you'll not get second email, below is the subscriber Journey, configured in AWS Pinpoint

Did you find this article valuable?

Support Delighteck Blog by becoming a sponsor. Any amount is appreciated!