Dynamite

How to add a third-party script to a Next.js app

In the App Router, a script that should load on every route goes in the root layout, through the Script component from next/script. Next.js loads it once and keeps it across client-side navigation. That second part is where most surprises come from.

Before you start

Steps

Check it worked

What goes wrong

Increase conversions on your Next.js site by 20%

Dynamite personalizes the page for every visitor. Dynamite personalizes a Next.js site from one Script element in the root layout, with the site id as a data attribute. It watches client-side route changes itself and asks for a fresh decision on each route.

Dynamite for Next.js

Questions

Where do I put a script that should load on every page in Next.js?

In the root layout, app/layout.tsx, using the Script component from next/script.

Does next/script reload the script on every navigation?

No. Next.js loads it once, even when a user navigates between multiple pages.

How do I remove the script?

Delete the Script element from the layout and redeploy.