Thuta Learning
Next.js
ExercisesWeb DevelopmentIntermediate

Practice Set 1 — Routing, Layout, and Component Basics Exercises

Next.jsLesson 3240 min

What you'll walk away with

  • Predict the URL of any folder path before running the app
  • Write a [slug] page that awaits its params
  • Wrap one group of pages in a layout with a route group, without changing their URLs
  • Keep "use client" on a small interactive component and use it from a Server Component

Explain it simply

Explain it simply

This lesson teaches nothing new. You already learned the routing and component rules in the earlier chapters; now it is time to write them by hand. Like a driving course, reading the manual is not the same as driving the practice track yourself.

Each task takes about ten minutes. For every task, first predict which URL will appear, then write the code, then check it in the browser. Wherever your prediction was wrong is exactly where your understanding needs work.

Problem → Why → Solution

The problem: it all made sense while reading

Everything was clear while reading the lessons, yet the first attempt produces three mistakes at once. The route group was written as marketing/ without parentheses, so the URL became /marketing/pricing. The product page reads params.slug directly and TypeScript rejects it. The Counter is missing "use client", so Next.js reports that useState only works in a Client Component.

None of these come from not knowing the concepts. Your hands simply have not practised them yet.

first attempts (three bugs)
// app/marketing/pricing/page.tsx   <- should be (marketing): URL is /marketing/pricing

// app/products/[slug]/page.tsx
export default function ProductPage({ params }: { params: { slug: string } }) {
  return <h1>Product: {params.slug}</h1>; // params is a Promise in current Next.js
}

// components/Counter.tsx            <- no "use client" at the top
import { useState } from "react";
export default function Counter() { const [n, setN] = useState(0); /* ... */ }

Why practice beats rereading

In file-system routing the rules hinge on single characters in folder names ([ ] and ( )) and on the very first line of a file. You only remember details like that after getting them wrong and fixing them yourself, not by reading about them again.

Core concept: the four tasks and how to check them

Start one project (npx create-next-app@latest practice-1) and work through the four tasks in order. Each task practises one concept, and the table below says how to check it in the browser.

TaskConceptHow to check it
1. app/about/page.tsx + nav LinkStatic route, Link/about opens; nav clicks do not reload
2. app/products/[slug]/page.tsxDynamic segment/products/abc and /products/123 differ
3. app/(marketing)/layout.tsxRoute groupOnly /pricing gets the new background
4. components/Counter.tsxClient boundaryThe count rises on every click

Brackets and parentheses

[slug] means "any value in this segment", delivered as params.slug. (marketing) never appears in the URL; it only groups folders so the group can have its own layout. That is why app/(marketing)/pricing/page.tsx is served at /pricing.

Only page.tsx makes a route

A folder without page.tsx is not a URL you can open, so a component file such as app/products/ProductCard.tsx can live inside app/ without becoming a route.

Keep the client boundary small

"use client" goes at the very top of a file, and that file plus the modules it imports end up in the browser bundle. The whole About page does not need to be client code; make only the Counter with its button a Client Component and render <Counter /> from the server-rendered page.

After each task, glance at the dev server's terminal. TypeScript errors and route conflicts often show up there before anything looks wrong in the browser. If a task does not work, fix it before moving on: the tasks build on each other, and Task 4's Counter is used inside Task 1's About page. Skipping a broken task makes the source of a later error much harder to find.

Mental model: predict, write, verify
  1. Predict the URL from the path
  2. Write the file with minimal code
  3. Check the guess in the browser
  4. Note why a wrong guess was wrong

A wrong prediction is useful: it marks the exact spot where you are learning.

General pattern: folder names to URLs

text
app/page.tsx                      ->  /
app/<name>/page.tsx               ->  /<name>
app/<name>/[param]/page.tsx       ->  /<name>/<any value>   params.param
app/(group)/<name>/page.tsx       ->  /<name>               (group) is not in the URL
app/(group)/layout.tsx            ->  wraps only the pages inside (group)
app/<name>/Widget.tsx             ->  no URL (not a page file)

Square brackets capture a value, parentheses group folders without touching the URL, and only a page file creates a URL.

Reference answers for the four tasks

Try each task yourself first, then compare with this code. Every task is a separate file named in its // comment. For Task 1, also add <Link href="/about">About</Link> to the root layout's nav. (marketing)/layout.tsx renders nested inside the root layout; it does not replace it.

practice-1 (task files)
// Task 1 - app/about/page.tsx -> "/about" (also add <Link href="/about"> to the nav)
import Counter from "@/components/Counter";

