Solved

Setting up Ampli in nextjs for client rendered and SSR pages

  • 21 December 2023
  • 1 reply
  • 697 views

How are you tracking events for client side rendered pages and server side rendered pages in nextjs?

We've set up  Ampli and Amplitude's browser SDK for our nextjs app’s analytics. We currently initialize it in a context provider that wraps the whole application and this works fine for client side components. I'm trying to figure out how to call our analytics for our server side rendered pages as well. Currently, I'm getting a "ERROR: Ampli is not yet initialized. Have you called ampli.load() on app start?" on server side rendered pages since they don’t see the context provider.

In an ideal world, we’d be able to call ampli events from client pages and server side rendered pages using the same tracking plan.

icon

Best answer by DJC 23 December 2023, 06:00

View original

1 reply

In case anyone has the same issue, here's what we settled on:

1) Only implement the Amplitude Browser SDK and Ampli wrapper

2) create page specific components with the 'use client'; declaration.

3) within those components, only include the relevant analytics code within a useEffect() hook to control when it fires and return null.

 

The one drawback is that analytics events can only correspond to user visible changes in the application. We won't be able to fire off an event that happens server side if there isn't any state change that's visible to the user's browser.

Reply