Skip to content
Tutorials Center
My learning

Topics

Lesson 100 of 132 ยท Ecosystem

Next.js App Router Basics

A first tour of the Next.js App Router for React developers - folder-based routes, layouts, loading and error files, server data fetching, server actions, route handlers and metadata.

React gives you components, state and rendering. It does not give you URLs, a server, a way to load data before the page appears, or a build that is tuned for search engines. In a plain Vite project you add those pieces one by one: a router, a data library, maybe server rendering. Next.js is a framework that ships them together. Its modern routing system, the App Router, is built directly on the React features you have already met: Server Components, Suspense, transitions and server functions.

This lesson is a map of the App Router for someone who knows React. You will see how folders become URLs, how layouts nest, how a page gets its data, what the special files do, and how a form can call server code. Next.js needs Node.js, a build step and a server, so the code here is read-only. The two live demos are small stand-ins that reproduce the ideas (a folder-to-route table and nested layouts) in the browser. Version details change between Next.js releases, so treat the official documentation for your installed version as the final word on exact APIs.

What the framework adds

Compare the two ways to start (see Setting Up a React Project):

Need Vite + React Next.js
Routing Add a router library Folders under app/
First HTML for crawlers Empty shell unless you add SSR Rendered on the server by default
Data loading Effects or a data library on the client async Server Components and server functions
Code splitting Manual React.lazy Automatic per route
Images, fonts, metadata Your own setup Built-in components and APIs
Back end A separate server Route handlers and server functions in the same project

Start a project with npx create-next-app@latest. The generated app/ folder is where almost everything happens.

Folders become routes

In the App Router a folder is a URL segment, and a file named page.tsx inside it makes that segment publicly reachable. Other files in the folder are not routes, so you can keep components next to the page that uses them.

TEXT
app/
  layout.tsx            wraps every page (the root layout)
  page.tsx              /
  about/
    page.tsx            /about
  blog/
    layout.tsx          wraps /blog and everything below it
    page.tsx            /blog
    [slug]/
      page.tsx          /blog/hello-world, /blog/anything
  (shop)/               a route group: the name is not in the URL
    cart/
      page.tsx          /cart
  _components/          a private folder: never a route

The naming rules are small:

  • [slug] is a dynamic segment. [...parts] matches any number of segments, and [[...parts]] also matches none.
  • (name) is a route group. It organizes folders or lets groups have different layouts without changing the URL.
  • A folder that starts with _ is private and opts out of routing.
flowchart TD
  A["Request /blog/hello-world"] --> B["app/layout.tsx"]
  B --> C["app/blog/layout.tsx"]
  C --> D["app/blog/[slug]/page.tsx"]
  D --> E["HTML for the whole page"]

The URL is matched to folders; the layouts on the way down wrap the page, outermost first.

The stand-in below does the same matching on a list of file paths. It converts each page.tsx path to a URL pattern and tells you which file serves a visited URL. It is plain JavaScript, not Next.js code, but it shows how little magic there is.

From folders to routes

Pick /cart: the file lives in the (shop) group, yet the route is plain /cart.

Pages and layouts

A page.tsx default-exports a component. Next passes route information as props:

TSX
// app/blog/[slug]/page.tsx
type Props = { params: Promise<{ slug: string }> };

export default async function PostPage({ params }: Props) {
  const { slug } = await params;
  return <h1>Post: {slug}</h1>;
}

In current versions params (and searchParams) are promises, so you await them. Older tutorials show them as plain objects; check your version.

A layout wraps pages and stays mounted while you navigate between its children, so state in a navigation bar is kept and only the changing page re-renders. The root layout is required and must render <html> and <body>:

TSX
// app/layout.tsx
import type { ReactNode } from 'react';

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <body>
        <header>My Site</header>
        {children}
      </body>
    </html>
  );
}

This is the children composition pattern you know, applied to routes. Each folder's layout.tsx receives the next level as children, so layouts nest from the outside in. The demo below builds that by hand for the URL /blog/hello-world.

Nested layouts are children composition

Navigate from /blog/a to /blog/b and only the innermost box would change; the two layouts around it are reused. In real code you move between pages with the Link component from next/link, which renders a normal <a href> (good for crawlers) and prefetches the target for instant navigation:

TSX
import Link from 'next/link';

<Link href="/blog/hello-world">Read the post</Link>

Server Components by default

Every component in app/ is a Server Component unless a file starts with "use client". A Server Component runs only on the server. It can be async, can read a database or the file system, and sends the browser its rendered output, not its code, so the JavaScript your visitors download is smaller. Add "use client" only at the files that need state, effects or browser events, and keep those components small and low in the tree.

Fetching data

Because a page can be async, you fetch data by awaiting it where you need it. There is no useEffect, no loading flag you manage by hand and no request waterfall caused by components mounting one after another:

TSX
// app/blog/page.tsx
import Link from 'next/link';
import { getPosts } from '@/lib/posts'; // reads your database

