

# Set up a web application to use CloudWatch RUM
<a name="CloudWatch-RUM-get-started"></a>

Use the steps in these sections to set up your web application to begin using CloudWatch RUM to collect performance data from real user sessions.

**Topics**
+ [Authorize your web application to send data to AWS](CloudWatch-RUM-get-started-authorization.md)
+ [Creating a CloudWatch RUM app monitor for a web application](CloudWatch-RUM-get-started-create-app-monitor.md)
+ [Modifying the code snippet to configure the CloudWatch RUM web client (optional)](CloudWatch-RUM-modify-snippet.md)
+ [Inserting the CloudWatch app monitor code snippet into your application](CloudWatch-RUM-get-started-insert-code-snippet.md)
+ [Testing your CloudWatch app monitor setup by generating user events](CloudWatch-RUM-get-started-generate-data.md)

# Authorize your web application to send data to AWS
<a name="CloudWatch-RUM-get-started-authorization"></a>

You have four options to set up data authentication:
+ Use Amazon Cognito and let CloudWatch RUM create a new Amazon Cognito identity pool for the application. This method requires the least effort to set up.

  The identity pool will contain an unauthenticated identity. This allows the CloudWatch RUM web client to send data to CloudWatch RUM without authenticating the user of the application.

  The Amazon Cognito identity pool has an attached IAM role. The Amazon Cognito unauthenticated identity allows the web client to assume the IAM role that is authorized to send data to CloudWatch RUM.
+ Use Amazon Cognito for authentication. If you use this, you can use an existing Amazon Cognito identity pool or create a new one to use with this app monitor. If you use an existing identity pool, you must also modify the IAM role that is attached to the identity pool. Use this option for identity pools that support unauthenticated users. You can use identity pools only from the same Region.
+ Use authentication from an existing identity provider that you have already set up. In this case, you must get credentials from the identity provider and your application must forward these credentials to the RUM web client.

  Use this option for identity pools that support only authenticated users.
+ Use resource-based policies to manage access to your app monitor. This includes the ability to send unauthenticated requests to CloudWatch RUM without AWS credentials. To learn more about resource based policies and RUM, see [Using resource-based policies with CloudWatch RUM](CloudWatch-RUM-resource-policies.md).

The following sections include more details about these options.

## Use an existing Amazon Cognito identity pool
<a name="CloudWatch-RUM-get-started-authorization-existingcognito"></a>

If you choose to use a Amazon Cognito identity pool, you specify the identity pool when you add the application to CloudWatch RUM. The pool must support enabling access to unauthenticated identities. You can use identity pools only from the same Region.

