EthicsComputerCourses
Join training +91 90532 10052

HTML Integration with Next.js

HTML · Lesson 190 of 234 Advanced 12 min read Updated

By the end of this lesson you will be able to read the HTML that a Next.js App Router app really sends, predict which tags the root layout, the Metadata API, next/link, next/image and next/script produce, and fix the HTML mistakes that break hydration or accessibility in Next.js projects.

What you should know first: HTML Integration with React (JSX and what React renders), HTML in Templates & Frameworks (escaping and parser repairs), DOM vs HTML Source Code and HTML Document Outline & Landmarks. This lesson does not teach Next.js itself; the Next.js tutorial does that.

Next.js is the kitchen, HTML is the tiffin

Think of a Mumbai dabbawala. The kitchen can use any recipe, but the customer only receives the tiffin box. Next.js is the kitchen where you write React components in .tsx files. The browser only receives the tiffin: HTML, CSS and JavaScript. Search engines, screen readers and validators never see your components, so every HTML rule still applies to that output.

The outputs in this lesson are real. They come from a small demo app built with Next.js 16.4.6 and React 19.3.1 (the current releases on npm, checked on 15 November 2026), using next build and next start. Long <script> tags are trimmed and marked with ....

The root layout owns html and body

In the App Router, app/layout.tsx is the root layout: the one component that wraps every page. It is the only place where you write <html> and <body>, and Next.js requires both there. Details are in Pages & Layouts.

Step 1: write the layout with a language, landmarks and a skip link.

React TSX
// app/layout.tsx
import type { Metadata } from "next";
import Link from "next/link";
import Script from "next/script";

export const metadata: Metadata = {
  metadataBase: new URL("https://tiffins.example"),
  title: { default: "Annapurna Tiffins", template: "%s | Annapurna Tiffins" },
  description: "Home-style tiffins delivered across Pune.",
};

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en-IN">
      <body>
        <a href="#main" className="skip">Skip to content</a>
        <header>
          <nav aria-label="Main">
            <Link href="/">Home</Link>
            <Link href="/menu">Menu</Link>
          </nav>
        </header>
        <main id="main">{children}</main>
        <footer>Pune, Maharashtra</footer>
        <Script src="/chat-widget.js" strategy="lazyOnload" />
      </body>
    </html>
  );
}

Step 2: build the app and open .next/server/app/index.html. This is the start of what the home page sends:

Output
<!DOCTYPE html><html lang="en-IN"><head><meta charSet="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/..."/>
<script src="/_next/static/chunks/..." async=""></script> ...
<title>Annapurna Tiffins</title>
<meta name="description" content="Home-style tiffins delivered across Pune."/>
</head><body><div hidden=""><!--$--><!--/$--></div>
<a href="#main" class="skip">Skip to content</a>
<header><nav aria-label="Main"><a href="/">Home</a><a href="/menu">Menu</a></nav></header>
<main id="main"> ...page content... </main><footer>Pune, Maharashtra</footer>
<script>(self.__next_f=self.__next_f||[]).push([0])</script> ...

Notice four things:

  • You never wrote <head>, the charset or the viewport tag. Next.js always adds those two meta tags.
  • className became class. charSet and srcSet stay camelCase, which is fine: HTML attribute names are not case-sensitive.
  • The layout's landmarks appear on every page, so a page adds only its <h1> and content, never a second <main>.
  • The self.__next_f.push(...) scripts carry the RSC payload: a serialised copy of the component tree that React uses to take over the page.

The Metadata API turns objects into head tags

You do not write <title> or <meta> by hand. You export a metadata object, or a generateMetadata function when the tags depend on the request. Both work only in Server Components. Metadata & SEO covers every field; here we only look at the output.

Step 3: give the menu page a title that depends on a query string.

React TSX
// app/menu/page.tsx
import type { Metadata } from "next";

type Props = { searchParams: Promise<{ veg?: string }> };

export async function generateMetadata({ searchParams }: Props): Promise<Metadata> {
  const { veg } = await searchParams;
  return {
    title: veg ? "Veg menu" : "Full menu",
    alternates: { canonical: "/menu" },
  };
}

Request /menu?veg=1 and the head contains:

Output
<title>Veg menu | Annapurna Tiffins</title>
<meta name="description" content="Home-style tiffins delivered across Pune."/>
<link rel="canonical" href="https://tiffins.example/menu"/>

The layout's template added the site name, the description was inherited, and metadataBase turned /menu into an absolute canonical URL. The docs say a relative URL without metadataBase causes a build error, so set it once in the root layout.

