Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 72 ยท Optimization and SEO

Fonts and Third-Party Scripts

Load web fonts without layout shift using next/font, and load analytics or widgets without blocking the page using next/script strategies in the App Router.

Two things quietly ruin the speed of many websites: web fonts and third-party scripts. A font file that arrives late makes text jump or flash. An analytics tag, a chat widget or an ad script competes with your own code for the network and the main thread. Neither is part of your app's logic, yet both can push your Core Web Vitals into the red.

Next.js ships a small component or helper for each problem. next/font downloads and hosts fonts for you and removes the layout jump. next/script lets you say when an external script should load. In this lesson you will use both, see the options that matter, and learn the traps. The real framework cannot run on this site, so the Next.js code is read-only. Two runnable stand-ins show the ideas underneath: how a font setup becomes CSS, and how script strategies change the order of events.

Fonts and scripts, handled

next/font Self-hosted fonts with no extra request to a font CDN.
No layout jump A matched fallback font keeps text from shifting.
next/script You choose when an outside script loads.
Third-party helpers Ready-made components for common widgets.
1 / 2

Why fonts cause trouble

When the browser meets a custom font, it must download the file before it can draw the text in that font. During the wait it either hides the text or shows a fallback such as Arial. When the real font arrives, the text is redrawn. If the two fonts have different widths and heights, every line reflows and the page jumps. This jump counts toward Cumulative Layout Shift (CLS), a metric you will meet again in Bundle Size and Core Web Vitals.

The usual fix by hand is a long checklist: download the files, convert them to WOFF2, add @font-face rules, set font-display, preload the important file, and tune a fallback font so it is the same size. A link to a font CDN is shorter but adds a connection to another domain on the critical path.

Google fonts with next/font

next/font/google does that checklist at build time. You import the font by name, call it as a function, and use the object it returns:

TSX
// app/layout.tsx (read-only)
import { Inter } from "next/font/google";

const inter = Inter({
  subsets: ["latin"],
  display: "swap",
});

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" className={inter.className}>
      <body>{children}</body>
    </html>
  );
}

During next build Next.js downloads the font files and stores them with your other static assets. At run time the browser asks your domain for them; it never contacts Google. The font function returns three useful things:

  • className: a generated class that sets font-family to the font (and a fallback).
  • style.fontFamily: the same family as an inline style value.
  • variable: a class that defines a CSS variable, if you pass the variable option.

Some options deserve a note:

  • subsets tells Next.js which character sets to download and preload. Choose only what you need, such as ["latin"]. Fewer subsets mean smaller files.
  • display maps to font-display. The default is swap: show the fallback at once and swap when the font is ready.
  • weight is required for fonts that are not variable. Pass a string or an array such as ["400", "700"].
  • Names with spaces use underscores in the import: Roboto_Mono, Open_Sans.

Variable fonts

A variable font packs a whole range of weights (and sometimes widths) into one file. When a font is variable, you do not need to list weights at all, and one file serves every weight your CSS asks for. Next.js recommends variable fonts when the family offers one, because they are flexible and often smaller than several static files. Inter({ subsets: ["latin"] }) above gets the variable file automatically. For extra axes such as width, a font that supports them accepts an axes option.

Using the CSS variable option

The className approach applies one font to a whole subtree. If you want several fonts, or if you use a CSS framework, ask for a variable instead and use it where you need it:

TSX
// app/layout.tsx (read-only)
import { Inter, Roboto_Mono } from "next/font/google";

const sans = Inter({ subsets: ["latin"], variable: "--font-sans" });
const mono = Roboto_Mono({ subsets: ["latin"], variable: "--font-mono" });

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" className={`${sans.variable} ${mono.variable}`}>
      <body>{children}</body>
    </html>
  );
}
CSS
/* app/globals.css (read-only) */
body {
  font-family: var(--font-sans), system-ui, sans-serif;
}
code {
  font-family: var(--font-mono), monospace;
}

With Tailwind CSS you map those variables into the theme so classes such as font-sans use them; Styling in Next.js shows how.

Your own font files

If you own the font files, use next/font/local. Put the files next to your code (for example in app/fonts/) and point to them:

TSX
// app/fonts.ts (read-only)
import localFont from "next/font/local";

export const brand = localFont({
  src: [
    { path: "./fonts/Brand-Regular.woff2", weight: "400", style: "normal" },
    { path: "./fonts/Brand-Bold.woff2", weight: "700", style: "normal" },
  ],
  variable: "--font-brand",
  display: "swap",
});

Pass a single path when you have one file, or an array when each file is a weight or style. Prefer WOFF2: it is compressed and supported everywhere.

What Next.js adds: a size-adjusted fallback

Self-hosting already removes one network hop. The cleverer part is the automatic fallback adjustment. While your font loads, text shows in a system font. Next.js generates an extra @font-face that takes that system font and scales it (with size-adjust and related descriptors) so its metrics match your real font. When the real font arrives, the lines barely move, and the layout shift is close to zero. You do not write any of this; it happens when the helper runs at build time.