You also must add the following permissions to the IAM policy that is attached to the IAM role that is associated with this identity pool.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        { 
            "Effect": "Allow",
            "Action": [
                "rum:PutRumEvents"
            ],
            "Resource": "arn:aws:rum:us-east-1:123456789012:appmonitor/app monitor name" 
        }
    ]
}
```

------

Amazon Cognito will then send the necessary security token to enable your application to access CloudWatch RUM.

## Third-party provider
<a name="CloudWatch-RUM-get-started-authorization-thirdparty"></a>

If you choose to use private authentication from a third-party provider, you must get credentials from the identity provider and forward them to AWS. The best way to do this is by using a *security token vendor*. You can use any security token vendor, including Amazon Cognito with AWS Security Token Service. For more information about AWS STS, see [Welcome to the AWS Security Token Service API Reference](https://docs.aws.amazon.com/STS/latest/APIReference/welcome.html). 

If you want to use Amazon Cognito as the token vendor in this scenario, you can configure Amazon Cognito to work with an authentication provider. For more information, see [Getting Started with Amazon Cognito Identity Pools (Federated Identities)](https://docs.aws.amazon.com/cognito/latest/developerguide/getting-started-with-identity-pools.html).

After you configure Amazon Cognito to work with your identity provider, you also need to do the following:
+ Create an IAM role with the following permissions. Your application will use this role to access AWS.

------
#### [ JSON ]

****  

  ```
  { 
   "Version":"2012-10-17",		 	 	 
   "Statement": [ 
     { 
       "Effect": "Allow",
       "Action": "rum:PutRumEvents",
       "Resource": "arn:aws:rum:us-east-2:123456789012:appmonitor/AppMonitorName"
     }
   ]
  }
  ```

------
+ Add the following to your application to have it pass the credentials from your provider to CloudWatch RUM. Insert the line so that it runs after a user has signed in to your application and the application has received the credentials to use to access AWS.

  ```
  cwr('setAwsCredentials', {/* Credentials or CredentialProvider */});
  ```

For more information about credential providers in the AWS JavaScript SDK, see [Setting credentials in a web browser](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-browser.html) in the v3 developer guide for SDK for JavaScript, [Setting credentials in a web browser](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials-browser.html) in the v2 developer guide for SDK for JavaScript, , and [@aws-sdk/credential-providers](https://www.npmjs.com/package/@aws-sdk/credential-providers). 

You can also use the SDK for the CloudWatch RUM web client to configure the web client authentication methods. For more information about the web client SDK, see [CloudWatch RUM web client SDK](https://github.com/aws-observability/aws-rum-web). 

# Creating a CloudWatch RUM app monitor for a web application
<a name="CloudWatch-RUM-get-started-create-app-monitor"></a>

To start using CloudWatch RUM with your application, you create an *app monitor*. When the app monitor is created, RUM generates a code snippet for you to paste into your application. The snippet pulls in the RUM client code. The RUM client captures data from your application's user sessions and sends it to RUM.

## To create an app monitor for a web platform
<a name="web-platform-app-monitor"></a>

1. Open the CloudWatch console at [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/).

1. In the navigation pane, choose **Application Signals**, **RUM**.

1. Choose **Add app monitor**.

1. For **App monitor name**, enter a name to be used to identify this app monitor within the CloudWatch RUM console.

1. Select **Web** as the platform.

1. For **Application domain list**, enter the registered domain names where your application has administrative authority. You can also use a wildcard character `*` to allow any sub-domain or top-level domains (for example, \$1.amazon.com, amazon.\$1, \$1.amazon.\$1).

1. For **Configure RUM data collection**, specify whether you want the app monitor to collect each of the following:
   + **Performance telemetry** – Collects information about page load and resource load times
   + **JavaScript errors** – Collects information about unhandled JavaScript errors raised by your application

     You can select **Unminify JavaScript error stack traces** to debug unminified JavaScript errors. To use this feature, upload your source map files to an Amazon S3 bucket or folder and provide the Amazon S3 URI. Once enabled, RUM will use these source maps and enrich JavaScript error events by adding the unminified stack trace. Note that after enabling, this feature only processes new JavaScript error events and cannot be used on previously collected data. For more information, see [Enabling unminification of JavaScript error stack traces](CloudWatch-RUM-JavaScriptStackTraceSourceMaps.md).
   + **HTTP errors** – Collects information about HTTP errors thrown by your application

   Selecting these options provides more information about your application, but also generates more CloudWatch RUM events and thus incurs more charges.

   If you don't select any of these, the app monitor still collects session start events and page IDs so that you can see how many users are using your application, including breakdowns by operating system type and version, browser type and version, device type, and location.

1. Select **Check this option to allow the CloudWatch RUM Web Client to set cookies** if you want to be able to collect user IDs and session IDs from sampled user sessions. The user IDs are randomly generated by RUM. For more information, see [CloudWatch RUM web client cookies (or similar technologies)](CloudWatch-RUM-privacy.md#CloudWatch-RUM-cookies).

1. For **Session samples**, enter the percentage of user sessions that will be used to gather RUM data. The default is 100%. Reducing this number gives you less data, but reduces your charges. For more information about RUM pricing, see [RUM pricing](CloudWatch-RUM.md#RUMpricing).

1. End user data that you collect for CloudWatch RUM is retained for 30 days and then deleted. If you want to keep copies of RUM events in CloudWatch Logs and configure how long to retain these copies, choose **Check this option to store your application telemetry data in your CloudWatch Logs account** under **Data storage**. By default, the CloudWatch Logs log group retains the data for 30 days. You can adjust the retention period in the CloudWatch Logs console.

1. (Optional) Choose to add a resource-based policy to your app monitor to control who can send `PutRumEvents` requests to your app monitor. If you choose **Create public policy**, a resource policy will be attached to your app monitor that enables anyone to send `PutRumEvents` requests to your app monitor. For more information about this method, see [Using resource-based policies with CloudWatch RUM](CloudWatch-RUM-resource-policies.md).

1. If you attached a resource-based policy in the previous step, then you don't need to sign requests to CloudWatch RUM with AWS credentials, and you can skip setting up authorization. Otherwise, for **Authorization**, specify whether to use a new or existing Amazon Cognito identity pool or use a different identity provider. Creating a new identity pool is the simplest option that requires no other setup steps. For more information, see see [Authorize your web application to send data to AWS](CloudWatch-RUM-get-started-authorization.md).

   Creating a new Amazon Cognito identity pool requires administrative permissions. For more information, see [IAM policies to use CloudWatch RUM](CloudWatch-RUM-permissions.md).

1. (Optional) By default, when you add the RUM code snippet to your application, the web client injects the JavaScript tag to monitor usage into the HTML code of all pages of your application. To change this, choose **Configure pages** and then choose either **Include only these pages** or **Exclude these pages**. Then, specify the pages to include or exclude. To specify a page to include or exclude, enter its complete URLs. To specify additional pages, choose **Add URL**.

1. To enable AWS X-Ray tracing of the user sessions that are sampled by the app monitor, choose **Active tracing** and select **Trace my service with AWS X-Ray.**

   If you select this, `XMLHttpRequest` and `fetch` requests made during user sessions sampled by the app monitor are traced. You can then see traces and segments from these user sessions in the RUM dashboard, and the X-Ray trace map and trace details pages. These user sessions will also show up as client pages in [Application Signals](CloudWatch-Application-Monitoring-Sections.md) after you have enabled it for your application.

   By making additional configuration changes to the CloudWatch RUM web client, you can add an X-Ray trace header to HTTP requests to enable end-to-end tracing of user sessions through to downstream AWS managed services. For more information, see [Enabling X-Ray end-to-end tracing](CloudWatch-RUM-modify-snippet.md#CloudWatch-RUM-xraytraceheader).

1. (Optional) To add tags to the app monitor, choose **Tags**, **Add new tag**.

   Then, for **Key**, enter a name for the tag. You can add an optional value for the tag in **Value**. 

   To add another tag, choose **Add new tag** again.

   For more information, see [Tagging AWS Resources](https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html).

1. Choose **Add app monitor**.

1. In the **Sample code** section, you can copy the code snippet to use to add to your application. We recommend that you choose **JavaScript** or **TypeScript** and use NPM to install the CloudWatch RUM web client as a JavaScript module.

   Alternatively, you can choose **HTML** to use a content delivery network (CDN) to install the CloudWatch RUM web client. The disadvantage of using a CDN is that the web client is often blocked by ad blockers.

1. Choose **Copy** or **Download**, and then choose **Done**.

# Modifying the code snippet to configure the CloudWatch RUM web client (optional)
<a name="CloudWatch-RUM-modify-snippet"></a>

You can modify the code snippet before inserting it into your application, to activate or deactivate several options. For more information, see the [ CloudWatch RUM web client documentation.](https://github.com/aws-observability/aws-rum-web/blob/main/docs/cdn_installation.md)

There are four configuration options that you should definitely be aware of, as discussed in these sections.

## Preventing the collection of resource URLs that might contain personal information
<a name="CloudWatch-RUM-resourceURL"></a>

By default, the CloudWatch RUM web client is configured to record the URLs of resources downloaded by the application. These resources include HTML files, images, CSS files, JavaScript files, and so on. For some applications, URLs may contain personally identifiable information (PII).

If this is the case for your application, we strongly recommend that you disable the collection of resource URLs by setting `recordResourceUrl: false` in the code snippet configuration, before inserting it into your application.

## Manually recording page views
<a name="CloudWatch-RUM-pageload"></a>

By default, the web client records page views when the page first loads and when the browser's history API is called. The default page ID is `window.location.pathname`. However, in some cases you might want to override this behavior and instrument the application to record page views programmatically. Doing so gives you control over the page ID and when it is recorded. For example, consider a web application that has a URI with a variable identifier, such as `/entity/123` or `/entity/456`. By default, CloudWatch RUM generates a page view event for each URI with a distinct page ID matching the pathname, but you might want to group them by the same page ID instead. To accomplish this, disable the web client's page view automation by using the `disableAutoPageView` configuration, and use the `recordPageView` command to set the desired page ID. For more information, see [ Application-specific Configurations](https://github.com/aws-observability/aws-rum-web/blob/main/docs/configuration.md) on GitHub.

**Embedded script example:**

```
cwr('recordPageView', { pageId: 'entityPageId' });
```

**JavaScript module example:**

```
awsRum.recordPageView({ pageId: 'entityPageId' });
```

## Enabling X-Ray end-to-end tracing
<a name="CloudWatch-RUM-xraytraceheader"></a>

When you create the app monitor, selecting **Trace my service with AWS X-Ray** enables the tracing of `XMLHttpRequest` and `fetch` requests made during user sessions that are sampled by the app monitor. You can then see traces from these HTTP requests in the CloudWatch RUM dashboard, and the X-Ray Trace Map and Trace details pages.

By default, these client-side traces are not connected to downstream server-side traces. To connect client-side traces to server-side traces and enable end-to-end tracing, set the `addXRayTraceIdHeader` option to `true` in the web client. This causes the CloudWatch RUM web client to add an X-Ray trace header to HTTP requests.

The following code block shows an example of adding client-side traces. Some configuration options are omitted from this sample for readibility.

```
<script>
    (function(n,i,v,r,s,c,u,x,z){...})(
        'cwr',
        '00000000-0000-0000-0000-000000000000',
        '1.0.0',
        'us-west-2',
        'https://client.rum.us-east-1.amazonaws.com/1.0.2/cwr.js',
        {
            enableXRay: true,
            telemetries: [ 
                'errors', 
                'performance',
                [ 'http', { addXRayTraceIdHeader: true } ]
            ]
        }
    );
