How to use Google Optimize with NextJS

This guide will show you how I’ve gotten Google Optimize experiments to run properly on a NextJS site, without doing any advanced implementation.

Google Optimize can help you test improvements to your site, but it’s most effective when you don’t need to interrupt developers to add new scripts to your site codebase for every test. Unfortunately creating tests using Optimize’s editor for a site that uses reactive frameworks can create errors.

I’ve found two common categories of errors that pop up when you run Optimize tests on a NextJS site:

Error crashes your site

When your test is previewed you can either see your test blink, or not show up at all, or the site crashes.

Why does this happen?

Your test is probably editing HTML on the page. Causing the reactive framework to develop errors when it rerenders that part of the screen.

How to work around it:

To work around this problem you can constrain yourself to adding HTMLmoving HTML, or adding CSS, but not changing or removing HTML.

Error where a test never starts, or gets zero traffic

When you preview tour test it either never starts, or it’s shown on every page regardless of URL or trigger. When published the test either never starts of the alternative get’s no traffic.

Why does this happen?

NextJS, and other JS frameworks, can send new pages from the server (server side rendered, or first page draw), or render new pages with new URLs directly in the browser. Unfortunately, rendering new pages in the browser does not trigger the same window events as server render, specifically Page Load.

How to work around it:

Add a specific event to your site Router. There are tons of examples on how to setup Routers for every framework our there, a good developer should solve it in an hour, and you only have to do this once.

Specifically we add an event on navigation in your Router, we call one using Google DataLayer to specifically support Google Tag Manager. This is the code we run: window.dataLayer.push({'event': 'pageView'});

Then trigger your experiments on Custom Event: pageView instead of PageLoad and they’ll all work like you intended.

Good luck, and let me know if you have any problems with this!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s