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

  1. <Script strategy>: delay non-critical scripts. Chat widgets with lazyOnload; analytics with afterInteractive; only consent and bot protection with beforeInteractive.
  2. @next/third-parties:
    • <GoogleTagManager gtmId="GTM-XXXX" /> and sendGTMEvent().
    • <GoogleAnalytics gaId="G-XXXX" /> and sendGAEvent().
    • <YouTubeEmbed videoid="..." /> uses a lightweight facade until the user clicks.
    • <GoogleMapsEmbed /> lazy-loads the map iframe.
  3. Placement: scripts in a specific page load only on that route; in the root layout they load everywhere.
  4. 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.tsx
2import { GoogleTagManager } from "@next/third-parties/google";
3import Script from "next/script";
4
5export 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}
16
17// app/videos/page.tsx
18// import { YouTubeEmbed } from "@next/third-parties/google";
19// <YouTubeEmbed videoid="dQw4w9WgXcQ" height={400} params="controls=1" />
20
21// 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.

Open in study app