</script>
```

**Warning**  
Configuring the CloudWatch RUM web client to add an X-Ray trace header to HTTP requests can cause cross-origin resource sharing (CORS) to fail or invalidate the request's signature if the request is signed with SigV4. For more information, see the [ CloudWatch RUM web client documentation](https://github.com/aws-observability/aws-rum-web/blob/main/docs/cdn_installation.md). We strongly recommend that you test your application before adding a client-side X-Ray trace header in a production environment.

For more information, see the [ CloudWatch RUM web client documentation](https://github.com/aws-observability/aws-rum-web/blob/main/docs/cdn_installation.md#http)

## Sending unsigned requests to CloudWatch RUM
<a name="CloudWatch-RUM-unsigned"></a>

By default, the RUM web client signs all requests sent to RUM. If you set `signing:false` in the client configuration, requests will be unsigned when they are sent to CloudWatch RUM. Data will be ingested to RUM only if there is a public resource based policy attached to the app monitor. For more information, see [Using resource-based policies with CloudWatch RUM](CloudWatch-RUM-resource-policies.md).

# Inserting the CloudWatch app monitor code snippet into your application
<a name="CloudWatch-RUM-get-started-insert-code-snippet"></a>

Next, you insert the code snippet that you created in the previous section into your application.

**Warning**  
The web client, downloaded and configured by the code snippet, uses cookies (or similar technologies) to help you collect end user data. Before you insert the code snippet, see [Filtering by metadata attributes in the consoleData protection and data privacy with CloudWatch RUM](CloudWatch-RUM-privacy.md).

If you don't have the code snippet that was previously generated, you can find it by following the directions in [How do I find a code snippet that I've already generated?](CloudWatch-RUM-find-code-snippet.md).

**To insert the CloudWatch RUM code snippet into your application**

1. Insert the code snippet that you copied or downloaded in the previous section inside the `<head>` element of your application. Insert it before the `<body>` element or any other `<script>` tags.

   The following is an example of a generated code snippet:

   ```
   <script>
   (function (n, i, v, r, s, c, x, z) {
       x = window.AwsRumClient = {q: [], n: n, i: i, v: v, r: r, c: c};
       window[n] = function (c, p) {
           x.q.push({c: c, p: p});
       };
       z = document.createElement('script');
       z.async = true;
       z.src = s;
       document.head.insertBefore(z, document.getElementsByTagName('script')[0]);
   })('cwr',
       '194a1c89-87d8-41a3-9d1b-5c5cd3dafbd0',
       '1.0.0',
       'us-east-2',
       'https://client.rum.us-east-1.amazonaws.com/1.0.2/cwr.js',
       {
           sessionSampleRate: 1,
           identityPoolId: "us-east-2:c90ef0ac-e3b8-4d1a-b313-7e73cfd21443",
           endpoint: "https://dataplane.rum.us-east-2.amazonaws.com",
           telemetries: ["performance", "errors", "http"],
           allowCookies: true,
           enableXRay: false
       });
   </script>
   ```

1. If your application is a multipage web application, you must repeat step 1 for each HTML page that you want included in the data collection.

# Testing your CloudWatch app monitor setup by generating user events
<a name="CloudWatch-RUM-get-started-generate-data"></a>

After you have inserted the code snippet and your updated application is running, you can test it by manually generating user events. To test this, we recommend that you do the following. This testing incurs standard CloudWatch RUM charges.
+ Navigate between pages in your web application.
+ Create multiple user sessions, using different browsers and devices.
+ Make requests.
+ Cause JavaScript errors.

After you have generated some events, view them in the CloudWatch RUM dashboard. For more information, see [Viewing the CloudWatch RUM dashboard](CloudWatch-RUM-view-data.md).

Data from user sessions might take up to 15 minutes to appear in the dashboard.

If you don't see data 15 minutes after you generated events in the application, see [Troubleshooting CloudWatch RUM](CloudWatch-RUM-troubleshooting.md).