Next.jsMedium

What is next/script and what are its loading strategies?

next/script exports a <Script> component for loading third-party JavaScript with explicit timing. Its strategy prop picks when the script loads, beforeInteractive, afterInteractive (default), lazyOnload or the experimental worker, and Next.js deduplicates scripts across navigations.

Strategies

  • beforeInteractive: injected into the initial HTML and loaded before any Next.js code or hydration. Only for critical scripts like bot detection or consent managers. Place it in the root layout.
  • afterInteractive (default): loads after some hydration. Good for analytics and tag managers.
  • lazyOnload: loads during browser idle time after everything else. Good for chat widgets, social embeds and low-priority tools.
  • worker (experimental): offloads the script to a web worker using Partytown. Requires nextScriptWorkers and is not supported in the App Router.

Other props

  • src or inline content (inline scripts need an id so Next.js can track them).
  • onLoad and onError (Client Components only), and onReady, which runs on load and on every remount.
  • Standard attributes such as nonce, crossOrigin and data-*.

Behavior

  • A script loads once, even if multiple pages render it, and stays loaded across client navigations.
  • Scripts in a layout load for all its routes; in a page, only when that page is visited.

Performance tips

  • Default to lazyOnload unless you need data early.
  • For Google Analytics, Tag Manager, YouTube and Maps embeds, @next/third-parties provides optimized components.
  • Third-party scripts often dominate INP and Total Blocking Time; audit them regularly.

Code example

tsx
1// app/layout.tsx
2import Script from "next/script";
3
4export default function RootLayout({ children }: { children: React.ReactNode }) {
5 return (
6 <html lang="en">
7 <body>
8 {children}
9
10 {/* Consent manager must run before the app */}
11 <Script src="https://consent.example.com/cmp.js" strategy="beforeInteractive" />
12
13 {/* Analytics: after hydration */}
14 <Script src="https://plausible.io/js/script.js" data-domain="acme.com" strategy="afterInteractive" />
15
16 {/* Chat widget: whenever the browser is idle */}
17 <Script src="https://widget.example-chat.com/loader.js" strategy="lazyOnload" />
18
19 {/* Inline script needs an id */}
20 <Script id="feature-flags" strategy="afterInteractive">
21 {`window.__FLAGS__ = { newCheckout: true };`}
22 </Script>
23 </body>
24 </html>
25 );
26}

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