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. RequiresnextScriptWorkersand is not supported in the App Router.
Other props
srcor inline content (inline scripts need anidso Next.js can track them).onLoadandonError(Client Components only), andonReady, which runs on load and on every remount.- Standard attributes such as
nonce,crossOriginanddata-*.
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
lazyOnloadunless you need data early. - For Google Analytics, Tag Manager, YouTube and Maps embeds,
@next/third-partiesprovides optimized components. - Third-party scripts often dominate INP and Total Blocking Time; audit them regularly.
Code example
tsx
1// app/layout.tsx2import Script from "next/script";34export default function RootLayout({ children }: { children: React.ReactNode }) {5 return (6 <html lang="en">7 <body>8 {children}910 {/* Consent manager must run before the app */}11 <Script src="https://consent.example.com/cmp.js" strategy="beforeInteractive" />1213 {/* Analytics: after hydration */}14 <Script src="https://plausible.io/js/script.js" data-domain="acme.com" strategy="afterInteractive" />1516 {/* Chat widget: whenever the browser is idle */}17 <Script src="https://widget.example-chat.com/loader.js" strategy="lazyOnload" />1819 {/* 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.