Since Next.js 15.2, a slow generateMetadata on a dynamic page may stream its tags into <body> after the page starts arriving. Bots that cannot run JavaScript are detected by user agent and still get them in <head>. For head design across many pages, see Metadata at Scale: Head Templates.

The <Link> components above became <a href="/">Home</a> and <a href="/menu">Menu</a>, with no extra attributes. That is good news: crawlers follow them, middle-click opens a new tab, and screen readers announce "link". Next.js only adds client-side navigation and prefetching on top. See Crawlable Links, Breadcrumbs & Pagination.

The common mistakes all lose that anchor:

  • <div onClick={() => router.push("/menu")}> has no href, no keyboard support and no link role. Use <Link>.
  • <Link href="/order"><button>Order</button></Link> puts a button inside a link. Interactive content may not nest. Style the link instead.
  • A whole card wrapped in <Link> with another <Link> inside it creates nested <a> elements, which the parser splits apart.

Mark the current page with aria-current="page". That needs usePathname(), so it lives in a small Client Component:

React TSX
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";

export function NavLink({ href, children }: { href: string; children: React.ReactNode }) {
  const pathname = usePathname();
  return (
    <Link href={href} aria-current={pathname === href ? "page" : undefined}>
      {children}
    </Link>
  );
}

next/image is an img with srcset

Step 4: add a photo of the day's thali to the home page.

React TSX
<Image src="/thali.jpg" alt="Steel plate with dal, rice, two rotis and sabzi"
  width={800} height={500} />
Output
<img alt="Steel plate with dal, rice, two rotis and sabzi" loading="lazy"
  width="800" height="500" decoding="async" data-nimg="1" style="color:transparent"
  srcSet="/_next/image?url=%2Fthali.jpg&amp;w=828&amp;q=75 1x, /_next/image?url=%2Fthali.jpg&amp;w=1920&amp;q=75 2x"
  src="/_next/image?url=%2Fthali.jpg&amp;w=1920&amp;q=75"/>

Everything from Responsive Images: Picture & Srcset and Lazy Loading & Image Optimization is here: width and height reserve space, loading="lazy" is the default, and srcSet offers two densities. With a sizes prop, the output switches to width descriptors (384w up to 3840w) plus your sizes attribute.

Lazy loading delays the main banner, which is often the Largest Contentful Paint element. Next.js 16 deprecated the priority prop in favour of preload. In our build, preload removed loading="lazy" and added <link rel="preload" as="image"> to the head. The docs suggest loading="eager" or fetchPriority="high" in most cases instead.

alt is required, but Next.js cannot judge it: alt="image" still ships. Write real alt text, or alt="" for decoration.

Server and Client Components: what arrives first

Server Components (the default) render on the server and send only HTML. Client Components start with "use client", as covered in Server & Client Components. Beginners often think Client Components arrive empty. They do not. Our OrderButton uses useState, yet the first HTML already contains it:

Output
<button type="button">Add to order (<!-- -->0<!-- -->)</button>

The <!-- --> comments separate text pieces so React can match them later. The button is visible at once, but it does nothing until its JavaScript downloads and hydrates it. On a slow connection near Rohtak, that gap can be several seconds.

So use real elements: a <button> or <a href> is announced correctly while it waits. For forms, a <form> whose action is a Server Action can be submitted by the browser before hydration finishes (React calls this progressive enhancement), unlike a click handler that calls fetch. See Server Actions & Forms.

next/script strategies decide where the tag lands

StrategyWhere the <script> appears
beforeInteractiveIn the server HTML, inside <head>; allowed only in the root layout
afterInteractive (default)Inserted by JavaScript after some hydration
lazyOnloadInserted during browser idle time, after other resources
workerExperimental and not supported in the App Router

Our layout used lazyOnload for /chat-widget.js. The built HTML has no <script> tag for it; only the RSC payload mentions it, and JavaScript adds the tag later. So "View source" never shows such widgets: check their markup in DevTools. Plain HTML script loading is in Script Loading: Async & Defer.

Invalid nesting breaks hydration

Hydration compares what React expects with the DOM the browser built. As HTML in Templates & Frameworks showed, the parser repairs some invalid nesting, so the two stop matching. Here is a page that does it:

React TSX
// app/bad/page.tsx
export default function Bad() {
  return (
    <>
      <h1>Bad nesting</h1>
      <p>Total: <div>₹500</div></p>
    </>
  );
}

next build finished without any error, and the HTML file contains exactly what we wrote: <p>Total: <div>₹500</div></p>. The problem appears only in the browser. Opening the page with next dev printed these two messages in the console (shortened):

