Next.js App Router and Server Components

By Published 7 min read

Next.js App Router and Server Components

Introduction:

So far in this course we have built everything with the Pages Router: files in the pages folder, data loaded with getStaticProps and getServerSideProps, and API routes in pages/api. That router still works and is still supported, but since Next.js 13 there is a newer way to build apps: the App Router, which lives in the app folder.

The App Router is built around React Server Components. Components run on the server by default, can read data directly with async/await, and send no JavaScript to the browser unless they need interactivity. The result is less code, smaller pages and a simpler mental model once it clicks.

In this lesson we will build a small blog with the App Router and see the key ideas one at a time. Every example was built and run with Next.js 16.

The app Folder

In the App Router, folders define routes and special files inside them define what is shown:

app/
├── layout.js            -> wraps every page (required)
├── page.js              -> /
├── blog/
│   ├── page.js          -> /blog
│   ├── loading.js       -> shown while /blog is loading
│   └── [slug]/
│       └── page.js      -> /blog/hello-world, /blog/app-router, ...
├── dashboard/
│   └── page.js          -> /dashboard
└── api/
    └── hello/
        └── route.js     -> /api/hello  (an API endpoint)

A folder becomes a public route only when it contains a page.js (or a route.js for an API). This means you can keep components, tests and styles inside the app folder next to the pages that use them, without them becoming routes.

The most important special files are:

  • page.js: the UI for a route.
  • layout.js: UI shared by a route and everything below it.
  • loading.js: a loading state shown while the page loads.
  • error.js: shown if something on the page throws an error.
  • not-found.js: shown when notFound() is called or no route matches.
  • route.js: an API endpoint (replaces pages/api).

Layouts

Every App Router project has a root layout in app/layout.js. It replaces _app.js and _document.js from the Pages Router, so it must render the <html> and <body> tags:

// app/layout.js
import Link from "next/link";

export const metadata = {
  title: "My Blog",
  description: "Built with the Next.js App Router",
};

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <nav>
          <Link href="/">Home</Link> | <Link href="/blog">Blog</Link>
        </nav>
        <main>{children}</main>
      </body>
    </html>
  );
}

children is the current page. When you navigate from / to /blog, only children changes; the layout stays on screen and keeps its state. You can add more layouts in sub-folders, for example app/dashboard/layout.js for a sidebar shown only on dashboard pages. Layouts nest inside each other automatically.

The exported metadata object sets the page’s <title> and meta tags. It replaces the <Head> component from the Pages Router.

Server Components: Fetching Data Directly

In the App Router, every component is a Server Component unless you say otherwise. Server Components run only on the server (at build time or on each request), and they can be async. That means you can load data right inside the component:

// lib/posts.js
const posts = [
  { slug: "hello-world", title: "Hello World", body: "My first post." },
  { slug: "app-router", title: "Learning the App Router", body: "Layouts, pages and Server Components." },
];

export async function getPosts() {
  await new Promise((r) => setTimeout(r, 50)); // pretend this is a database call
  return posts;
}

export async function getPost(slug) {
  const all = await getPosts();
  return all.find((p) => p.slug === slug) || null;
}
// app/blog/page.js
import Link from "next/link";
import { getPosts } from "../../lib/posts";

export default async function BlogPage() {
  const posts = await getPosts(); // runs on the server

  return (
    <>
      <h1>Blog</h1>
      <ul>
        {posts.map((post) => (
          <li key={post.slug}>
            <Link href={`/blog/${post.slug}`}>{post.title}</Link>
          </li>
        ))}
      </ul>
    </>
  );
}

Compare this with the Pages Router: there is no getStaticProps, no props passed in from a separate function, and no API route needed in between. In a real app, getPosts() could query a database or call a CMS with a secret key, because this code never reaches the browser. We checked: after building the app, the text of lib/posts.js appears nowhere in the JavaScript files sent to the browser.

Static or Dynamic?

When you run next build, Next.js decides for each page whether it can be prerendered once at build time (static) or must be rendered on every request (dynamic). A page is static unless it uses request-specific data such as cookies, headers or search parameters. You can also force a page to be dynamic:

// app/dashboard/page.js
export const dynamic = "force-dynamic";

export default async function Dashboard() {
  const time = new Date().toLocaleTimeString("en-IN", { timeZone: "Asia/Kolkata" });
  return <p>Server time in India: {time}</p>;
}

The build output shows the result for each route:

Route (app)
┌ ○ /
├ ○ /_not-found
├ ƒ /api/hello
├ ○ /blog
├   /blog/[slug]
│ ├ ● /blog/hello-world
│ └ ● /blog/app-router
└ ƒ /dashboard

○  (Static)   prerendered as static content
●  (SSG)      prerendered as static HTML (uses generateStaticParams)
ƒ  (Dynamic)  server-rendered on demand

Client Components: “use client”

Server Components can’t use state, effects or browser events, because they don’t run in the browser. For anything interactive (a button, a form, a dropdown) you create a Client Component by putting "use client" at the very top of the file:

// components/LikeButton.js
"use client";

import { useState } from "react";

