Scripts and third-party code
Load analytics, tag managers, and widgets with next/script and its loading strategies, run code after load, and use @next/third-parties for common embeds.
Scripts and third-party code
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- `next/script` loads a third-party script once, even as users move between routes, and lets you choose when it loads with the `strategy` prop.
- The strategies are `beforeInteractive`, `afterInteractive` (the default), `lazyOnload`, and the experimental `worker`; pick the latest one the script can tolerate.
- `beforeInteractive` is only allowed in the root layout and is for critical scripts like bot detectors and cookie consent managers.
- A script placed in a layout loads for that layout's routes, in the root layout for every route; the docs recommend loading scripts only in the pages or layouts that need them.
- `onLoad`, `onReady`, and `onError` only work in Client Components, and an inline script needs an `id` so Next.js can track it.
Code you did not write still costs you
Analytics, a tag manager, a chat widget, a cookie banner. Each is a script from someone else’s server, and each competes with your own code for the browser’s main thread. A plain <script> tag in your HTML blocks, or races with, everything else, and you cannot tell it “wait until the page is usable.”
next/script wraps the <script> tag and adds a loading policy. The docs’ pitch is simple: Next.js loads the script once, even if the user moves between several routes, and you pick when it runs. The HTML-level mechanics of async and defer are in script loading, async, defer and modules; this lesson covers what Next.js layers on top.
Where you put it decides where it loads
// app/dashboard/layout.tsx
import Script from 'next/script'
export default function DashboardLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<>
<section>{children}</section>
<Script src="https://example.com/script.js" />
</>
)
}
A script in a layout is fetched when someone visits that layout’s route or any nested one, and only once while they stay inside. Put it in the root layout and it loads for any route. The docs recommend the narrower choice: include third-party scripts only in the specific pages or layouts that need them, to avoid unnecessary performance cost.
Strategy: when it loads
The strategy prop has four values:
beforeInteractiveloads before any Next.js code and before hydration. It is injected into the initial HTML, downloaded before any Next.js module, and runs in the order placed. It does not block hydration. It must live in the root layout, and is always injected into<head>wherever you put it. Use it for critical scripts such as bot detectors and cookie consent managers. It runs once per document load, so a client-side navigation does not run it again.afterInteractiveis the default. It loads early, after some hydration. Good for tag managers and analytics. It can live in any page or layout and loads only when that page or group of pages is opened.lazyOnloadloads during browser idle time, after everything else is fetched. Good for chat plugins and social widgets.workeris experimental and moves the script into a web worker using Partytown.
<Script src="https://example.com/chat.js" strategy="lazyOnload" />
The usable rule: start at lazyOnload, move earlier only when the script has to be there sooner, and reach for beforeInteractive only when it must beat your own code. Core web vitals in Next.js covers how loading order shows up in the numbers.
A note on worker
The docs mark worker with a warning: it is not stable and does not yet work with the App Router. The API reference adds that worker scripts can currently only be used in the pages/ directory, and that it needs experimental: { nextScriptWorkers: true } plus Partytown installed. So in an App Router project, treat it as unavailable. The video below demonstrates every strategy, and the worker demonstration may therefore not match what you can run in the App Router.
Running code after the script loads
Often a script defines a global you then have to call. Next.js gives you three events:
onLoadruns once after the script has finished loading.onReadyruns after load and again every time the component is mounted, such as after a route change.onErrorruns if the script fails to load.
'use client'
import Script from 'next/script'
export default function Page() {
return (
<Script
src="https://example.com/script.js"
onLoad={() => {
console.log('Script has loaded')
}}
/>
)
}
The handlers only work in a Client Component. onLoad and onError cannot be used with beforeInteractive; use onReady there.
Inline scripts and extra attributes
An inline script is written as children or with dangerouslySetInnerHTML. It needs an id:
<Script id="show-banner">
{`document.getElementById('banner').classList.remove('hidden')`}
</Script>
Attributes Script does not use itself, like nonce or data-*, are forwarded to the final <script> element. That is how a nonce from a Content Security Policy reaches the script; see security headers and CSP.
Skipping the plumbing: @next/third-parties
For a handful of popular integrations there is a package: @next/third-parties. The docs call it an experimental library under active development and suggest installing it with @latest or @canary. From @next/third-parties/google you get:
GoogleTagManagerwith agtmId, placed in the root layout for all routes or in a page for one. It fetches the script after hydration by default, andsendGTMEventpushes to the data layer.GoogleAnalyticswith agaId, withsendGAEventfor events. Pageviews on client-side navigation are tracked by Google Analytics itself, provided Enhanced Measurement is on.GoogleMapsEmbed, lazy-loaded by default.YouTubeEmbed, which loads faster by usinglite-youtube-embed.
import { GoogleAnalytics } from '@next/third-parties/google'
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
<GoogleAnalytics gaId="G-XYZ" />
</html>
)
}
The docs recommend configuring Analytics through Tag Manager if you already include Tag Manager, rather than adding both components.
What the video covers
Aditya Singh’s video is Part 2 of a short series, from March 2024, about fourteen minutes. By its title and recorded notes it implements beforeInteractive, afterInteractive, lazyOnload, the worker strategy, and inline scripts. We could not read a transcript, so nothing beyond that is claimed. Caveats: it is a small channel, it is two years old, it does not cover @next/third-parties, and its worker demo hits the App Router limit above. Part 1 (the concepts) and a Partytown-only talk from WP Engine Builders (June 2025, about half an hour, with worker called experimental in its own notes) are the “go deeper” links. Check by ear that the audio is English; titles and descriptions are.
Where this fits
That finishes styling and assets. Next, the question every app with accounts has to answer: authentication concepts and sessions.
Check yourself
A chat widget is not needed until the page is idle. Which strategy fits, and what is the default if you set none?
`lazyOnload` loads during browser idle time and suits chat widgets and social widgets. With no `strategy`, the default is `afterInteractive`, which loads early but after some hydration.
Where must a `beforeInteractive` script go in the App Router, and why is that restriction reasonable?
In the root layout. The script is injected into the initial HTML head and loaded before any Next.js code for the whole site, so it only makes sense for scripts every page needs, such as cookie consent.
Why does `<Script onLoad={...}>` fail in a Server Component?
The event handlers only work inside Client Components. Add `"use client"` to the file, and note `onLoad` and `onError` cannot be combined with `beforeInteractive`.
What is the difference between `onLoad` and `onReady`?
`onLoad` runs once after the script finishes loading. `onReady` runs after the load and again every time the component is mounted, which is what you want to re-create a map after a route change.
Why does an inline `<Script>` need an `id`?
Next.js uses it to track and optimize the script.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.