export default function AboutPage() {
  return (
    <section>
      <h1>About this shop</h1>
      <p>This text is rendered on the server.</p>
      <Counter />
    </section>
  );
}

// Task 2 - app/products/[slug]/page.tsx -> "/products/blue-mug"
type Props = { params: Promise<{ slug: string }> };

export default async function ProductPage({ params }: Props) {
  const { slug } = await params;
  const name = slug.replaceAll("-", " ");
  return <h1>Product: {name}</h1>;
}

// Task 3 - app/(marketing)/layout.tsx wraps /pricing, not /about
export default function MarketingLayout({ children }: { children: React.ReactNode }) {
  return <div style={{ background: "#fff7e6", padding: 24 }}>{children}</div>;
}

// app/(marketing)/pricing/page.tsx -> "/pricing" (no "(marketing)" in the URL)
export default function PricingPage() {
  return <h1>Pricing</h1>;
}

// Task 4 - components/Counter.tsx: the only file that ships click logic
"use client";
import { useState } from "react";

export default function Counter() {
  const [count, setCount] = useState(0);
  return (
    <button type="button" onClick={() => setCount((c) => c + 1)}>
      Clicked {count} times
    </button>
  );
}

Code breakdown

  1. A Server Component renders a Client Component<Counter />

    AboutPage has no "use client", so it renders on the server. The Counter arrives as HTML first and starts responding to clicks once its JavaScript loads in the browser.

  2. Awaiting the slugconst { slug } = await params;

    The component is async and awaits the params Promise. slug is the raw string taken from the URL.

  3. Turning the slug into a labelconst name = slug.replaceAll("-", " ");

    Slugs usually use hyphens, so they are swapped for spaces on display. A real shop would look the slug up in a database and show the stored product name.

  4. A layout only for the groupexport default function MarketingLayout({ children }: { children: React.ReactNode }) {

    Only pages inside the (marketing) folder are passed in as children. app/about sits outside the group, so its background stays unchanged.

  5. The directive comes first"use client";

    The directive must be the file's first statement, before any import. Only comments may come above it, as in this example.

You should see
/about shows the heading "About this shop" and a "Clicked 0 times" button that counts 1, 2, 3 as you click. /products/blue-mug shows "Product: blue mug". /pricing shows "Pricing" on a pale orange background, while /marketing/pricing is a 404.

Extra experiments once the tasks work

  • Add app/(shop)/about/page.tsx. It resolves to the same URL as app/about, so Next.js reports a route conflict, which proves that route groups never change the URL.
  • Render <Counter /> twice and confirm that each one keeps its own count.
  • Put console.log("server") in AboutPage. The log appears in the dev server's terminal, not in the browser console.
  • Navigate from /products/blue-mug to /products/red-cup with a Link and confirm the root layout's header is not redrawn.

In real projects

In real projects

The four patterns you practise here are the skeleton of most company websites. Marketing pages such as /pricing and /features are gathered into a (marketing) group with a promotional layout, while the app's dashboard pages sit in an (app) group with a sidebar layout of their own. The URLs stay short: /pricing, /dashboard.

Products, blog posts and user profiles are [slug] or [id] dynamic routes. Only the interactive bits, such as a cart button, a like button or a dropdown, become small Client Components, which keeps the JavaScript sent to the browser small and the pages fast. New team members are often asked to do exactly these exercises in their first week.

Common mistakes

Common mistakes

Forgetting the parentheses on a route group

app/marketing/pricing/ makes marketing an ordinary segment, so the URL becomes /marketing/pricing and /pricing is a 404, with no error message to warn you.

Putting "use client" on the whole page

Adding "use client" to page.tsx makes the error go away, but now the whole page and everything it imports ships to the browser, and the page can no longer fetch server-only data directly. Mark only the interactive component as client code.

Reading params as a plain object

The type { params: { slug: string } } comes from the Next.js 14 era. In current versions params is a Promise: type it as Promise<{ slug: string }> and await it.

Two groups producing the same URL

app/(marketing)/about and app/(shop)/about both resolve to /about, and Next.js refuses that. Remember that group names never reach the URL.

Best practices

Tips for practising well

  • Try each task on your own for at least ten minutes before opening the reference answer, and afterwards close it and rewrite the file instead of copying
  • Make one git commit per finished task, so you can return to a working state if the next task gets messy
  • Read error messages from the top; most Next.js errors name the file and suggest the fix

Mini challenge

Write a route resolver that follows the App Router rules

Turn the rules from the four tasks into code. Write three functions that derive URL patterns from a list of file paths and decide which route handles a pathname. This is not Next.js's real router, just a small model that proves you understand the rules.

  • routeFromFile(): only page files under app/ become routes, and (group) segments are dropped
  • matchRoute(): segment counts must match; [name] captures any value into params
  • resolve(): try routes with fewer dynamic segments first, and return "404 Not Found" when none match
  • /products/new must reach the static route and /products/blue-mug the [slug] route
route-model.ts
type Params = Record<string, string>;

// "app/(marketing)/pricing/page.tsx" -> "/pricing"; non-page files -> null
function routeFromFile(file: string): string | null {
  // TODO: must start with "app" and end with page.tsx/ts/jsx/js
  // TODO: drop "app", the file name and every "(group)" segment
}

// matchRoute("/products/[slug]", "/products/blue-mug") -> { slug: "blue-mug" }
function matchRoute(pattern: string, pathname: string): Params | null {
  // TODO: compare segment by segment; "[name]" captures, others must be equal
}

function resolve(routes: string[], pathname: string): string {
  // TODO: sort so routes with fewer [dynamic] segments are tried first
  // TODO: return "<route> <params as JSON>" or "404 Not Found"
}

Expected: Five of the seven files become routes; layout.tsx and ProductCard.tsx print (not a route). /products/new reaches the static route, /products/blue-mug reaches [slug] with {"slug":"blue-mug"}, and /marketing/pricing and /products are 404s.

Show hint

Split with file.split("/"). A group segment satisfies s.startsWith("(") && s.endsWith(")"). pathname.split("/").filter(Boolean) turns "/" into [], so the root route "/" matches as well.

Show solution
route-model.ts
type Params = Record<string, string>;

const isGroup = (s: string) => s.startsWith("(") && s.endsWith(")");
const isDynamic = (s: string) => s.startsWith("[") && s.endsWith("]");

function routeFromFile(file: string): string | null {
  const parts = file.split("/");
  const last = parts[parts.length - 1];
  if (parts[0] !== "app" || !/^page\.(tsx|ts|jsx|js)$/.test(last)) return null;
  const segments = parts.slice(1, -1).filter((s) => !isGroup(s));
  return "/" + segments.join("/");
}

function matchRoute(pattern: string, pathname: string): Params | null {
  const want = pattern.split("/").filter(Boolean);
  const got = pathname.split("/").filter(Boolean);
  if (want.length !== got.length) return null;
  const params: Params = {};
  for (let i = 0; i < want.length; i++) {
    if (isDynamic(want[i])) params[want[i].slice(1, -1)] = got[i];
    else if (want[i] !== got[i]) return null;
  }
  return params;
}

// Static segments beat dynamic ones, like the App Router.
function resolve(routes: string[], pathname: string): string {
  const dynamicCount = (r: string) => r.split("/").filter(isDynamic).length;
  const ordered = [...routes].sort((a, b) => dynamicCount(a) - dynamicCount(b));
  for (const route of ordered) {
    const params = matchRoute(route, pathname);
    if (params) return `${route} ${JSON.stringify(params)}`;
  }
  return "404 Not Found";
}

const files = [
  "app/page.tsx",
  "app/about/page.tsx",
  "app/products/[slug]/page.tsx",
  "app/products/new/page.tsx",
  "app/(marketing)/layout.tsx",
  "app/(marketing)/pricing/page.tsx",
  "app/products/ProductCard.tsx",
];

const routes: string[] = [];
for (const f of files) {
  const route = routeFromFile(f);
  console.log(`${f} -> ${route ?? "(not a route)"}`);
  if (route) routes.push(route);
}

const paths = [
  "/products/blue-mug", "/products/new", "/pricing", "/marketing/pricing", "/products",
];
for (const path of paths) console.log(`${path} => ${resolve(routes, path)}`);

Quick quiz 1 / 3

At which URL does app/(shop)/products/[slug]/page.tsx render the slug "blue-mug"?

Quick quiz 2 / 3

Counter.tsx uses useState but has no "use client", and a Server Component page imports it. What happens?

Quick quiz 3 / 3

Which pages does app/(marketing)/layout.tsx wrap, given app/about/page.tsx and app/(marketing)/pricing/page.tsx?

What to remember

  • For every task, predict the URL first, then write the code and check it in the browser
  • [slug] captures a value; (group) stays out of the URL and only provides a shared layout
  • Only page files create routes, and static segments win over dynamic ones
  • Keep "use client" on small interactive components rendered from Server Component pages

Next.js Documentation — Next.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Practice Set 1 — Routing, Layout, and Component Basics Exercises | Thuta Learning