The stand-in below mimics the shape of what next/font/local produces from a configuration: a generated class name, one @font-face rule per file, and a CSS variable class. The real implementation also hashes file contents, emits preload tags and computes the fallback metrics, which the stand-in leaves out.

Node.js From font config to CSS (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that the URLs point at /_next/static/media/ on your own domain, which is the whole point of self-hosting. The font file name is a generated one; you never reference it yourself.

Where to call the font function

Call the font function at the top level of a module, never inside a component or a loop. Next.js analyzes the call at build time to know which files to fetch, so the options must be literal values. A tidy habit is one fonts.ts file that exports every font, imported by layouts. Because the fonts are scoped to where you apply the class, you can use a different font for one section of the app by putting its className on a nested layout instead of the root.

Loading third-party scripts

A third-party script is JavaScript you do not own: analytics, a consent banner, a chat bubble, an A/B testing tool. A plain <script src> tag in the document head blocks parsing, and one slow vendor server can stall your whole page. next/script wraps the tag in a component with a loading strategy.

TSX
// app/layout.tsx (read-only)
import Script from "next/script";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <Script src="https://widgets.example.com/chat.js" strategy="lazyOnload" />
      </body>
    </html>
  );
}

The strategies, from earliest to latest:

  • beforeInteractive loads the script before any Next.js code runs and before the page hydrates. It is meant for things the page cannot work without, such as a bot detector or a consent manager that must run first. In the App Router it belongs in the root layout.
  • afterInteractive is the default. The script loads after some of the page has hydrated, which suits tag managers and analytics.
  • lazyOnload waits until the browser is idle after everything else has loaded. Use it for chat widgets, social buttons and anything not needed to use the page.
  • worker would move a script into a web worker. It is experimental and does not work with the App Router, so skip it.

The stand-in below lists a page's life in order and drops one script into it, depending on the strategy you choose. It is a model of the order of events, not of real timing.

Where does the script run?

Switch the strategy and watch the highlighted line move down. The later the line, the less the script slows the moment your page becomes usable.

Inline scripts, events and the @next/third-parties package

You can also write a script inline. Give it an id so Next.js can track it and avoid running it twice:

TSX
// read-only
<Script id="init-flag" strategy="afterInteractive">
  {`window.__siteReady = true;`}
</Script>

next/script accepts callbacks. onLoad runs once when the script first finishes loading, onReady runs after it loads and again whenever the component is mounted anew, and onError runs if loading fails. Callbacks are functions, so a component that uses them has to be a Client Component (see Client Components and "use client"). If you only need the script tag, a Server Component is fine.

For popular services there is the optional @next/third-parties package, with components that load Google Analytics, Google Tag Manager, an embedded YouTube player or Google Maps in a performance-friendly way:

TSX
// app/layout.tsx (read-only)
import { GoogleAnalytics } from "@next/third-parties/google";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>{children}</body>
      <GoogleAnalytics gaId="G-XXXXXXXXXX" />
    </html>
  );
}

Replace the placeholder with your own measurement ID.

Analytics and third-party libraries in depth

Analytics, tag managers, maps and video embeds are the usual reasons a fast page becomes a slow one. Each is a third-party script that you do not control. The @next/third-parties package wraps the most common services in components that load them with sensible timing, so you do not have to choose next/script strategies yourself. Install it with npm install @next/third-parties.

The ready-made components

All of them are imported from @next/third-parties/google:

TSX
// read-only
import { GoogleAnalytics, GoogleTagManager, YouTubeEmbed, GoogleMapsEmbed } from "@next/third-parties/google";

// Google Analytics 4: once, in the root layout (it also tracks client-side route changes).
<GoogleAnalytics gaId="G-XXXXXXXXXX" />

// Google Tag Manager: use this OR GoogleAnalytics, not both. Put it in the root layout.
<GoogleTagManager gtmId="GTM-XXXXXXX" />

// A YouTube player that loads a lightweight placeholder first and the iframe only on demand.
<YouTubeEmbed videoid="abc123XYZ" height={400} params="controls=0" />

// A Google Map in an iframe that loads lazily. The key must be a browser key restricted to your domain.
<GoogleMapsEmbed apiKey="YOUR_BROWSER_KEY" height={300} width="100%" mode="place" q="Brandenburg+Gate,Berlin" />

Use either GoogleAnalytics or GoogleTagManager. A tag manager can load analytics itself, and installing both counts every visit twice. Both components accept a dataLayerName option if you need a custom data layer name. To send a custom event from a Client Component, use the helper functions:

TSX
// components/buy-button.tsx (read-only)
"use client";
import { sendGAEvent } from "@next/third-parties/google";

