Next.jsMedium
How does Next.js optimize third-party scripts?
Next.js gives third-party scripts controlled loading with next/script strategies (beforeInteractive, afterInteractive, lazyOnload, experimental worker), deduplicates them across navigations, and provides @next/third-parties components for Google Tag Manager, Google Analytics, YouTube and Google Maps that load efficiently by default.
Why it matters
Third-party scripts (analytics, ads, chat, A/B testing) are often the largest source of main-thread work, hurting INP, Total Blocking Time and LCP.
Tools
<Script strategy>: delay non-critical scripts. Chat widgets withlazyOnload; analytics withafterInteractive; only consent and bot protection withbeforeInteractive.@next/third-parties:<GoogleTagManager gtmId="GTM-XXXX" />andsendGTMEvent().<GoogleAnalytics gaId="G-XXXX" />andsendGAEvent().<YouTubeEmbed videoid="..." />uses a lightweight facade until the user clicks.<GoogleMapsEmbed />lazy-loads the map iframe.
- Placement: scripts in a specific page load only on that route; in the root layout they load everywhere.
- Workers:
strategy="worker"with Partytown moves scripts off the main thread. It is experimental and Pages Router only.
Other practices
- Preconnect to required third-party origins only.
- Self-host small scripts when licensing allows.
- Use facades for embeds (load the real widget on click).
- Respect consent: do not load tracking scripts until the user agrees.
- Add hashes or nonces to a Content Security Policy so only approved scripts run.
Code example
tsx
1// app/layout.tsx2import { GoogleTagManager } from "@next/third-parties/google";3import Script from "next/script";45export default function RootLayout({ children }: { children: React.ReactNode }) {6 return (7 <html lang="en">8 <GoogleTagManager gtmId="GTM-ABCD123" />9 <body>10 {children}11 <Script src="https://widget.intercom.io/widget/abc123" strategy="lazyOnload" />12 </body>13 </html>14 );15}1617// app/videos/page.tsx18// import { YouTubeEmbed } from "@next/third-parties/google";19// <YouTubeEmbed videoid="dQw4w9WgXcQ" height={400} params="controls=1" />2021// Client event:22// "use client";23// import { sendGTMEvent } from "@next/third-parties/google";24// <button onClick={() => sendGTMEvent({ event: "signup_click" })}>Sign up</button>
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.