October 23, 2023

Add CloudWatch RUM to a Next.js app

This tutorial will assume that you've already set up your CloudWatch RUM monitor in AWS CloudWatch. If you haven't follow those instructions here.


CloudWatch RUM (Real User Monitoring) is a powerful tool within the AWS suite that allows you to collect client-side metrics and performance data.

There is enough documentation available on how to add RUM to any React application, but if you are using Next.js there are some extra steps in order to get up and running.

The RUM web client documentation suggests using the HTML snippet, but other than getting some IDE errors when pasting it in, since we're (probably) using Typescript for our Next.js app, it makes sense to use Typescript to initialize RUM.

When we insert the RUM code in our layout.tsx file (or whereever you decide to place the initilzation code), we'll see the following error in our console.

ReferenceError: window is not defined

This is because by default, Next.js pages are rendered server side and RUM is trying to access the window object, which is only available client-side.

To fix this, we can set our Next.js layout.tsx file to be rendered client side by inserting the following at the top of the file:

"use client";

This tells Next.js to render it as a client-side component. Now when we run out RUM initialization code, we're error free!