export default function LikeButton() {
  const [likes, setLikes] = useState(0);
  return <button onClick={() => setLikes(likes + 1)}>👍 {likes}</button>;
}

A Server Component can import and render a Client Component like any other component. The server renders the HTML first (so the button appears immediately with 👍 0), and then the browser downloads only the JavaScript for LikeButton to make it interactive.

A simple rule for deciding:

  • Server Component (the default): fetching data, reading from a database, using secret keys, rendering mostly static content.
  • Client Component: useState, useEffect, onClick and other event handlers, browser-only APIs such as localStorage, and libraries that depend on them.

Keep "use client" as low in the tree as possible: make the small interactive pieces client components, and leave the pages and layouts as server components. Everything imported by a client component also becomes client code, so marking a whole page with "use client" would send all of it to the browser.

Dynamic Routes

A folder name in square brackets, like [slug], creates a dynamic route, just like pages/blog/[slug].js in the Pages Router. The page receives a params prop. In Next.js 15 and later, params is a Promise, so you await it:

// app/blog/[slug]/page.js
import { notFound } from "next/navigation";
import { getPost, getPosts } from "../../../lib/posts";
import LikeButton from "../../../components/LikeButton";

// Build these pages ahead of time (replaces getStaticPaths)
export async function generateStaticParams() {
  const posts = await getPosts();
  return posts.map((post) => ({ slug: post.slug }));
}

// A different <title> for every post
export async function generateMetadata({ params }) {
  const { slug } = await params;
  const post = await getPost(slug);
  return { title: post ? post.title : "Post not found" };
}

export default async function PostPage({ params }) {
  const { slug } = await params;
  const post = await getPost(slug);
  if (!post) notFound(); // shows the 404 page

  return (
    <article>
      <h1>{post.title}</h1>
      <p>{post.body}</p>
      <LikeButton />
    </article>
  );
}

Visiting /blog/app-router shows the post with the title “Learning the App Router” in the browser tab and a working like button, while /blog/nope returns a 404 status.

Loading States

Add a loading.js file next to a page, and Next.js shows it instantly while the page’s data is loading, then swaps in the real page when it’s ready:

// app/blog/loading.js
export default function Loading() {
  return <p>Loading posts…</p>;
}

Behind the scenes Next.js wraps the page in a React Suspense boundary and streams the HTML: the layout and loading state are sent first, and the rest follows as soon as the data arrives. Visitors see something on the screen right away instead of a blank page. In the same way, an error.js file (which must be a Client Component) catches errors and can show a “Try again” button.

Route Handlers: APIs in the App Router

API endpoints live in route.js files and export a function for each HTTP method. They use the standard Web Request and Response objects:

// app/api/hello/route.js
export async function GET(request) {
  const { searchParams } = new URL(request.url);
  const name = searchParams.get("name") || "world";
  return Response.json({ message: `Hello, ${name}!` });
}

A request to /api/hello?name=Khan returns:

{"message":"Hello, Khan!"}

Export POST, PUT, PATCH or DELETE functions in the same file to handle other methods. Note that a folder can’t have both a page.js and a route.js.

Pages Router vs App Router

If you already know the Pages Router from the earlier lessons, here is how the ideas map across:

  • pages/about.js becomes app/about/page.js.
  • _app.js and _document.js become app/layout.js.
  • getStaticProps / getServerSideProps become an async Server Component that loads its own data.
  • getStaticPaths becomes generateStaticParams.
  • next/head becomes the metadata export or generateMetadata.
  • pages/api/hello.js becomes app/api/hello/route.js.
  • useRouter from next/router becomes useRouter, usePathname and useSearchParams from next/navigation (in Client Components).

Both routers can live in the same project, so an existing app can move to the App Router one page at a time. For new projects, create-next-app uses the App Router by default.

Common Mistakes

1. Using hooks in a Server Component:

useState, useEffect or an onClick in a file without "use client" causes a build error. Move the interactive part into a small Client Component.

2. Putting “use client” on everything:

It works, but you lose the benefits: all that code is sent to the browser and you can no longer load data directly in the component.

3. Importing server-only code into a Client Component:

A Client Component can’t read the database or use secret environment variables. Load the data in a Server Component and pass it down as props (props must be plain data, not functions or class instances).

4. Forgetting to await params:

In Next.js 15 and 16, params and searchParams are Promises. Writing params.slug without await gives undefined.

Conclusion:

The App Router organises your app with folders and special files (page.js, layout.js, loading.js, error.js, route.js). Components are Server Components by default: they can be async, load data directly and send no JavaScript to the browser. Add "use client" only to the small interactive pieces. Use generateStaticParams and generateMetadata for dynamic routes, loading.js for instant loading states, and route handlers for APIs. With these pieces you can build the same apps as with the Pages Router, with less code and faster pages.

In the next Next.js lesson we will look at environment variables in Next.js: how to keep secrets on the server and which values are safe to send to the browser.

Khan Waseem is a tech lead and full-stack engineer in Bengaluru, building hospitality and SaaS software with Node.js, React and React Native. See the resume