Skip to the solution
MediumFrontend4 min read

What is next/script and what are its strategy options in Next.js?

1.1k views

The problem

Question presented to candidate: "We need Google Tag Manager, a chat widget and a consent script on the site. How do you add third-party scripts in Next.js without hurting performance, and which strategy would each get?"

What a strong answer should cover:

  • The Script component from next/script loads external or inline scripts once per document, deduplicated, with a loading strategy.
  • beforeInteractive: before any Next.js code and before hydration; only allowed in the root layout; for scripts that must run first (consent, bot checks).
  • afterInteractive (default): after some hydration; for analytics and tag managers.
  • lazyOnload: during browser idle time after all resources load; for chat widgets and social embeds.
  • worker (experimental) moves a script into a web worker with Partytown; onLoad, onReady and onError callbacks need a Client Component.

Clarifying questions expected:

  • "Does this script need to run before the page becomes interactive?" β€” only then beforeInteractive.
  • "Is it needed on every page or just some?" β€” place the Script in the layout or page accordingly.

Code / implementation expected: Yes β€” one script per strategy.

  • nextjs
  • next-script
  • third-party
  • performance

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

4 min read Β· 8 sections

Read the code

One script per strategy
// app/layout.tsx
import Script from "next/script";
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <Script src="https://consent.example.com/cmp.js" strategy="beforeInteractive" />
        <Script src="https://www.googletagmanager.com/gtm.js?id=GTM-XXXX" strategy="afterInteractive" />
      </body>
    </html>
  );
}

// components/Chat.tsx
"use client";
import Script from "next/script";
export function Chat() {
  return <Script src="https://chat.example.com/widget.js" strategy="lazyOnload" onLoad={() => console.log("chat ready")} />;
}

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 24 of 129 in Next.js

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Next.js questions
Up nextMedium

How do you implement search, filtering and pagination with URL search params in the App Router?

Continue