AgendaViva has a home page and a header whose links still don't lead anywhere. In this lesson you'll give them somewhere to go: you'll create /events, /venues and the skeleton of /dashboard, and you'll separate the public section from the management area so that each one has its own visual frame.
To do it well, you need to understand exactly what a layout is: what it wraps, what it keeps when you navigate and what it can't know. Decisions that might seem arbitrary depend on that idea, such as why a layout doesn't receive the search params or why it can't be used to control access. Route groups round out the lesson: they let you distribute layouts without cluttering the URLs.
- The page: what belongs to each route
A page.tsx is always the leaf of its branch: the innermost part of the tree, the part that changes when you go from one URL to another. Its component can receive two props, params and searchParams, which are covered in the next lesson. By default it's a Server Component, so it can be declared async and fetch data.
Being able to be async doesn't mean it should be. Compare these two ways of writing the same page:
// A: the page waits
export default async function VenuesPage() {
const venues = await listVenues()
return <VenueList venues={venues} />
}
// B: the page composes and a child waits
export default function VenuesPage() {
return (
<>
<h1 className="text-3xl font-bold">Venues</h1>
<Suspense fallback={<p>Loading venues…</p>}>
<VenueList />
</Suspense>
</>
)
}Version A produces the error you saw in 01-04: there's uncached data outside a <Suspense>. Version B lets the heading be part of the shell, and only the list waits. With Cache Components, the rule of thumb is that the page composes and the waits are placed as far down as possible. The deeper the wait, the larger the part that can be prerendered.
There's one way to make version A valid: a loading.tsx file, which wraps the page in a <Suspense>. You'll see it in 02-04.
- Nested layouts
A layout.tsx wraps everything in its folder and below it. In children it receives the next level down: another, inner layout or the page. Layouts nest just like folders, without any of them importing the others.
// app/dashboard/layout.tsx
export default function DashboardLayout({ children }: LayoutProps<'/dashboard'>) {
return (
<div className="grid gap-8 md:grid-cols-[12rem_1fr]">
<DashboardMenu />
<div>{children}</div>
</div>
)
}LayoutProps<'/dashboard'> is the global type that Next.js generates from your folders. The argument is the layout's route, not the file's location. It includes children, params and, if there are any, the parallel route slots you'll see in 02-05.
2.1. What's kept when you navigate
When the user goes from /dashboard to /dashboard/events with a <Link>, the browser doesn't download the whole page again. Next.js compares the two routes, identifies the shared segments and requests only what changes. Shared layouts aren't rendered again.
flowchart TD
R["RootLayout<br/>kept"] --> P["DashboardLayout<br/>kept"]
P --> A["/dashboard<br/>page that gets hidden"]
P --> B["/dashboard/events<br/>page that arrives from the server"]
| Element | When navigating between sibling routes | When reloading the browser |
|---|---|---|
| Shared layout (server) | Doesn't run again | Runs |
| State of its client components | Kept | Lost |
| Position of a menu with its own scroll in the layout | Kept | Lost |
| Destination page | Rendered on the server | Rendered on the server |
| Origin page | Hidden, keeping its state | Doesn't exist |
The last row is specific to Cache Components. Instead of unmounting the page you leave, Next.js hides it with React's <Activity> component: it keeps its state and its DOM, and cleans up its effects. If you come back, it reappears just as you left it, with its fields filled in and its dropdowns open. Up to three routes are kept; older ones are discarded.
That's an advantage in a half-completed form and a surprise in a dialog that was left open. You'll take it into account in 02-05, when you build a modal.
2.2. What a layout can't know
If a layout doesn't run when you navigate, any URL data it read would become stale as soon as the user changed pages. That's where its restrictions come from:
| A layout… | Why | Alternative |
|---|---|---|
Doesn't receive searchParams |
They change without the layout running | The page's prop, or useSearchParams in a client component |
| Doesn't know the current route | Same reason | usePathname in a client component (02-03) |
Can't pass data to children |
children arrives already built |
Fetch the data in each place; how to avoid repetition is covered in 04-03 |
| Doesn't see the segments below it | They're in its children's hands | useSelectedLayoutSegment in a client component |
It does receive params, but only those of the dynamic segments from the root down to its folder.
And there's a security consequence. A layout that checks the session checks it once and doesn't do so again when navigating between its pages. It can decide what a menu shows; it can't be the only access control. Authorization will be placed next to the data, in 08-04.
2.3. Data inside a layout
A layout can fetch data, but under the same rules as a page: the waits go inside a <Suspense> of its own. The loading.tsx in its folder is no use to it, because in the hierarchy it sits inside the layout.
export default function LayoutWithNotices({ children }: LayoutProps<'/'>) {
return (
<>
<Suspense fallback={null}>
<TodaysNotices />
</Suspense>
{children}
</>
)
}Notice that the <Suspense> wraps only the notices. If it also wrapped children, every page on the site would wait for the notices.
- Template: a layout that mounts again
template.tsx is written just like a layout and sits between the layout and whatever is below it. The difference is that Next.js gives it a different key depending on the segment: when the segment at its level changes, React unmounts it and mounts a new one.
layout.tsx |
template.tsx |
|
|---|---|---|
| When navigating between sibling routes | Stays | Mounts again |
| State of the client components it contains | Kept | Reset |
useEffect in those components |
Doesn't run again | Runs again |
<Suspense> placed in it |
Shows the fallback only the first time | Shows it on every navigation |
| Only the search params change | Stays | Also stays |
The important nuance is at which level the change happens. An app/template.tsx mounts again when going from /events to /venues, because the first segment changes. It doesn't when going from /dashboard to /dashboard/events, because at its level the segment is still dashboard.
A good fit is a satisfaction survey at the bottom of each help topic, which should appear empty on every page:
// app/help/template.tsx (example; AgendaViva doesn't use it)
import { QuickSurvey } from './_components/quick-survey'
export default function HelpTemplate({ children }: { children: React.ReactNode }) {
return (
<>
{children}
<QuickSurvey />
</>
)
}In a layout, the answer selected in one topic would still be visible in the next one. Unless you have a need like this one, use layouts: remounting destroys state and recreates the DOM, which is exactly what the App Router tries to avoid. AgendaViva doesn't need any template.
- Route groups
Right now app/layout.tsx renders the public header and footer on every route. The organizer dashboard shouldn't show them: it needs a toolbar and a side menu. With what we've covered so far there's no way out, because the root layout reaches everything.
A route group is a folder whose name is in parentheses. It organizes, it can have its own layout.tsx and it doesn't appear in the URL:
It's useful for three things: organizing routes by area or team, giving a layout to some routes and not to others at the same level, and declaring several root layouts.
The rules to remember:
- Two groups can't resolve the same URL.
(public)/help/page.tsxand(dashboard)/help/page.tsxboth point to/helpand cause an error. - The name is just for you. Choose it by its purpose; changing it doesn't alter any URL.
- They can be nested and repeated at any level.
- They don't count in the types either. The
(public)layout corresponds to the/route, so its type isLayoutProps<'/'>.
4.1. Multiple root layouts
A root layout is one that has no other above it. If you remove app/layout.tsx and put one in each group, with its <html> and <body> tags, you'll have several. It's useful when two areas share neither global styles nor document attributes.
It comes at a price: navigating between routes with different root layouts triggers a full page load, with no client-side navigation. In addition, the home page has to live inside one of the groups, and the general 404 gets more complicated because there's no single layout to wrap it.
In AgendaViva, organizers often go from the dashboard to the public guide. We'll keep a single root layout, reduced to the document, and put the visual frame in each group.
- Reorganizing AgendaViva
This is where we're heading. Don't touch anything yet: notice that the home page moves to another folder and is still /.
app/
├── layout.tsx Document: html and body
├── globals.css
├── (public)/
│ ├── layout.tsx Header, main and footer
│ ├── page.tsx /
│ ├── events/
│ │ └── page.tsx /events
│ └── venues/
│ └── page.tsx /venues
└── (dashboard)/
├── layout.tsx Management bar and main
└── dashboard/
├── layout.tsx Organizer side menu
├── page.tsx /dashboard
├── _components/
│ └── dashboard-menu.tsx
└── events/
└── page.tsx /dashboard/eventsHaving (dashboard)/dashboard looks redundant. It isn't: the group provides the frame shared by the whole management area, which will include /admin, and the dashboard folder is the URL segment with the organizer's menu.
With the development server stopped, create the folders and move the home page:
mkdir -p "app/(public)/events" "app/(public)/venues"
mkdir -p "app/(dashboard)/dashboard/events" "app/(dashboard)/dashboard/_components"
mv app/page.tsx "app/(public)/page.tsx"The quotes are required: in the terminal, parentheses have a meaning of their own. The home page is moved, not copied; if app/page.tsx were left behind as well, two files would respond to /. You don't need to touch its imports, because they use the @/ alias.
5.1. The layouts
// app/layout.tsx
import type { Metadata } from 'next'
import { SITE_NAME } from '@/lib/site'
import './globals.css'
export const metadata: Metadata = {
title: SITE_NAME,
description: 'Concerts, theater, exhibitions and workshops in Vallenar del Río',
}
export default function RootLayout({ children }: LayoutProps<'/'>) {
return (
<html lang="en">
<body className="flex min-h-screen flex-col bg-slate-50 text-slate-900">
{children}
</body>
</html>
)
}// app/(public)/layout.tsx
import { Header } from '@/components/header'
import { Footer } from '@/components/footer'
export default function PublicLayout({ children }: LayoutProps<'/'>) {
return (
<>
<Header />
<main className="mx-auto w-full max-w-5xl flex-1 px-4 py-8">{children}</main>
<Footer />
</>
)
}// app/(dashboard)/layout.tsx
import Link from 'next/link'
import { SITE_NAME } from '@/lib/site'
export default function ManagementLayout({ children }: LayoutProps<'/'>) {
return (
<>
<header className="bg-slate-900 text-white">
<div className="mx-auto flex max-w-6xl justify-between px-4 py-3">
<span className="font-semibold">{SITE_NAME} · Management</span>
<Link href="/">View the public guide</Link>
</div>
</header>
<main className="mx-auto w-full max-w-6xl flex-1 px-4 py-8">{children}</main>
</>
)
}The <main> has moved down from the root layout into each group. The pages still don't write it. Each group decides its width and its header, while the document, the global styles and the default metadata stay in a single place.
What's missing is the inner level, with the organizer's menu:
// app/(dashboard)/dashboard/_components/dashboard-menu.tsx
import Link from 'next/link'
export function DashboardMenu() {
return (
<nav aria-label="Dashboard" className="flex flex-col gap-2">
<Link href="/dashboard">Overview</Link>
<Link href="/dashboard/events">My events</Link>
</nav>
)
}// app/(dashboard)/dashboard/layout.tsx
import { DashboardMenu } from './_components/dashboard-menu'
export default function DashboardLayout({ children }: LayoutProps<'/dashboard'>) {
return (
<div className="grid gap-8 md:grid-cols-[12rem_1fr]">
<DashboardMenu />
<div>{children}</div>
</div>
)
}DashboardMenu lives in a private folder because only this branch uses it, and it's imported with a relative path: colocated code moves along with its route. For shared code, @/ stays.
5.2. The pages
// app/(public)/events/page.tsx
import { Suspense } from 'react'
import { EventCard } from '@/components/event-card'
import { listEvents } from '@/lib/data/events'
export default function EventsPage() {
return (
<>
<h1 className="mb-6 text-3xl font-bold">Event guide</h1>
<Suspense fallback={<p>Loading the guide…</p>}>
<EventList />
</Suspense>
</>
)
}
async function EventList() {
const { events, total } = await listEvents()
return (
<>
<p className="mb-4 text-sm text-slate-600">{total} events</p>
<ul className="grid gap-4 sm:grid-cols-2">
{events.map((event) => (
<li key={event.id}>
<EventCard event={event} />
</li>
))}
</ul>
</>
)
}// app/(public)/venues/page.tsx
import { Suspense } from 'react'
import { listVenues } from '@/lib/data/venues'
export default function VenuesPage() {
return (
<>
<h1 className="mb-6 text-3xl font-bold">Venues</h1>
<Suspense fallback={<p>Loading venues…</p>}>
<VenueList />
</Suspense>
</>
)
}
async function VenueList() {
const venues = await listVenues()
return (
<ul className="grid gap-4 sm:grid-cols-3">
{venues.map((venue) => (
<li key={venue.id} className="rounded-lg border border-slate-200 bg-white p-4">
<h2 className="font-semibold">{venue.name}</h2>
<p className="text-sm text-slate-600">{venue.district}</p>
</li>
))}
</ul>
)
}For now, the dashboard pages are a skeleton with no data. Showing an organizer's events requires knowing who they are, and sessions arrive in module 8.
// app/(dashboard)/dashboard/page.tsx
export default function DashboardPage() {
return (
<>
<h1 className="text-2xl font-bold">Overview</h1>
<p className="mt-4">Your events' activity will show up here.</p>
</>
)
}// app/(dashboard)/dashboard/events/page.tsx
export default function DashboardEventsPage() {
return <h1 className="text-2xl font-bold">My events</h1>
}5.3. Checking the result
Run npm run typecheck, which regenerates the route types, and then npm run build. The routes with data are partial (◐) and the dashboard ones are fully static (○):
The group names don't appear. Now browse the site with npm run dev. When you go from /events to /venues, the header doesn't flicker: PublicLayout stays. When you go from /dashboard to the public guide the whole frame changes, but navigation is still client-side, because the root layout is shared.
Anyone can open /dashboard. That's expected: having a different folder or layout doesn't protect anything. Until module 8, the dashboard is public and only contains fictional data.
Common Mistakes and Tips
- Leaving
app/page.tsxbehind when creating(public)/page.tsx. Both respond to/and the build fails. - Writing
<html>and<body>in an inner layout when there's already a root one. Only the root one writes them. - Reading search params or the current route in a layout. It doesn't receive them, because they'd become stale.
- Using the layout as access control. It doesn't run on every navigation.
- Fetching uncached data in a layout and relying on
loading.tsx. The layout sits outside it; it needs its own<Suspense>. - Choosing
template.tsxjust in case. It destroys state on every segment change. Use it when that reset is what you're after. - Assuming a page's state is always lost when you leave. With Cache Components the page is hidden and keeps it; when you come back, it reappears.
- Forgetting the quotes when handling folders with parentheses in the terminal.
Exercises
Exercise 1: what runs
With the structure from this lesson, a user opens /dashboard by typing the URL, clicks "My events", then "View the public guide" and finally "Events". For each step, state which layouts are rendered on the server and which are kept.
Solution
| Step | Rendered | Kept |
|---|---|---|
Opens /dashboard |
RootLayout, ManagementLayout, DashboardLayout and the page |
None: it's a full load |
| "My events" | Only the /dashboard/events page |
All three layouts |
| "View the public guide" | PublicLayout and the home page |
RootLayout |
| "Events" | Only the /events page |
RootLayout and PublicLayout |
One remark: the prerendered parts may have been generated at build time or arrived through prefetching. "Rendered" means they're part of what the client needs to complete that step.
Exercise 2: sign-in pages without a header
/sign-in and /sign-up must be shown in a narrow, centered column, without the public header or footer. Create the structure and the necessary files, with pages that only have a heading.
Solution
// app/(account)/layout.tsx
export default function AccountLayout({ children }: LayoutProps<'/'>) {
return <main className="mx-auto w-full max-w-sm flex-1 px-4 py-16">{children}</main>
}
// app/(account)/sign-in/page.tsx
export default function SignInPage() {
return <h1 className="text-2xl font-bold">Sign in</h1>
}
// app/(account)/sign-up/page.tsx
export default function SignUpPage() {
return <h1 className="text-2xl font-bold">Sign up</h1>
}The group is a sibling of (public), not a child: if it were inside, it would inherit its header. This is a practice exercise; the final pages are built in 08-02.
Exercise 3: spotting the problems
A teammate proposes this structure, without app/layout.tsx. Point out the problems and what someone navigating from the guide to the dashboard will notice.
app/
├── page.tsx
├── (public)/
│ ├── layout.tsx with html and body
│ ├── events/page.tsx
│ └── help/page.tsx
└── (dashboard)/
├── layout.tsx with html and body
├── dashboard/page.tsx
└── help/page.tsxSolution
app/page.tsxhas no root layout above it. When you use several, the home page has to be inside a group, for example(public)/page.tsx.(public)/helpand(dashboard)/helpresolve the same URL,/help. One of them has to be renamed or moved todashboard/help.- Once that's fixed, the structure is valid, but going from
/eventsto/dashboardcrosses different root layouts: there will be a full load and the client state will be lost.
Conclusion
The page is what changes and the layout is what stays. Since a layout doesn't run on every navigation, it doesn't know the search params or the route, it doesn't pass data to its children and it can't be the only access barrier. template.tsx exists for the cases where you want exactly the opposite. Route groups distribute layouts without touching the URLs, and with them AgendaViva now separates its public section from the management area.
The lists show events and venues, but you can't open any of them or filter anything. In the next lesson, Dynamic Routes and Search Params, you'll create the event and venue pages with a dynamic segment and turn the URL into the state of the filters and pagination.
