next/script component lets you load and manage third-party scripts with built-in loading strategies that optimize performance.
Basic usage
ImportScript from next/script and add it to any layout or page:
Loading strategies
Thestrategy prop controls when the script loads relative to the page lifecycle.
afterInteractive (default)
afterInteractive (default)
Loads the script after the page becomes interactive. This is the default and is suitable for most third-party scripts that don’t need to run before the page is usable.Use for: Analytics, tag managers, chatbots.
app/page.tsx
lazyOnload
lazyOnload
Loads the script during browser idle time, after all page resources have been fetched. Use for scripts that don’t need to load early.Use for: Low-priority scripts, social share buttons, feedback widgets.
app/page.tsx
beforeInteractive
beforeInteractive
Loads the script before any Next.js code and before page hydration. This strategy must be placed in the root layout (Use for: Bot detection scripts, consent managers, polyfills that must run before any other code.
app/layout).app/layout.tsx
worker (experimental)
worker (experimental)
Loads the script in a web worker using Partytown. This offloads heavy third-party scripts from the main thread.Enable the feature first in Use for: Analytics, ad scripts, and other heavy third-party scripts you want off the main thread.
next.config.js:next.config.js
app/page.tsx
Inline scripts
For small inline scripts, use theScript component with either a string or JSX children:
Inline scripts require a unique
id prop so Next.js can track and optimize them.Event handlers
Use event handler props to execute code at different points of the script lifecycle:Fires once when the script has finished loading. Cannot be used with
beforeInteractive.Fires after the script loads and every time the component mounts. Useful for re-running script initialization when navigating between pages.
Fires when the script fails to load. Cannot be used with
beforeInteractive.Props reference
URL of the external script. Required unless
dangerouslySetInnerHTML or children are used.The loading strategy. One of
'beforeInteractive', 'afterInteractive', 'lazyOnload', or 'worker'.Required for inline scripts (those using
dangerouslySetInnerHTML or children).A cryptographic nonce for Content Security Policy support.