Output
In HTML, <div> cannot be a descendant of <p>.
This will cause a hydration error.

Error: Hydration failed because the server rendered HTML didn't match the client.
As a result this tree will be regenerated on the client.

React then renders that tree again on the client, losing the benefit of server rendering. The error also lists other causes, such as Date.now() in render, locale-dependent dates and browser extensions. Invalid nesting is the one you fix with HTML knowledge.

The example below rebuilds React's check in a few lines. It parses the server HTML the way the browser does, then walks the tree React expected and stops at the first difference.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Mini Hydration Check</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    pre { background: #f4f4f4; padding: 8px; white-space: pre-wrap; }
  </style>
</head>
<body>
  <h1>Does the browser tree match React's tree?</h1>
  <pre id="out"></pre>

  <script>
    // What React expects: [tag, ...children]; strings are text
    const pages = {
      "Bad page": {
        expected: ["main", ["h1", "Bad nesting"], ["p", "Total: ", ["div", "₹500"]]],
        html: '<main><h1>Bad nesting</h1><p>Total: <div>₹500</div></p></main>'
      },
      "Fixed page": {
        expected: ["main", ["h1", "Bad nesting"], ["p", "Total: ", ["span", "₹500"]]],
        html: '<main><h1>Bad nesting</h1><p>Total: <span>₹500</span></p></main>'
      }
    };

    function check(expected, node, path) {
      const [tag, ...kids] = expected;
      if (!node || node.localName !== tag) {
        return "Mismatch at " + path + ": expected <" + tag + ">, found " +
          (node ? "<" + node.localName + ">" : "nothing");
      }
      const wanted = kids.filter((k) => Array.isArray(k));
      const actual = [...node.children];
      for (let i = 0; i < wanted.length; i++) {
        const result = check(wanted[i], actual[i], path + " > " + tag);
        if (result) return result;
      }
      if (actual.length !== wanted.length) {
        return "Mismatch inside <" + tag + ">: expected " + wanted.length +
          " child elements, found " + actual.length;
      }
      return "";
    }

    let text = "";
    for (const [name, page] of Object.entries(pages)) {
      const doc = new DOMParser().parseFromString(page.html, "text/html");
      const main = doc.querySelector("main");
      text += name + "\n  Browser built: " + main.outerHTML + "\n  " +
        (check(page.expected, main, "body") || "Trees match, hydration can reuse the HTML") + "\n\n";
    }
    document.querySelector("#out").textContent = text;
  </script>
</body>
</html>

For the bad page you see <p>Total: </p><div>₹500</div><p></p> and a mismatch: the <div> React expected inside the <p> has moved out. The fixed page with <span> matches.

Live coding: audit the HTML Next.js sent

Step 5: copy a built page into a plain HTML file and let a script check it. Below is our home page output with the scripts removed and the image URLs swapped for a sample image. Later, paste your own project's output into the <body>.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en-IN">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Annapurna Tiffins</title>
  <meta name="description" content="Home-style tiffins delivered across Pune.">
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    img { max-width: 100%; height: auto; }
    #report { background: #eef6ee; padding: 8px; white-space: pre-wrap; }
  </style>
</head>
<body>
  <div hidden=""><!--$--><!--/$--></div>
  <a href="#main" class="skip">Skip to content</a>
  <header><nav aria-label="Main"><a href="/">Home</a><a href="/menu">Menu</a></nav></header>
  <main id="main"><h1>Today's thali</h1><img alt="Steel plate with dal, rice, two rotis and sabzi" loading="lazy" width="800" height="500" decoding="async" data-nimg="1" style="color:transparent" srcset="https://course.ethicscomputer.in/assets/samples/landscape-400.svg 1x, https://course.ethicscomputer.in/assets/samples/landscape.svg 2x" src="https://course.ethicscomputer.in/assets/samples/landscape.svg"><p>Price: ₹120</p><button type="button">Add to order (<!-- -->0<!-- -->)</button></main>
  <footer>Pune, Maharashtra</footer>

  <pre id="report"></pre>
  <script>
    const lines = [];
    const ok = (good, text) => lines.push((good ? "PASS  " : "FAIL  ") + text);
    ok(document.documentElement.lang !== "", "html has lang: " + document.documentElement.lang);
    ok(document.title.trim() !== "", "title: " + document.title);
    ok(!!document.querySelector('meta[name="description"]'), "meta description present");
    ok(document.querySelectorAll("main").length === 1, "exactly one main");
    ok(document.querySelectorAll("h1").length === 1, "exactly one h1");
    const skip = document.querySelector('a[href^="#"]');
    ok(skip && document.querySelector(skip.getAttribute("href")), "skip link target exists");
    for (const a of document.querySelectorAll("nav a")) ok(a.hasAttribute("href"), "nav link has href: " + a.textContent);
    for (const img of document.querySelectorAll("main img")) {
      ok(img.hasAttribute("alt"), "img has alt");
      ok(img.hasAttribute("width") && img.hasAttribute("height"), "img has width and height");
    }
    for (const b of document.querySelectorAll("button")) ok(b.type === "button" || b.closest("form"), "button type is clear: " + b.textContent);
    document.querySelector("#report").textContent = lines.join("\n");
  </script>
