0
0
NextJSframework~5 mins

Script component for third-party scripts in NextJS

Choose your learning style9 modes available
Introduction

The Script component helps you add external scripts safely and easily in your Next.js app.

You want to add Google Analytics to track visitors.
You need to load a chat widget from a third-party service.
You want to include a payment gateway script on your checkout page.
You need to add a script that runs only after the page loads.
Syntax
NextJS
import Script from 'next/script';

<Script
  src="https://example.com/script.js"
  strategy="lazyOnload"
  onLoad={() => console.log('Script loaded!')}
/>

The src attribute sets the URL of the external script.

The strategy controls when the script loads: beforeInteractive, afterInteractive, or lazyOnload.

Examples
Loads the script before the page becomes interactive, useful for critical scripts.
NextJS
<Script src="https://example.com/script.js" strategy="beforeInteractive" />
Loads the script right after the page is interactive, good for most third-party scripts.
NextJS
<Script src="https://example.com/script.js" strategy="afterInteractive" />
Loads the script during idle time after the page loads, best for non-critical scripts.
NextJS
<Script src="https://example.com/script.js" strategy="lazyOnload" />
Example of adding an inline script with an ID and strategy.
NextJS
<Script id="custom-script" strategy="afterInteractive">
  {`console.log('Inline script running')`}
</Script>
Sample Program

This example shows how to add Google Analytics scripts using the Next.js Script component. The first Script loads the external GA library after the page is interactive. The second Script runs inline code to initialize GA tracking.

NextJS
import React from 'react';
import Script from 'next/script';

export default function Home() {
  return (
    <>
      <h1>Welcome to My Site</h1>
      <Script
        src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"
        strategy="afterInteractive"
      />
      <Script
        id="google-analytics"
        strategy="afterInteractive"
      >
        {`window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'GA_MEASUREMENT_ID');`}
      </Script>
    </>
  );
}
OutputSuccess
Important Notes

Use the strategy prop to control when scripts load for better performance.

Always add an id prop for inline scripts to avoid duplication.

Scripts added with the Script component are automatically optimized by Next.js.

Summary

The Script component safely loads third-party scripts in Next.js.

Use strategy to control script loading timing.

Supports both external and inline scripts with easy syntax.