export default async function BlogIndex() {
  const posts = await getPosts();
  return (
    <ul>
      {posts.map((post) => (
        <li key={post.slug}>
          <Link href={`/blog/${post.slug}`}>{post.title}</Link>
        </li>
      ))}
    </ul>
  );
}

getPosts can talk to a database directly, because this code never reaches the browser. Fetch in parallel with Promise.all when two requests are independent. How results are cached and when they refresh has changed across Next.js versions, so read the caching section of the docs for the version you use and decide per page whether it should be static, revalidated on a timer, or fully dynamic. For data that a signed-in user changes on the client, you can still use a client data library as in caching and server state.

Loading, error and not-found files

Special file names handle the states you would otherwise code by hand:

File Purpose
loading.tsx Shown instantly while the page below it is waiting for data. Next wraps the page in <Suspense> with this as the fallback, so it also enables streaming.
error.tsx An error boundary for the segment. It must be a Client Component and receives the error and a reset function to retry.
not-found.tsx Rendered when you call notFound() or no route matches, with a real 404 status.
TSX
// app/blog/[slug]/page.tsx
import { notFound } from 'next/navigation';
import { findPost } from '@/lib/posts';

export default async function PostPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const post = await findPost(slug);
  if (!post) notFound();
  return <article><h1>{post.title}</h1></article>;
}
TSX
// app/blog/error.tsx
'use client';

export default function BlogError({ reset }: { error: Error; reset: () => void }) {
  return (
    <div role="alert">
      <p>Something went wrong.</p>
      <button type="button" onClick={reset}>Try again</button>
    </div>
  );
}

Server actions

For changing data, you do not need to build an API route and a fetch call. A Server Function marked with "use server" runs on the server, and you can pass it to a form's action, exactly as in form actions:

TSX
// app/blog/actions.ts
'use server';

import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { createPost } from '@/lib/posts';

export async function addPost(formData: FormData) {
  const title = String(formData.get('title') ?? '').trim();
  if (title === '') {
    return;
  }
  await createPost(title);
  revalidatePath('/blog'); // refresh the cached list
  redirect('/blog');
}
TSX
// app/blog/new/page.tsx
import { addPost } from '../actions';

export default function NewPost() {
  return (
    <form action={addPost}>
      <input name="title" required />
      <button type="submit">Publish</button>
    </form>
  );
}

The form works even before JavaScript loads, because it is a real HTML form. In a Client Component you can combine the same action with useActionState for validation messages and useFormStatus for pending buttons. Treat every server function like a public HTTP endpoint: validate the input and check the user's permission inside it, as covered in React security, since anyone can call it with any data.

Route handlers

When you need a real HTTP endpoint (for a mobile app, a webhook, or a third party), add a route.ts file and export a function named after the HTTP method:

TypeScript
// app/api/health/route.ts
export async function GET() {
  return Response.json({ status: 'ok' });
}

A folder can contain either a page.tsx or a route.ts for the same URL, not both.

Metadata and SEO

Export a metadata object (or an async generateMetadata that can read params) from a page or layout and Next writes the right tags into the HTML head, merging layouts and pages:

TSX
import type { Metadata } from 'next';

export const metadata: Metadata = {
  title: 'Blog',
  description: 'Articles about building with React.',
};

Combined with server rendering, this is what gives you the search-friendly output discussed in SEO and Core Web Vitals. For dynamic routes you can also export generateStaticParams to build known pages ahead of time.

When to choose Next.js

Choose it when you want SEO, fast first load, a back end in the same project, or file-based conventions for a larger team. A client-only dashboard behind a login may not need a server, and React Router in framework mode is a capable alternative with a different feel. The component skills you build in this tutorial transfer to all of them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which file creates the public route /about in the App Router?

    A folder is a URL segment, and a page.tsx file inside it makes that segment reachable. Other file names in the folder do not create routes.
  2. 2. What does a layout do when the user navigates between two pages that share it?

    Layouts wrap their children and are preserved across navigations between those children, so things like a navigation bar keep their state.
  3. 3. How do you fetch data in an App Router page that is a Server Component?

    Server Components can be async, so you await the database or fetch call directly. No effect or client-side loading state is required.
  4. 4. Which statement about server actions is correct?

    Anyone can send a request to a server action with any data. Always validate the input and verify authorization inside the function.
  5. 5. What is the role of error.tsx in a route folder?

    error.tsx wraps the segment in an error boundary. It must be a Client Component and receives a reset function to try rendering again.

Summary

  • The App Router maps folders under app/ to URLs; a page.tsx makes a segment public, [slug] is dynamic, and (group) folders do not appear in the URL.
  • Layouts wrap their children and persist across navigation; the root layout renders <html> and <body>.
  • Components are Server Components by default. Add "use client" only where you need state, effects or browser events.
  • Fetch data by making Server Components async; use loading.tsx, error.tsx and not-found.tsx for the loading, error and 404 states.
  • Server actions ("use server") handle form submissions and mutations; treat them as public endpoints and validate everything.
  • route.ts creates HTTP endpoints, and metadata writes head tags for SEO.

Next: Project: Todo App