Course map
Stage 1: App Router Foundations
Stage 2: The Rendering Model
Stage 3: Data, Caching and Mutations
Stage 4: Full-Stack Next.js
Stage 5: Production and Specialization

Part 04 / Stage 1

Metadata, fonts and static assets

Goal: Give Apna Bazaar a real <title>/description on every page with the static metadata export and generateMetadata, understand the font setup create-next-app already gave this harness and scope a second font to one section with next/font, serve a real static asset from public/, render it with next/image, and wire up a favicon and an Open Graph image. Time: ~4 h · Level: 🟢 finished Part 3, comfortable with nested layouts and dynamic segments

What you will learn

  • Static metadata (export const metadata) at a layout and at a page, and how title templates cascade across nested layouts
  • generateMetadata for a title and description that depend on data — reusing the same dynamic segment Part 2 and Part 3 already built on
  • next/font/google, explained for the first time against the font setup create-next-app silently gave this harness back in Part 1
  • Fonts scoped to one component, proven by comparing the real Link preload headers on two different pages
  • public/ as the static-files folder: a real file, served at the site's root, with no route needed
  • next/image's automatic sizing, lazy loading and on-demand resizing, against a real local image
  • Favicons and Open Graph images as file conventions, not configuration

Topics in this part

Practice

Every exercise edits or adds files under harness/app/ or harness/public/, runs a real command against them, and then restores the harness to the exact state Part 4's README ends on. Copy the exact commands you ran and their real output into your own notes; do not type output from memory.

This harness is shared across every part in this course (Part 1, section 9, explains why), so a next build's route table may show routes you didn't add yourself if other work is also in progress elsewhere in app/. Don't worry about those — grep for the specific route each exercise below asks about, the same way the commands here do, rather than reading the whole table.


Exercise 1: Give the home page its own title

Scenario: The README's section 1 found that /store's title falls through to the root layout's template ("Apna Bazaar | Next.js Step by Step"), because the store layout's own default isn't formatted by its own template. Prove the fix: give the home page an explicit title of its own. What to do: Add export const metadata: Metadata = { title: "Home" }; to app/store/(shop)/page.tsx.