export function BuyButton() {
  return <button onClick={() => sendGAEvent("event", "buttonClicked", { value: "buy" })}>Buy</button>;
}

sendGTMEvent does the same for Tag Manager. Check the package documentation for the current list of components and options, because Google changes its products and the package follows.

In many countries you must ask before loading analytics or advertising scripts. The simplest honest approach is to not render the component until the visitor agrees. A small Client Component reads the choice and mounts the script only then:

TSX
// components/analytics.tsx (read-only)
"use client";
import { useEffect, useState } from "react";
import { GoogleAnalytics } from "@next/third-parties/google";

export function Analytics() {
  const [allowed, setAllowed] = useState(false);

  useEffect(() => {
    setAllowed(document.cookie.includes("analytics=granted"));
  }, []);

  return allowed ? <GoogleAnalytics gaId="G-XXXXXXXXXX" /> : null;
}

Reading the cookie in an effect (not during render) keeps the server HTML identical for everyone, which keeps pages cacheable, as in Static Generation. A consent banner then sets the cookie and the state. Because the legal rules differ by country and change, treat this as the technical pattern only and ask a specialist about your obligations. The stand-in below models the pattern: events are queued until consent is given and then flushed, and nothing is sent when consent is refused.

Node.js Queue analytics events until consent

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Reporting Web Vitals

Analytics for performance means Web Vitals: Largest Contentful Paint (LCP, how fast the main content appears), Interaction to Next Paint (INP, how quickly the page responds to input) and Cumulative Layout Shift (CLS, how much the layout jumps). They are measured in real visitors' browsers, which tells you more than a lab test. Next.js exposes them with the useReportWebVitals hook from next/web-vitals, which must run in a Client Component. Put a tiny one in the root layout:

TSX
// components/web-vitals.tsx (read-only)
"use client";
import { useReportWebVitals } from "next/web-vitals";

export function WebVitals() {
  useReportWebVitals((metric) => {
    // metric: { id, name, value, rating, delta, navigationType }
    const body = JSON.stringify({ name: metric.name, value: metric.value, rating: metric.rating, id: metric.id });
    navigator.sendBeacon("/api/vitals", body);
  });
  return null;
}

navigator.sendBeacon queues a small request that the browser delivers even while the page is closing, which is exactly when some metrics are final. A Route Handler at /api/vitals (Route Handlers) stores them. Each metric arrives with a rating of good, needs-improvement or poor, based on Google's published thresholds. The stand-in rates a few measurements by those thresholds and summarizes a batch the way a collector would.

Node.js Rate and summarize Web Vitals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Judge a page by the 75th percentile (p75) of real visits, as Google does for its page-experience reports, not by the average, because a few very slow visitors hide inside an average. Related tools: the @vercel/analytics and @vercel/speed-insights packages if you host on Vercel, and any analytics product that offers a script, which you load with next/script and the afterInteractive or lazyOnload strategy from this lesson. Whatever you add, keep a budget: measure the page before and after (Bundle Size and Core Web Vitals), and if you use a Content Security Policy, allow each vendor's domain (Security Headers and CSP).

Rules of thumb

  • Every third-party script has a price. Ask whether you need it before you ask how to load it.
  • Default to afterInteractive; move anything non-essential to lazyOnload.
  • Use beforeInteractive only when the page would be wrong without the script, and only in the root layout.
  • Set subsets narrowly for fonts, and prefer a variable font when one exists.
  • Measure the result. Fonts and scripts show up in the Lighthouse report and in field data.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where does the browser download a font that you loaded with next/font/google?

    next/font fetches the files during the build and serves them as static assets of your site, so visitors never connect to Google.
  2. 2. Which strategy is the default for next/script?

    afterInteractive is used when you pass no strategy. The script loads soon after the page starts to hydrate.
  3. 3. A chat widget is nice to have but not needed to use the page. Which strategy fits best?

    lazyOnload waits for the browser to be idle after the page has loaded, so the widget cannot compete with your own code.
  4. 4. Why does next/font reduce layout shift?

    The adjusted fallback has nearly the same size as the web font, so the text hardly moves when the real font replaces it.
  5. 5. Why must the options of a font function such as Inter({ subsets: ['latin'] }) be literal values?

    The font files are fetched and processed at build time, so Next.js must be able to read the options statically.

Summary

  • next/font downloads fonts at build time and serves them from your own domain, with an adjusted fallback so text does not jump.
  • Use next/font/google for Google families and next/font/local for your own WOFF2 files; call font functions at module top level with literal options.
  • Variable fonts need no weight list; non-variable fonts require one. Keep subsets narrow.
  • The variable option exposes a CSS variable, which suits several fonts and Tailwind.
  • next/script strategies are beforeInteractive, afterInteractive (default), lazyOnload and the experimental worker.
  • Inline scripts need an id; callbacks like onLoad require a Client Component; @next/third-parties wraps common services.

Next: Metadata and SEO