</body>
</html>

Every line should say PASS. Now delete lang, add a second <main> or remove the image's alt, and run again to see a FAIL. Accessibility Automated Testing takes this further.

Common mistakes

  • A second <main> in a page when the layout already has one.
  • Hand-written <title> tags in components. Use metadata or generateMetadata.
  • router.push on a <div> instead of <Link>, or a <button> inside a <Link>.
  • Lazy loading the hero image. Use preload, loading="eager" or fetchPriority="high".
  • Block elements inside <p> in any component, which breaks hydration.

Interview questions

1. Where do <html> and <body> come from in a Next.js App Router app?

From the root layout, app/layout.tsx, which must render both. It is the right place for lang, the skip link and landmarks shared by every page. Next.js adds <head> content itself, including the charset and viewport meta tags.

2. How do you set a page title and description in the App Router?

Export a metadata object, or a generateMetadata function when the values depend on params, search params or fetched data. Both are allowed only in Server Components. A title.template in a layout adds a suffix such as the site name to child titles.

3. What HTML does next/link produce, and why does that matter?

A plain <a href> element. Crawlers can follow it, it works with the keyboard and middle-click, and assistive technology announces it as a link. Next.js adds client-side navigation and prefetching on top.

4. Does a Client Component appear in the server HTML?

Yes. On the first request it is rendered to HTML on the server with its initial state, then hydrated in the browser. Until then its event handlers do nothing, so use real buttons, links and Server Action forms.

5. Why can invalid HTML nesting cause a hydration error even when the build passes?

The server sends the HTML as written. The browser's parser then repairs it, for example closing a <p> before a <div>. React expects its own tree, finds a different DOM, reports a hydration mismatch and re-renders that part on the client.

Key points

  • Next.js components become ordinary HTML; check that output, not the .tsx files.
  • The root layout writes <html lang> and <body>; Next.js adds charset and viewport tags automatically.
  • metadata and generateMetadata produce <title>, <meta> and <link> tags; set metadataBase for absolute URLs.
  • next/link outputs <a href>; next/image outputs <img> with width, height, srcset and loading="lazy" unless you use preload.
  • Server and Client Components both arrive as HTML first; Client Components work only after hydration.
  • beforeInteractive scripts are in the server HTML; the other strategies insert scripts later with JavaScript.
  • Invalid nesting passes the build but fails hydration in the browser.

Exercise

Meera's bakery site in Kochi has this root layout body: <body><div className="page"><Link href="/cakes"><button>Cakes</button></Link><main>{children}</main></div></body>, and the home page component returns <main><h1>Fresh cakes</h1><p>Order now: <div>Call 0484 000000</div></p></main>. The <html> element has no lang. List every HTML problem in the output, then rewrite the layout and the page.

Show solution
React TSX
// app/layout.tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en-IN">
      <body>
        <a href="#main">Skip to content</a>
        <header>
          <nav aria-label="Main">
            <Link href="/cakes">Cakes</Link>
          </nav>
        </header>
        <main id="main">{children}</main>
      </body>
    </html>
  );
}

// app/page.tsx
export default function Home() {
  return (
    <>
      <h1>Fresh cakes</h1>
      <p>Order now: <span>Call 0484 000000</span></p>
    </>
  );
}

The original had no lang, a button inside a link, two <main> elements, no navigation landmark, and a <div> inside <p>, which causes a hydration error. The fix keeps one <main> in the layout, uses a plain link and swaps the <div> for a <span>.

Quick Quiz

1. Which tags does Next.js add to every page even if you define no metadata?

2. What does <Link href="/menu">Menu</Link> render?

3. A <Script strategy="lazyOnload"> is in the root layout. Where is its tag in the server HTML?

4. In Next.js 16, which prop replaces the deprecated priority on next/image?

Learn HTML with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call