Sample output (run for real against this course's harness):

$ curl -s http://localhost:PORT/store | grep -o '<title>[^<]*</title>'
<title>Home | Apna Bazaar</title>

Now the store layout's template formats it, not the root's — a plain string title always uses the nearest ancestor's template; only a layout's own default skips past its own template. Remove the metadata export afterward — this harness's canonical home page has none, relying on the store layout's default instead. 💡 Hint: This is the exact contrast the README's section 1 built toward — compare this result side by side with the un-edited /store output quoted there.


Exercise 2: generateMetadata for search results

Scenario: /store/search/[...terms] has no metadata at all yet — every search result shares the store layout's default title. What to do: Add generateMetadata to app/store/(shop)/search/[...terms]/page.tsx, returning { title: Search: ${terms.join(" ")} }.

Sample output (run for real against this course's harness):

$ curl -s http://localhost:PORT/store/search/silk | grep -o '<title>[^<]*</title>'
<title>Search: silk | Apna Bazaar</title>
$ curl -s http://localhost:PORT/store/search/pottery | grep -o '<title>[^<]*</title>'
<title>Search: pottery | Apna Bazaar</title>

Remove the generateMetadata export afterward. 💡 Hint: Same shape as the README's section 2 — await params, then build a Metadata object from whatever it resolves to. This route is a catch-all, not a single [id], so terms is an array; join it before using it in a title string.


Exercise 3: A second file in public/

Scenario: Apna Bazaar wants a small logo mark, separate from the product photo section 5/6 already added. What to do: Add public/apna-bazaar-logo.svg (any small valid SVG) and confirm it's served directly.

Sample output (run for real against this course's harness):

$ curl -s -D - -o /dev/null http://localhost:PORT/apna-bazaar-logo.svg | grep -iE "^(HTTP|content-type|cache-control)"
HTTP/1.1 200 OK
Cache-Control: public, max-age=0
Content-Type: image/svg+xml

Delete the file afterward. 💡 Hint: No page.tsx, no route.ts, no import anywhere — this is section 5's whole point, reproduced with a second file instead of the first.


Exercise 4: Scope a font to a single page

Scenario: Section 4 scoped Poppins to every page under /store (via StoreNav, which renders on all of them). Scope a different font to just one page. What to do: In app/store/(info)/about/page.tsx, import a Google Font — Playfair_Display works — call it at module scope, and apply its .style.fontFamily to the page's <h1>.

Sample output (run for real against this course's harness):

$ curl -s -D - -o /dev/null http://localhost:PORT/store/about | grep -i "^Link:" | grep -o "font/woff2" | wc -l
       4
$ curl -s -D - -o /dev/null http://localhost:PORT/store/products | grep -i "^Link:" | grep -o "font/woff2" | wc -l
       3

Four font files preload on /store/about (the two root Geist fonts, Poppins from StoreNav, and this new one) against three everywhere else under /store that doesn't import it. Remove the import and the inline style afterward. 💡 Hint: Counting preloaded font files, rather than reading @font-face rules by eye, is a fast way to prove a font is — or isn't — scoped the way you think it is.


Exercise 5: A more specific Open Graph image wins

Scenario: The installed package's own metadata guide says a more specific opengraph-image file "will take precedence over any OG images above it in the folder structure." Section 7 only built one, at app/store/. Add a second, deeper one, and confirm only the deeper pages pick it up. What to do: Add app/store/(shop)/products/opengraph-image.tsx, using ImageResponse the same way app/store/opengraph-image.tsx does, with different content (a different background color is enough to tell them apart).

Sample output (run for real against this course's harness):

$ curl -s http://localhost:PORT/store/products | grep -o '<meta property="og:image" content="[^"]*"'
<meta property="og:image" content="http://localhost:PORT/store/products/opengraph-image-<hash>?<hash>"
$ curl -s http://localhost:PORT/store/about | grep -o '<meta property="og:image" content="[^"]*"'
<meta property="og:image" content="http://localhost:PORT/store/opengraph-image?f9bc1875e9d3494b"

/store/products picked up the new, more specific file — note that Next.js gives it a generated, hashed path segment of its own (opengraph-image-<hash>, not a plain /store/products/opengraph-image) rather than reusing the parent's path — while /store/about, outside the products/ folder, still resolves to the original, higher-level file. Delete app/store/(shop)/products/opengraph-image.tsx afterward. 💡 Hint: Don't guess the more specific image's URL by hand — curl the page's own og:image tag and use whatever URL actually appears there, exactly like the sample output above does.


Exercise 6: Remove metadataBase and watch the fallback

Scenario: Section 7 showed og:image resolving against metadataBase under a production build. Remove metadataBase and see what Next.js does instead. What to do: Delete the metadataBase line from app/layout.tsx's metadata export. Run next build and read the warning. Then run next build && next start on some port other than 3000 and curl any storefront page's og:image.

Sample output (run for real against this course's harness):

$ npm run build
...
⚠ metadataBase property in metadata export is not set for resolving social open graph or twitter images, using "http://localhost:3000". See https://nextjs.org/docs/app/api-reference/functions/generate-metadata#metadatabase
$ npm run start -- -p 3115
...
$ curl -s http://localhost:3115/store/about | grep -o '<meta property="og:image" content="[^"]*"'
<meta property="og:image" content="http://localhost:3000/store/opengraph-image?f9bc1875e9d3494b"

The server is genuinely running on port 3115, but the og:image URL hardcodes http://localhost:3000 anyway — Next.js's own documented fallback, not the real request's actual origin. A wrong og:image URL served in production (pointing at a port or host nothing is listening on) is exactly the bug metadataBase exists to prevent. Restore the metadataBase line afterward. 💡 Hint: The warning names the exact fallback value before you even test it — read warnings a build prints, they usually say exactly what's about to go wrong.


Exercise 7: Break generateMetadata by forgetting to await params

Scenario: Part 2 proved that reading params synchronously is a type error. Prove the same holds inside generateMetadata, not just inside a page component. What to do: In app/store/(shop)/products/[id]/page.tsx's generateMetadata function, change const { id } = await params; to const { id } = params;. Run next build.

Sample output (run for real against this course's harness):

$ npm run build
...
app/store/(shop)/products/[id]/page.tsx(22,11): error TS2339: Property 'id' does not exist on type 'Promise<{ id: string; }>'.
Failed to type check.

The exact same class of error Part 2 showed for a page's own params — PageProps's generated type makes params a Promise wherever it's used, generateMetadata included, and TypeScript, not a runtime crash, is what catches it here. Restore the await afterward, and confirm next build is green again. 💡 Hint: generateMetadata and the page's own default export both receive the exact same { params } shape — there is nothing special about metadata that exempts it from the "params is a Promise" rule.

Show the solutions for Part 4 (7 files)

solutions/ex01.tsx

// Solution to Exercise 1. Add this export to
// harness/app/store/(shop)/page.tsx, alongside its existing imports and
// default export (don't replace the whole file — just add the export).
import type { Metadata } from "next";

export const metadata: Metadata = {
  title: "Home",
};

// After adding it:
// $ curl -s http://localhost:PORT/store | grep -o '<title>[^<]*</title>'
// <title>Home | Apna Bazaar</title>
//
// Remove the export afterward — this harness's canonical home page has no
// metadata export of its own, relying on app/store/layout.tsx's `default`
// title instead.

solutions/ex02.tsx

// Solution to Exercise 2. Add this export to
// harness/app/store/(shop)/search/[...terms]/page.tsx, above the existing
// generateStaticParams export.
import type { Metadata } from "next";

export async function generateMetadata({ params }: PageProps<"/store/search/[...terms]">): Promise<Metadata> {
  const { terms } = await params;
  return { title: `Search: ${terms.join(" ")}` };
}

// After adding it:
// $ curl -s http://localhost:PORT/store/search/silk | grep -o '<title>[^<]*</title>'
// <title>Search: silk | Apna Bazaar</title>
// $ curl -s http://localhost:PORT/store/search/pottery | grep -o '<title>[^<]*</title>'
// <title>Search: pottery | Apna Bazaar</title>
//
// Remove the export afterward — this harness's canonical search page has
// no metadata of its own.

solutions/ex03.md

# Solution to Exercise 3: a second file in `public/`

Any small, valid SVG works — for example:

```svg
<!-- harness/public/apna-bazaar-logo.svg -->
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">
  <circle cx="32" cy="32" r="30" fill="#1f5c8c" />
  <text x="32" y="40" font-size="24" text-anchor="middle" fill="#fff" font-family="system-ui">AB</text>
</svg>
```

Curled directly, no route or import required:
```text
$ curl -s -D - -o /dev/null http://localhost:PORT/apna-bazaar-logo.svg | grep -iE "^(HTTP|content-type|cache-control)"
HTTP/1.1 200 OK
Cache-Control: public, max-age=0
Content-Type: image/svg+xml
```

Same `Cache-Control: public, max-age=0` the README's section 5 found for `apna-bazaar-vase.png` — any file dropped into `public/` gets this treatment, not just the one this part happened to build first.

Delete the file afterward — it is not part of this part's canonical harness state.

solutions/ex04.md

# Solution to Exercise 4: scope a font to a single page

In `harness/app/store/(info)/about/page.tsx`, add the font import and apply it to the heading only:

```tsx
import { Playfair_Display } from "next/font/google";

const playfair = Playfair_Display({ subsets: ["latin"], weight: "700" });

// ...
<h1 style={{ fontFamily: playfair.style.fontFamily }}>About Apna Bazaar</h1>
```

Count the font preloads on two different pages:
```text
$ curl -s -D - -o /dev/null http://localhost:PORT/store/about | grep -i "^Link:" | grep -o "font/woff2" | wc -l
       4
$ curl -s -D - -o /dev/null http://localhost:PORT/store/products | grep -i "^Link:" | grep -o "font/woff2" | wc -l
       3
```

`/store/about` gets four: the two Geist fonts from the root layout, Poppins from `StoreNav` (every `/store/*` page gets these three), and now Playfair Display, present only because this one page imports it. `/store/products` — which renders the same `StoreNav` but never imports Playfair Display — stays at three.

Remove the import and the inline `style` prop afterward, restoring the plain `<h1>About Apna Bazaar</h1>`.

solutions/ex05.tsx

// Solution to Exercise 5. Drop in as
// harness/app/store/(shop)/products/opengraph-image.tsx.
import { ImageResponse } from "next/og";

export const alt = "Apna Bazaar catalog";
export const size = { width: 1200, height: 630 };
export const contentType = "image/png";

export default function ProductsOgImage() {
  return new ImageResponse(
    (
      <div
        style={{
          width: "100%",
          height: "100%",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          background: "#a33",
          color: "white",
          fontSize: 96,
        }}
      >
        Full Catalog
      </div>
    ),
    size,
  );
}

// After adding it:
// $ curl -s http://localhost:PORT/store/products | grep -o '<meta property="og:image" content="[^"]*"'
// <meta property="og:image" content="http://localhost:PORT/store/products/opengraph-image-<hash>?<hash>"
// $ curl -s http://localhost:PORT/store/about | grep -o '<meta property="og:image" content="[^"]*"'
// <meta property="og:image" content="http://localhost:PORT/store/opengraph-image?f9bc1875e9d3494b"
//
// /store/products picked up this new, more specific file (note the
// generated, hashed path segment Next.js gives it — not a plain
// /store/products/opengraph-image). /store/about, outside the products/
// folder, still resolves to app/store/opengraph-image.tsx.
//
// Delete this file afterward — it is not part of this part's canonical
// harness state.

solutions/ex06.md

# Solution to Exercise 6: remove `metadataBase` and watch the fallback

Delete the `metadataBase` line from `harness/app/layout.tsx`'s `metadata` export:
```diff
 export const metadata: Metadata = {
-  metadataBase: new URL("https://nextjs-step-by-step.test"),
   title: { template: "%s | Next.js Step by Step", default: "Next.js Step by Step" },
   description: "A hands-on Next.js 16 course, built and verified one part at a time.",
 };
```

`next build` warns immediately, naming the exact fallback it's about to use:
```text
$ npm run build
...
⚠ metadataBase property in metadata export is not set for resolving social open graph or twitter images, using "http://localhost:3000". See https://nextjs.org/docs/app/api-reference/functions/generate-metadata#metadatabase
```

Start a real production server on a port that is **not** 3000, and curl any storefront page's `og:image`:
```text
$ npm run start -- -p 3115
...
$ curl -s http://localhost:3115/store/about | grep -o '<meta property="og:image" content="[^"]*"'
<meta property="og:image" content="http://localhost:3000/store/opengraph-image?f9bc1875e9d3494b"
```

The server is really listening on `3115`, but the `og:image` tag points at `http://localhost:3000` regardless — Next.js's hardcoded fallback when no `metadataBase` is set, not a guess at the real request's host or port. Shared to a chat app or crawler, this URL would 404 or hit nothing at all. This is exactly the failure `metadataBase` prevents, and exactly why the README's section 7 insists on testing metadata URLs against a real `next start`, not only `next dev` (where the dev server's own origin happens to paper over the problem by coincidence).

Restore the `metadataBase` line afterward and confirm `og:image` resolves to `https://nextjs-step-by-step.test/...` again.

solutions/ex07.md

# Solution to Exercise 7: break `generateMetadata` by forgetting to `await params`

In `harness/app/store/(shop)/products/[id]/page.tsx`, inside `generateMetadata` only (leave the page's own default export untouched):
```diff
 export async function generateMetadata({ params }: PageProps<"/store/products/[id]">): Promise<Metadata> {
-  const { id } = await params;
+  const { id } = params;
   const product = findProduct(id);
```

```text
$ npm run build
...
app/store/(shop)/products/[id]/page.tsx(22,11): error TS2339: Property 'id' does not exist on type 'Promise<{ id: string; }>'.
Failed to type check.
```

The generated `PageProps<"/store/products/[id]">` type makes `params` a `Promise<{ id: string }>` wherever it's destructured — inside the page's default export (Part 2, section 4) and inside `generateMetadata`, identically. Both receive the same `{ params }` shape from the same route, so there is nothing metadata-specific that would exempt this function from the rule.

Restore the `await` afterward:
```tsx
export async function generateMetadata({ params }: PageProps<"/store/products/[id]">): Promise<Metadata> {
  const { id } = await params;
  const product = findProduct(id);
```
and confirm `npm run build` is green again.

Common mistakes

Mistake Why it is wrong Fix
Expecting a nested layout's title.default to run through its own title.template Proven in section 1: /store's title came out as "Apna Bazaar | Next.js Step by Step", formatted by the root's template, not the store layout's own A template only formats titles from segments below the layout that defines it, never that layout's own default
Trusting generateMetadata's <head> output for an id outside generateStaticParams Section 2 showed the shell's inherited default title instead of the function's own "not found" branch, on both next dev and a production next start Keep every real, linkable id in generateStaticParams; treat an unlisted id's own metadata as unreliable until it is
Assuming next/font/google phones home to Google at runtime The installed package's guide and this harness's own headers say otherwise — zero fonts.googleapis.com references, fonts preloaded from this app's own /_next/static/media/ Trust the self-hosting claim; verify it yourself with grep -c "fonts.googleapis.com" on your own pages if in doubt
Giving a public/ image explicit width/height by hand A static import already gets Next.js to read the real file and infer both — hand-typed values can silently drift from the actual file Prefer import img from "../path/to/file.png" over a bare string path when the file lives in your project
Testing metadataBase resolution only under next dev Section 7 found two different og:image URLs for the exact same code — the dev server's own origin versus the real metadataBase Always confirm absolute-URL metadata (og:image, canonical URLs) against a real next build && next start, not only next dev
Assuming every real route appears in AppRoutes File-based metadata routes (opengraph-image.tsx here) show up in the build's route table but not in the typed route list, confirmed in section 8 Use AppRoutes/PageProps for pages you link to; don't expect it to enumerate every URL the server can answer

Quick recap

  • Static metadata cascades through nested layouts via title.template/title.default; a leaf's own plain string title is formatted by the nearest ancestor's template, while a layout's own default bubbles past its own template to the next one up.
  • generateMetadata earns its keep exactly where generateStaticParams already did — data-dependent pages — and is only as reliable in <head> as the params list backing it.
  • next/font/google self-hosts a font with zero runtime requests to Google, confirmed by this harness's own response headers; fonts are scoped to whichever component imports them, proven by comparing two pages' Link preload headers.
  • public/ serves any file verbatim from the site's root, with a max-age=0 cache header, because its URL never changes even if the file's contents do.
  • next/image, given a static import, infers real width/height, lazy-loads by default, and serves resized, format-converted (WebP) variants through /_next/image — all independently confirmed against a real local file, not a remote one.
  • Favicons and Open Graph images are file conventions (favicon.ico, opengraph-image.tsx) scoped by folder position, exactly like every other special filename this course has met; metadataBase only gets used for absolute URLs under a real production build, not under next dev.

Checklist

  • I added a static metadata export to a layout and a page, and traced which ancestor's title template actually formatted the result.
  • I reproduced the one case where a layout's own default title skips its own template and gets formatted by the next ancestor's instead.
  • I converted a dynamic page's metadata to generateMetadata and confirmed it works for a prerendered id — and found out for myself where it doesn't, for an unlisted one.
  • I can explain, from this harness's own response headers, why next/font/google doesn't mean "load this font from Google every time."
  • I scoped a font to one component and proved it with a header comparison between two real pages, not just by reading the docs.
  • I served a real file from public/ and read its cache header.
  • I rendered that same file with next/image via a static import and fetched a resized, WebP-converted variant from /_next/image myself.
  • I confirmed a favicon and a generated Open Graph image both work, and I know why og:image's URL differs between next dev and next start.

Search the guide