Layouts, Templates and Metadata
A version-qualified path through the Next.js App Router: server components, client boundaries, data fetching, caching layers, streaming, error handling, proxy, images, performance, testing and deployment, with the Next.js 15 and 16 behavior changes called out where they matter.
What you will be able to do
#- Structure nested layouts and explain what persists across child navigations.
- Choose between layout.tsx and template.tsx and justify the choice.
- Export static and dynamic metadata, including the separate viewport export.
Overview
#Layouts persist, templates remount
layout.tsx wraps its child segments and does not re-render when the user navigates between children, so state inside a layout, like a scroll position or an open sidebar, survives navigation. Every layout receives children and nests: the root layout renders <html> and <body> exactly once, and each nested layout wraps its own subtree inside the parent's output.
template.tsx looks like a layout but remounts its children on every navigation, so component state resets and enter animations replay. Use it when each navigation should genuinely start fresh; use layouts for shared chrome.
Metadata
Export a metadata object for static values or a generateMetadata function for values that depend on data:
// app/blog/[slug]/page.tsx
export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params;
const post = await getPost(slug);
return { title: post.title, description: post.summary };
}
Set a title template once in the root layout, title: { default: 'My App', template: '%s | My App' }, and child segments inherit it. Since Next.js 14, viewport concerns moved out of metadata into a separate viewport export: export const viewport: Viewport = { themeColor: '#0a0a0a' }. Putting themeColor inside the metadata object is deprecated.
What metadata can read
generateMetadata runs on the server for every request that renders the route dynamically, or once at build time for static routes. It can await the same data functions the page uses. To avoid fetching twice, wrap the shared read in React's cache() so the page and its metadata dedupe to one call per request. Under Next.js 16 Cache Components, uncached external reads inside generateMetadata are flagged by prerender validation when the rest of the route is prerenderable, so cache the read with use cache or move it inside a Suspense boundary.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
Root layout exports title: { default: 'Shop', template: '%s | Shop' }. app/products/page.tsx exports metadata = { title: 'Products' }. What is the document title of /products?
Exercise 2Explain
Your team debates layout.tsx versus template.tsx for a dashboard sidebar with an input that filters a list. Which do you choose and why? What changes if the input must reset on every navigation?
Reveal the reference answer
reference.textChoose layout.tsx. The sidebar wraps child pages, and navigation between children should not unmount it, so the filter input keeps its value and focus while the content area changes. If the product decision is that every navigation starts a fresh session view, template.tsx remounts children each time and the input state resets with the remount. The cost of template is losing any state you wanted to keep, so the choice is a product decision expressed through a file convention.Authored expected output: layout.tsx for persistence, template.tsx when remounting is the desired behavior.
The two files differ in exactly one behavior: remounting on navigation.
Exercise 3Implement
Write app/posts/[slug]/page.tsx metadata: generateMetadata awaits params, fetches the post through a shared cached getPost function, and returns title and description. Show the React cache() wrapper too.
starter.tsx// lib/data.ts // TODO: export getPost wrapped in React cache // app/posts/[slug]/page.tsx // TODO: export generateMetadata using getPostReveal the reference answer
reference.tsx// lib/data.ts import { cache } from 'react'; export const getPost = cache(async (slug: string) => { const res = await fetch(`https://api.example.com/posts/${slug}`); if (!res.ok) return null; return res.json(); }); // app/posts/[slug]/page.tsx import { getPost } from '@/lib/data'; export async function generateMetadata({ params, }: { params: Promise<{ slug: string }>; }) { const { slug } = await params; const post = await getPost(slug); if (!post) return { title: 'Post not found' }; return { title: post.title, description: post.summary }; }Authored expected output: One fetch per request serves both metadata and the page.
React cache() dedupes within a single server render, which is exactly the metadata plus page case.
Exercise 4Debug
This nested layout breaks the page with a hydration or nesting error. Find and fix the problem. // app/dashboard/layout.tsx export default function DashboardLayout({ children }: { children: React.ReactNode }) { return ( <html> <body> <aside>Sidebar</aside> {children} </body> </html> ); }
starter.tsx// app/dashboard/layout.tsx export default function DashboardLayout({ children }: { children: React.ReactNode }) { return ( <html> <body> <aside>Sidebar</aside> {children} </body> </html> ); }Reveal the reference answer
reference.tsxNested layouts must not render html and body; only the root app/layout.tsx may. Replace the wrapper with a plain div: <section><aside>Sidebar</aside>{children}</section>. The document shell exists once at the root.Authored expected output: The dashboard renders its sidebar inside the existing root document.
Rendering a second html element produces invalid nested documents and hydration mismatches.
Exercise 5Test
Write a pure function applyTitleTemplate(template: string, title: string | null | undefined, fallback: string) that reproduces the metadata title template rule, then assert: template '%s | Shop' with title 'Products' gives 'Products | Shop'; with null gives 'Shop'; and template '%s' with 'About' gives 'About'.
starter.tsexport function applyTitleTemplate( template: string, title: string | null | undefined, fallback: string, ): string { // TODO }Reveal the reference answer
reference.tsexport function applyTitleTemplate( template: string, title: string | null | undefined, fallback: string, ): string { if (!title) return fallback; if (!template.includes('%s')) return title; return template.replace('%s', title); } // A template without the placeholder cannot interpolate, so the raw title wins.Authored expected output: All three assertions pass.
Encoding the rule once makes the template behavior testable without a browser.
Exercise 6Interview
An interviewer asks: how do you keep metadata and page data consistent without double fetching, and what changes under Cache Components in Next.js 16?
Reveal the reference answer
reference.textAnswer in two parts. Without Cache Components: define the shared read once in a module wrapped with React cache(), call it from both generateMetadata and the page, and React dedupes it to one execution per request. Under Cache Components in Next.js 16: prerender validation requires dynamic data access to be explicit, so either mark the shared read with use cache and optionally cacheTag for on-demand invalidation, or move the uncached read inside a Suspense boundary so it runs at request time while the prerendered shell ships. Also mention that generateMetadata runs per request for dynamic routes and at build time for static ones, which is why caching the read matters for build performance.Authored expected output: React cache() dedupe plus the Cache Components requirement to cache or suspend the read.
This question connects three lessons: metadata, data fetching and the new caching model.
Common misconceptions
#- Every layout needs html and body. Only the root layout renders them; nested layouts must not, or the HTML nests invalid documents.
- Layout state resets on navigation. Layouts persist across child navigations; template.tsx is the file that remounts.
- themeColor belongs in metadata. Since Next.js 14 it belongs in the separate viewport export.
- generateMetadata and the page always fetch twice. React cache() dedupes identical reads within one request.
Follow-up practice
#- nextjs-server-components
- nextjs-images-env-config
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.