Next.js — Routing, Server Components and Forms
File-based routing, layouts, server and client components, server actions, and when to render on the server.
From a React UI to a Complete Web Application
React components describe a user interface, but a production application also needs routes, data access, server-side code, metadata, and a deployment model. Next.js combines React with a framework for these application concerns. Its App Router uses folders and files to define a route tree and encourages a server-first design: render data on the server when interactivity is not required, and add client code only where it provides value.
Our study planner will have a dashboard at /planner, a detail page for one study plan, and a route handler for a JSON endpoint. A shared layout can provide navigation and consistent page structure. The folder hierarchy makes the URL structure visible to the team.
| File or directory | Purpose | Planner example |
|---|---|---|
| app/layout.tsx | Required root layout and shared document shell | Global styles and site shell |
| app/planner/page.tsx | Page for a route segment | Study dashboard |
| app/planner/[planId]/page.tsx | Dynamic route segment | One plan by identifier |
| app/api/plans/route.ts | HTTP route handler | JSON endpoint for plan requests |
| components/PlanActions.tsx | Reusable interactive UI | Client-side checkbox or form |
page, layout, and route within the app tree.Build URLs from the App Directory
A page file makes a route accessible. Nested folders represent nested URL segments, and bracketed folders represent dynamic segments. A layout wraps pages below it and preserves shared UI as users navigate. Route groups can organize files without adding a URL segment, while loading and error UI can be scoped to a segment.
type Plan = { id: string; title: string; subject: string }
async function getPlan(planId: string): Promise<Plan> {
const response = await fetch(process.env.PLANNER_API_URL + "/plans/" + planId, {
cache: "no-store",
})
if (!response.ok) throw new Error("Could not load study plan")
return response.json() as Promise<Plan>
}
export default async function PlanPage({
params,
}: { params: { planId: string } }) {
const plan = await getPlan(params.planId)
return (
<main>
<p>Study plan</p>
<h1>{plan.title}</h1>
<p>Subject: {plan.subject}</p>
</main>
)
}This example performs a server-side request and never sends the private service URL to browser code. In a real app, validate the route identifier and authorize access before returning a student's data. Do not assume that a difficult-to-guess URL is authorization.
Choose the Right Component Boundary
App Router components are server components by default. They can read server-side configuration and load data, and they send rendered output rather than the component's interactive JavaScript to the browser. A client component is needed for state, effects, event handlers, or browser APIs; mark its module with use client. A client boundary also pulls its imported component dependencies into the client bundle, so keep it as small as practical.
"use client"
import { useState } from "react"
export function CompleteSessionButton({ sessionId }: { sessionId: string }) {
const [complete, setComplete] = useState(false)
return (
<button type="button" aria-pressed={complete}
onClick={() => setComplete((value) => !value)}>
{complete ? "Completed" : "Mark complete"}
</button>
)
}Server components can render client components and pass serializable props into them. They cannot pass an arbitrary function defined on the server as an event handler. Put interactivity behind a client component, or use a server action or route handler for a server mutation.
Fetch Close to the Server-Rendered Page
Server-side data access avoids shipping credentials and database clients to the browser. Fetch in the component or in a server-only data-access function, and handle missing records, authorization, and upstream failure deliberately. Pick caching and revalidation behavior based on freshness requirements: a public course catalog can be cached longer than a student's completion state.
Do not automatically add a browser effect for every request. Server rendering can return useful initial content and reduce client-side loading transitions. For an interactive filter, the client can update the URL and request a different server-rendered result or call a JSON route, depending on the product need.
- Identify the page data and which user is allowed to see it.
- Load it in a server component or a server-only data-access layer.
- Choose cache behavior based on whether the data is public, personal, or frequently changing.
- Render deliberate loading and error UI for slow or failed paths.
- Use a client component only for the interaction that needs local state or browser events.
Expose a Small JSON Endpoint
Route handlers live in a route.ts file and implement HTTP methods such as GET or POST using the web Request and Response APIs. They are useful for a public JSON contract, callbacks, or a request that needs to be called by another client. Validate input, authenticate and authorize the caller, return a meaningful status, and avoid returning internal error details.
import { NextResponse } from "next/server"
export async function GET(request: Request) {
const url = new URL(request.url)
const studentId = url.searchParams.get("studentId")
if (!studentId) {
return NextResponse.json({ error: "studentId is required" }, { status: 400 })
}
// In production: authenticate, authorize, then query the data layer.
const plans = await findPlansForStudent(studentId)
return NextResponse.json({ plans })
}
async function findPlansForStudent(studentId: string) {
return [{ id: "plan-1", studentId, title: "Midterm revision" }]
}The placeholder function makes the request flow visible, but real data must come from the persistence layer and must be scoped to the authenticated student, not a freely chosen ID supplied by the browser. A successful response should have a stable shape; consumers should not need to guess whether an error is a list or an object.
Keep Form Changes on a Trusted Server Path
Creating a study task changes persistent data, so it is a mutation rather than a render. A server action can receive a form submission and run server-side logic; a route handler is another option when a JSON API is useful. Whichever path you choose, validate input again on the server, check the current user's permission, and return a safe result. Client validation helps usability but can be bypassed.
"use server"
import { revalidatePath } from "next/cache"
export async function addStudyTask(formData: FormData) {
const title = String(formData.get("title") ?? "").trim()
const subject = String(formData.get("subject") ?? "").trim()
if (title.length < 2 || title.length > 120 || !subject) {
return { ok: false, message: "Enter a title and subject." }
}
const student = await requireSignedInStudent()
await saveTask({ studentId: student.id, title, subject })
revalidatePath("/planner")
return { ok: true }
}
async function requireSignedInStudent() {
throw new Error("Connect this action to the app's auth layer")
}
async function saveTask(input: { studentId: string; title: string; subject: string }) {
void input
}The two placeholder functions are intentional seams for the authentication and database lessons. Never treat a server action's obscurity as access control. Authenticate the request and verify that the user is permitted to create or edit the referenced record.
Common Mistakes
Adding use client to the entire application
Why: A wide client boundary increases browser JavaScript and can expose assumptions about private modules.
Fix: Keep data access on the server and isolate small interactive components.
Fetching private data only after hydration
Why: The page can flash empty UI and unnecessarily expose a server-to-server task to the browser.
Fix: Load initial private data on the server after checking the user.
Using a route parameter as proof of ownership
Why: A user can alter a URL or request body to select another record.
Fix: Authorize every read and write against the authenticated identity.
Ignoring cache behavior
Why: Personal data may be stale or shared incorrectly if caching assumptions are wrong.
Fix: Choose and test cache policy according to the data's privacy and freshness requirements.
Build Planner Routes with a Server-First Boundary
Practice
A dashboard, detail route and secure mutation
- Create a shared root layout and a /planner page with meaningful headings and navigation.
- Add a dynamic plan detail route and render its data from a server-side function.
- Build a small client component for marking one session complete, keeping state local to that control.
- Add a GET route handler that validates its query and returns a consistent JSON response.
- Design a server-side task creation path that validates fields and checks the signed-in student's ownership.
Hint: Keep database and authentication functions as explicit seams until you complete the later lessons; never claim an ID parameter is authorization.
🎯 Key Takeaways
- ✓The App Router maps special files in the app directory to routes, layouts, and HTTP handlers.
- ✓Server components are the default; client components are for browser interaction.
- ✓Keep client boundaries narrow and pass only serializable data into them.
- ✓Load private data on the server after authentication and authorization.
- ✓Route handlers define explicit HTTP contracts; validate requests and return useful status codes.
- ✓Mutations need server-side validation, authorization, and deliberate cache revalidation.
- Read the official Next.js App Router guides for layouts, server and client components, data fetching, and route handlers; framework capabilities can evolve.
Next
What comes next
Build a dedicated JSON API with routes, schemas, middleware, and predictable error responses.
Lesson 06 · Building a REST API with Node.js and Express →HELP US IMPROVE
How was this lesson?
Your note is shared with the Chaduvuko team for review. Please don’t include personal or sensitive information.
Spotted a mistake or something unclear? Suggest a fix on GitHub or email us. Select the text first and it is quoted for you.
Discussion
0Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.
