How to implement Amplitude in Next.js: A 3-Step Guide

In this data-driven era, analytic tools like Amplitude Analytics are essential for startups. Amplitude uses an event-based analysis method, allowing you to deeply understand user interactions. This is crucial during the growth stages of a product, assisting in the evaluation of the effectiveness of each feature as soon as they are released into production, enabling experimentation with various UI/UX strategies and identifying problem areas. All of this can translate into a user experience that perfectly fits your product's audience, ultimately leading to an undeniable increase in user retention.

This article offers a guide on how to incorporate Amplitude into a new Next.js application.


Disclaimer

This is my basic and somewhat subjective approach to setting it up. During the setup in a Next.js app, I encountered numerous problems, and a post like this would have been incredibly helpful at that time. Hopefully, this can be of assistance to you all 🙂 .

You can refer to the official Amplitude documentation via this link: https://www.docs.developers.amplitude.com/

I'm going to assume that you have already created an account and obtained an API code from Amplitude. If you need help, don't hesitate to ask in the comments or through Github Discussions.

Interesting links:

Step 1: Setting up a Next.js Application

First, create a new Next.js application and install the Amplitude library with the following commands:

yarn create-next-app@latest my-app
yarn add @amplitude/analytics-browser

You can also clone the repository that I made to explain this blog:

git clone [email protected]:Ianduha13/next-amplitude-blog.git

Then, generate a new file called .env in the root directory of your project and add your Amplitude API key:

NEXT_PUBLIC_AMPLITUDE_API_KEY=Your_Amplitude_API_Key

Step 2: Implement Amplitude in your Code

To incorporate Amplitude into your application, you need to include certain functions in your code. These entail initializing Amplitude and setting up a click handler to track specific events.

Initialize Amplitude

Initially, develop a function to import the Amplitude package asynchronously and initialize it with your API key. I personally recommend extracting the instance logic to a custom hook.

import { useEffect } from "react"

export let amplitude
const AMPLITUDE_API_KEY = process.env.NEXT_PUBLIC_AMPLITUDE_API_KEY

const useAmplitudeInit = () => {
  useEffect(() => {
    const initAmplitude = async () => {
      amplitude = await import("@amplitude/analytics-browser")
      amplitude.init(AMPLITUDE_API_KEY, undefined, {
        logLevel: amplitude.Types.LogLevel.Warn,
        defaultTracking: {
          sessions: true,
        },
      })
    }
    initAmplitude()
  }, [])
}

export default useAmplitudeInit

The initAmplitude function utilizes dynamic import to bring in the @amplitude/analytics-browser package. Using a regular static import can lead to issues as the library might not work optimally in SSR. The configurations made here are among those recommended by the official documentation. (defaultTrackingand logLevelpertains to which of Amplitude's predefined events we wish to incorporate into your tracking plan for this particular application)

Step 3: Use the hook in a component

Then, in your _app.js (or page.js if you are using Next.js 13) import the custom hook and use it in your app component.

import useAmplitudeInit from "@/app/hooks/useAmplitudeInit"

export default function Home() {
  useAmplitudeInit()
  ...
}

Note: this hook should be used only once in your project, since it's used to create the first instance.

Create Event Handler

Following this, construct an event handler function, clickHandler, to monitor click events importing and using the amplitude instance:

import { amplitude } from "@/app/hooks/useAmplitudeInit"

...

const clickHandler = () => {
  amplitude.track("click", {
    text: "each click is a new event, and each star or like supports me immensely!",
  })
}

Now, this handler can be attached to any element in your application to track click events. For instance, if there's a button in your application, link the clickHandler to the onClick event of this button:

The amplitude .track method receives as its first parameter the name of the event which will be identified within amplitude and as its second parameter an object with the properties of the event (this is clearly seen in the following section). In the amplitude documentation, you will find many possibilities to customize these events, different methods and properties that later facilitate the extraction of data and analysis of the same.

It's amazing the world of possibilities that working with event-driven analytics opens up for us as developers, plus Amplitude is hugely customizable.

Congratulations! You can now visualize your first events on Amplitude 🚀

To view the tracked events, head to your Amplitude dashboard and select user-lookup in your navbar. You should see something like this:

If you want to see the "user stream" made for a user, you can select the userID provided in that list.

Which will display the following profile card, here you can visualize many very interesting and customizable data that can be very helpful when evaluating the engagement of a certain feature:

And that's it! When a user press the button on the page, it triggers an event in the Amplitude analytics log. With this data, you can create custom charts and dashboards to better understand how your product is being used, all in-lined with your specific business needs.

💡 Here I leave you an official source to practice with sample data in a premium environment: https://analytics.amplitude.com/demo/home


Bonus Track: Online demo

Here is the page we developed through this tutorial, complicated, isn't it? 🤣

Jokes aside, here's a link to the online demo: https://next-amplitude.vercel.app/

If you visit the link and press the button, you'll witness a real-time change in the chart within the Amplitude public link provided in the second button. You'll see something like this:

Apologies if the chart is somewhat condensed, but charts can't be shared with full access links as editors on Amplitude's free plan.

Thank you for reading my article! It was a great experience for me, and I hope you found it valuable.

As a JavaScript developer in a seed phase startup, I'll be sharing more insights and updates on my journey. If you're interested in staying updated with my future posts, you can follow me on the following links:

I look forward to connecting with other developers 😃

More content at PlainEnglish.io.

Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.

02/07/2023