The agendaviva project now starts up and you've gone through its configuration files. The essential part is still missing: how Next.js interprets what you put inside app/. In a convention-based framework, a file's name and location are part of the program. A page.tsx publishes a URL; the same code in view.tsx does nothing.
In this lesson you'll get an overview of the names that carry meaning, the rule that decides what gets published and what doesn't, the order in which special files are nested and the organization we'll follow for components, data and actions. It's a big-picture view: each special file is covered in depth in modules 2 and 7.
- The project root
The root holds folders that mean something to Next.js, configuration files and whatever folders you decide to add.
| Item | Meaning to Next.js |
|---|---|
app/ |
App Router routes |
public/ |
Static files served from the site root |
src/ |
Optional folder that can contain app/ (we don't use it) |
pages/ |
Pages Router routes (we don't use it) |
next.config.ts |
Configuration |
proxy.ts |
Code that runs before the route is resolved |
instrumentation.ts |
Observability bootstrap |
.env, .env.local, … |
Environment variables |
.next/ |
Build output; never edited or committed |
components/, lib/, actions/ |
None: they're our own choices |
The last row matters. Next.js doesn't dictate where to keep components or utilities. You'll see projects with ui/, utils/, features/ or server/: they're all valid as long as the team is consistent.
1.1. The public folder
A file in public/ is served from the site root without being transformed: public/posters/festival.pdf ends up at /posters/festival.pdf. It's the right place for downloadable documents and images whose URL must stay fixed.
Keep two things in mind. Since its content can change without the name changing, Next.js serves it with Cache-Control: public, max-age=0, meaning the browser always revalidates it. And everything you put there is public: never store files that require permissions in public/. For the site icon, robots.txt or the sitemap there are special files inside app/, which are preferable.
- Folders are segments, files publish
Inside app/, each folder is a URL segment. Folders nest just like the parts of the path:
app/
├── page.tsx /
├── events/
│ ├── page.tsx /events
│ └── [slug]/
│ └── page.tsx /events/riverside-quartet
├── dashboard/
│ └── events/
│ ├── page.tsx /dashboard/events
│ └── new/
│ └── page.tsx /dashboard/events/new
└── api/
└── events/
└── route.ts /api/eventsThe folder defines the segment, but it doesn't publish it. The full rule is:
A URL is reachable only if its folder contains a
page.tsxor aroute.ts.
In the tree above, the app/dashboard/ folder exists but has no page.tsx: visiting /dashboard returns a 404, even though /dashboard/events works. And what gets sent to the browser is only what that file returns, not the other files sitting next to it.
2.1. page.tsx and route.ts
page.tsxdefault-exports a component: the route's interface.route.tsexports functions named after HTTP methods (GET,POST…): an endpoint. It replaces the oldpages/api.
Both respond to the same URL, so they can't live in the same folder. That's why endpoints are usually grouped under app/api/, even though the name api is nothing special.
2.2. Folder names with meaning
Besides regular names, there are ways of writing a folder name that change how it's interpreted:
| Form | Name | Effect | Lesson |
|---|---|---|---|
events |
Static segment | Matches that exact text | 02-01 |
[slug] |
Dynamic segment | Accepts any value and passes it on as a parameter | 02-02 |
[...path] |
Catch-all | Accepts one or more segments | 02-02 |
[[...path]] |
Optional catch-all | Same, and also none | 02-02 |
(public) |
Route group | Organizes without adding anything to the URL | 02-01 |
_components |
Private folder | Excluded from routing | Section 4 |
@modal |
Parallel route slot | Passed to the layout as a prop | 02-05 |
(.)events |
Intercepting route | Shows another route without leaving the current one | 02-05 |
Don't memorize the table. It's enough that, when you see brackets, parentheses, an at sign or an underscore in a project, you know they aren't part of the URL as written.
- The special files
In any folder under app/ you can place files with a reserved role. They're all optional except the root layout.
| File | Role | Details |
|---|---|---|
layout.tsx |
Interface shared by the segment and its descendants; it doesn't re-render when navigating between them | 02-01 |
page.tsx |
The route's own interface; makes it public | 02-01 |
template.tsx |
Like a layout, but remounted on every navigation | 02-01 |
loading.tsx |
What's shown while the page waits for data | 02-04 |
error.tsx |
Fallback when something fails during rendering; must be a Client Component | 02-04 |
global-error.tsx |
Same, for failures in the root layout; only in app/ |
02-04 |
not-found.tsx |
The 404 interface | 02-04 |
default.tsx |
Fallback content for a parallel route; mandatory in its slots | 02-05 |
route.ts |
HTTP endpoint | 07-01 |
There are also metadata files with reserved names: favicon.ico, icon, apple-icon, opengraph-image, twitter-image, sitemap.ts, robots.ts and manifest.ts. They're covered in module 9. And proxy.ts doesn't go in app/ but in the project root, alongside it; it has had that name since version 16 (it used to be middleware.ts) and is covered in 07-02.
The supported extensions for interface files are .tsx, .jsx and .js; route uses .ts or .js. In this course, interface files will always be .tsx.
3.1. The root layout
app/layout.tsx is the only mandatory one. It wraps every route and is responsible for writing the <html> and <body> tags:
import type { Metadata } from 'next'
import './globals.css'
export const metadata: Metadata = {
title: 'AgendaViva',
description: 'The cultural events guide for Vallenar del Río',
}
export default function RootLayout({ children }: LayoutProps<'/'>) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}childrenis whatever sits below: the page or a more deeply nested layout.LayoutProps<'/'>is a global type that Next.js generates from your folders. It knows the parameters of the given route and isn't imported. For pages there'sPageProps.metadatadeclares the title and description. Don't write<title>or<meta>by hand: the framework inserts them into<head>and avoids duplicates. The details are in 09-03.globals.cssis imported here so its styles reach the whole site.
3.2. The default export
Next.js finds a special file's component through its default export. The function name is up to you and only helps with debugging; in this course we'll use descriptive names (EventsPage, DashboardLayout). All other components, the ones you import yourself, we'll export by name, which makes them easier to find and rename.
- Colocation and private folders
Since only page and route publish anything, you can keep any other file inside a route folder without it becoming a URL. This is called colocation:
app/events/ ├── page.tsx Publishes /events ├── filters.tsx Not a route ├── filters.test.tsx Not a route └── sort.ts Not a route
The advantage is proximity: whatever only /events uses sits right next to /events, and when you delete the route it goes with it. There are two risks: the folder fills up and the route structure becomes hard to see, and one of your names may clash with a reserved name, current or future. A loading.tsx you create for some other purpose will change the route's behavior.
Private folders solve both problems. When a folder's name starts with an underscore, the folder and everything in it are excluded from routing:
app/events/
├── page.tsx Publishes /events
└── _components/
├── filters.tsx
└── page.tsx Publishes NOTHING: the folder is privateThey aren't required for colocating files, but they separate interface logic from routing at a glance. If you ever needed a URL that really does start with an underscore, you'd name the folder with its URL-encoded form: %5Fname.
4.1. Not being a route doesn't make it secret
Don't confuse "not published as a route" with "doesn't reach the browser". A file colocated next to the page is included in the client JavaScript if a Client Component imports it. What decides whether code is sent to the browser is who imports it, not which folder it lives in. Lessons 03-03 and 03-05 explain that boundary and how to protect it.
- Rendering hierarchy
When a folder contains several special files, Next.js always nests them in the same order. For a segment that has all of them, the result is equivalent to this component tree:
// Simplified view of what Next.js mounts for a segment
<Layout>
<Template>
<ErrorBoundary fallback={<Error />}>
<Suspense fallback={<Loading />}>
<NotFoundBoundary fallback={<NotFound />}>
<Page />
</NotFoundBoundary>
</Suspense>
</ErrorBoundary>
</Template>
</Layout>Under the hood, error.tsx is a React error boundary; loading.tsx, a <Suspense>; and not-found.tsx, another error boundary for the specific case of a 404. Next.js doesn't invent new mechanisms: it uses React's and mounts them for you.
The order gives rise to rules you'd otherwise have to memorize:
error.tsxdoesn't catch failures in thelayout.tsxof its own folder, because the layout sits outside it. They're caught by theerror.tsxof the parent folder and, if the root layout fails, byglobal-error.tsx.loading.tsxdoesn't cover the waits of thelayout.tsxin its folder. If a layout reads uncached data, it needs its own<Suspense>; with Cache Components, leaving it out is an error.- While
loading.tsxis showing, the layout stays visible and usable.
5.1. Nesting across segments
The structure is recursive. A child segment's content takes the place of the page in its parent's tree. For /dashboard/events, with layouts at the root and in dashboard:
flowchart TD
A["app/layout.tsx<br/>html, body, header"] --> B["app/dashboard/layout.tsx<br/>sidebar menu"]
B --> C["app/dashboard/error.tsx"]
C --> D["app/dashboard/loading.tsx"]
D --> E["app/dashboard/events/page.tsx"]
When you navigate from /dashboard/events to /dashboard/events/new, the page changes but both layouts stay put: they don't re-render and they keep the state of their client components. That's what makes a sidebar menu that keeps its scroll position possible.
- The organization we'll use
The documentation describes three strategies, all supported:
| Strategy | Advantage | Drawback |
|---|---|---|
Everything outside app/, which is left for routes only |
Routes can be read at a glance | Route-specific code ends up far from its route |
Shared folders inside app/ |
A single tree | Routes and code get mixed together |
| Split by feature or route | Maximum proximity | You have to decide when something becomes shared |
In AgendaViva we'll use the first one as our base, with one exception: anything used only by one route is colocated next to it, in a private _components folder.
agendaviva/ ├── app/ Routes and special files │ ├── layout.tsx │ ├── page.tsx │ ├── globals.css │ └── events/ │ ├── page.tsx │ └── _components/ Only for /events ├── components/ Shared components │ ├── header.tsx │ └── event-card.tsx ├── lib/ Code with no UI │ ├── types.ts Domain model │ ├── format.ts Dates and labels │ └── data/ Data access │ ├── events.ts │ └── venues.ts ├── actions/ Server Actions (module 6) └── public/
Responsibilities and allowed dependencies:
app/composes. A page decides which data to request and which components to show; it contains little logic.components/presents. It receives data through props. There will be both Server Components and Client Components here.lib/data/is the only place that knows where the data comes from. Pages and components call its functions without knowing the source, which will let us replace the in-memory data with PostgreSQL in 04-02.actions/modifies. It will group the Server Actions, because they're entry points from the browser and it's worth keeping them in one place so they can be reviewed.
flowchart LR
APP[app/] --> COMP[components/]
APP --> DATA[lib/data/]
APP --> ACT[actions/]
COMP --> ACT
COMP --> TYPES[lib/types.ts]
ACT --> DATA
DATA --> TYPES
Notice that lib/ doesn't depend on app/ or components/. That one-way direction prevents circular dependencies and makes it easier to test the logic in isolation (module 10).
6.1. Naming conventions
| Item | Convention | Example |
|---|---|---|
| Your own files and folders | Lowercase with hyphens | event-card.tsx |
| Components | PascalCase, named export | EventCard |
| Special files | The reserved name, default export | page.tsx → EventsPage |
| Functions | camelCase, starting with a verb | listEvents |
| URL segments | Lowercase, no accents or special characters | /my-bookings |
Lowercase file names avoid the cross-platform casing failures mentioned in the previous lesson.
6.2. Lots of tabs called page.tsx
An everyday downside of these conventions is that the editor fills up with tabs that all have the same name. VS Code lets you label them with their folder; create .vscode/settings.json:
{
"workbench.editor.customLabels.patterns": {
"**/app/**/page.tsx": "${dirname(1)}/${dirname} - page.tsx",
"**/app/**/layout.tsx": "${dirname(1)}/${dirname} - layout.tsx",
"**/app/**/loading.tsx": "${dirname(1)}/${dirname} - loading.tsx",
"**/app/**/error.tsx": "${dirname(1)}/${dirname} - error.tsx",
"**/app/**/route.ts": "${dirname(1)}/${dirname} - route.ts"
}
}Common Mistakes and Tips
- Creating the folder and expecting the URL to exist. Without
page.tsxorroute.tsthere's no route. - Misspelling the reserved name:
pages.tsx,Page.tsxornot_found.tsxhave no effect, and they don't produce an error either. If a special file "does nothing", check its name first. - Putting
page.tsxandroute.tsin the same folder. They respond to the same URL and conflict with each other. - Forgetting the default export in a special file: a named
export functionisn't enough. - Storing private documents in
public/. Anyone with the URL can download them. - Believing a private folder protects code. It only excludes it from routing; if a Client Component imports it, it will reach the browser.
- Using a reserved name for one of your own files. A shared component called
error.tsxortemplate.tsxinsideapp/will be interpreted as a convention.
Exercises
Exercise 1: what gets published
State which URLs are reachable with this structure and why the other folders or files don't publish anything.
app/
├── layout.tsx
├── page.tsx
├── venues/
│ ├── page.tsx
│ ├── map.tsx
│ └── _data/
│ └── page.tsx
├── sign-in/
│ └── form.tsx
└── api/
└── health/
└── route.tsSolution
Three are reachable: /, /venues and /api/health (the latter for whichever methods route.ts exports).
map.tsxis colocated next to a page, but its name isn't reserved._data/is private: itspage.tsxis ignored.sign-in/has nopageorroute;/sign-inreturns a 404 even though the folder exists.layout.tsxwraps routes; it doesn't create them./apidoesn't respond either: the endpoint is one level further down.
Exercise 2: who catches the error
A project has app/layout.tsx, app/error.tsx, app/dashboard/layout.tsx, app/dashboard/error.tsx and app/dashboard/page.tsx. Say which file shows the fallback if rendering fails in: (a) app/dashboard/page.tsx; (b) app/dashboard/layout.tsx; (c) app/layout.tsx.
Solution
- (a)
app/dashboard/error.tsx: it's the closest boundary wrapping the page. - (b)
app/error.tsx. Theerror.tsxindashboardsits inside thedashboardlayout, so it can't catch it; the one in the parent segment does. - (c) Neither of them:
app/error.tsxis also inside the root layout. You'd needapp/global-error.tsx, which replaces the entire document and therefore includes its own<html>and<body>tags.
Exercise 3: placing each piece
Decide where you'd put the following in AgendaViva: (1) a pagination component that /events and /venues will use; (2) a district selector used only by /events; (3) a function that looks up a venue by its slug; (4) the function that creates a booking when a form is submitted; (5) the press kit as a PDF.
Solution
components/pagination.tsx: it's shared.app/events/_components/district-select.tsx: only that route uses it.lib/data/venues.ts: all data access goes through there.actions/bookings.ts: it's a Server Action. Internally it will call a function fromlib/data/.public/press/press-kit.pdf: it's public and needs a fixed URL.
Conclusion
In app/, folders define segments and only page.tsx and route.ts publish them. The other special files add behavior (shared interface, loading, errors, 404) and are nested in a fixed order that explains what each one covers and what it doesn't. Everything else, from colocation to the components/, lib/ and actions/ folders, is your own organization: ours separates who composes, who presents, who reads and who modifies.
With the groundwork laid, in the next lesson, The Case Study: the AgendaViva Cultural Guide, you'll meet the product you're going to build and write its first code: the domain types, the data module and the home page.
