---
title: "Next.js App Router and Server Components"
url: https://www.khanwaseem.com/blog/nextjs-tutorial/next-js-app-router-and-server-components
author: "khan Waseem"
published: 2026-11-26
updated: 2026-11-26
topics: ["Nextjs Tutorial", "course"]
description: "A practical introduction to the Next.js App Router: the app folder and its special files, layouts, Server Components that fetch data directly, Client Components with “use client”, dynamic routes with…"
---

# Next.js App Router and Server Components

Table of Contents

[Toggle](#)

- [Introduction:](#introduction)
- [The app Folder](#the-app-folder)
- [Layouts](#layouts)
- [Server Components: Fetching Data Directly](#server-components-fetching-data-directly)[Static or Dynamic?](#static-or-dynamic)

- [Client Components: “use client”](#client-components-%e2%80%9cuse-client%e2%80%9d)
- [Dynamic Routes](#dynamic-routes)
- [Loading States](#loading-states)
- [Route Handlers: APIs in the App Router](#route-handlers-apis-in-the-app-router)
- [Pages Router vs App Router](#pages-router-vs-app-router)
- [Common Mistakes](#common-mistakes)[1. Using hooks in a Server Component:](#1-using-hooks-in-a-server-component)
- [2. Putting “use client” on everything:](#2-putting-%e2%80%9cuse-client%e2%80%9d-on-everything)
- [3. Importing server-only code into a Client Component:](#3-importing-server-only-code-into-a-client-component)
- [4. Forgetting to await params:](#4-forgetting-to-await-params)

- [Conclusion:](#conclusion)

## 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](https://blog.khanwaseem.com/api-routes-in-next-js/) 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:

```php
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)Code language: PHP (php)
```

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:

```javascript
// 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>
  );
}Code language: JavaScript (javascript)
```

`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:

```javascript
// 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;
}Code language: JavaScript (javascript)
```

```javascript
// 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>
    </>
  );
}Code language: JavaScript (javascript)
```

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:

```javascript
// 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>;
}Code language: JavaScript (javascript)
```

The build output shows the result for each route:

```php
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 demandCode language: PHP (php)
```

## 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:

```javascript
// 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>;
}Code language: JavaScript (javascript)
```

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:

```javascript
// 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>
  );
}Code language: JavaScript (javascript)
```

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:

```javascript
// app/blog/loading.js
export default function Loading() {
  return <p>Loading posts…</p>;
}Code language: JavaScript (javascript)
```

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:

```javascript
// 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}!` });
}Code language: JavaScript (javascript)
```

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

```json
{"message":"Hello, Khan!"}Code language: JSON / JSON with Comments (json)
```

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.

### Related posts:

[React Router](https://blog.khanwaseem.com/react-router/)
[Navigation Pages in Next.js](https://blog.khanwaseem.com/navigation-pages-in-next-js/)
[API Routes in Next.js](https://blog.khanwaseem.com/api-routes-in-next-js/)
[Routing and Navigation](https://blog.khanwaseem.com/routing-and-navigation/)

Powered by [YARPP](https://yarpp.com).
