Thuta Learning
Next.js
ProjectsWeb DevelopmentIntermediate

Mini Project — Link Stash (Part 1): Setup and Core Structure

Next.jsLesson 2935 min

What you'll walk away with

  • Decide which file under app/ renders each Link Stash URL before writing code
  • Write the header and navigation once in the root layout and reuse it on every page
  • Keep the Bookmark type and getBookmarks()/getBookmark() in lib/ so pages only call functions
  • Write the app/bookmarks/[id]/page.tsx dynamic route that awaits its params

Explain it simply

Explain it simply

Over three lessons you will build Link Stash, a small app where a user saves a link with a title, a URL and a few tags, then finds it again by tag. Part 1 has no form and no delete button yet. It shows three bookmarks that are written directly in code.

Think of building a house. Before choosing nice windows, you fix the floor plan (the routes), the hallway every room opens onto (the layout), and the storeroom where things are kept (lib/db.ts). If this Part 1 skeleton is right, Part 2 can start adding and removing things without knocking down any rooms.

Problem → Why → Solution

The problem: a first draft crammed into one page

Here is a first draft written in a hurry. The bookmark array lives inside app/page.tsx, the detail page sits in a folder called app/bookmarks/id/page.tsx (no brackets), and every link is a plain <a>.

Clicking a card shows a 404 for /bookmarks/1. Only typing /bookmarks/id literally shows the page. Every click also makes the browser reload the whole document from scratch. And the detail page needs its own copy of the array, so changing one bookmark means editing two files.

first-draft (broken)
// app/page.tsx
const bookmarks = [{ id: "1", title: "Next.js Docs", url: "https://nextjs.org" }];

export default function HomePage() {
  return bookmarks.map((b) => (
    <a key={b.id} href={`/bookmarks/${b.id}`}>{b.title}</a> // full reload
  ));
}

// app/bookmarks/id/page.tsx  <- folder named "id", not "[id]"
// Only the literal URL /bookmarks/id reaches this file; /bookmarks/1 is a 404.

Why does this happen?

The App Router reads folder names literally as URL segments. Only square brackets tell it "accept any value here". A plain <a> bypasses the Next.js router and asks the browser for a brand-new document, hence the reload. And because the data is written inside the page, every page has to know where the data comes from.

Core concept: URL map, layout and one data entry point

Create the project with npx create-next-app@latest link-stash. The prompts differ slightly between versions, but make sure TypeScript and the App Router are on and keep the default @/* import alias. Then run npm run dev and open http://localhost:3000. Before writing any code, we make three decisions.

1. One file per URL

In the App Router every folder under app/ is a URL segment, and a URL only opens if that folder contains page.tsx. So write the URL map first, like the table below. A bracketed name such as [id] is a dynamic segment: one file handles /bookmarks/1, /bookmarks/2 and every other id.

2. Put what never changes in the layout

app/layout.tsx is the frame around every page. Write the header and nav here, once. When you move between pages with the Link component from next/link, the layout stays mounted and only the page inside it changes.

3. Await the dynamic value

When a user opens /bookmarks/2, Next.js calls the [id] page component with { params }. In current versions params is a Promise, so the component is async and reads const { id } = await params. The id you get is always a string: "2", never the number 2.

4. Hide the data behind functions

The Bookmark type and starter data live in lib/bookmarks.ts, and pages only call getBookmarks() and getBookmark(id) from lib/db.ts. When Part 2 changes the storage, you edit lib/db.ts alone and none of the page files.

URLFile that renders it
/app/page.tsx
/bookmarks/1, /bookmarks/2 ...app/bookmarks/[id]/page.tsx
/bookmarks/new (Part 2)app/bookmarks/new/page.tsx
No URL (plain code)lib/bookmarks.ts, lib/db.ts
text
Link Stash after Part 1
-----------------------
link-stash/
  app/
    layout.tsx            header + nav, wraps every page
    globals.css
    page.tsx              "/"              list of bookmarks
    bookmarks/
      [id]/page.tsx       "/bookmarks/:id" one bookmark
  lib/
    bookmarks.ts          type Bookmark + seed data
    db.ts                 getBookmarks(), getBookmark(id)

Every one of these files is a Server Component. Nothing needs click handlers or state yet, so "use client" does not appear anywhere.

Mental model: URL map, frame, data door
  1. Write URLs down as folders
  2. Put header and nav in the layout once
  3. Keep data behind lib/db.ts functions
  4. Pages only call those functions

If a page knows where data is stored, Part 2 has one more file to change. A page should only know what to show.

General pattern: a dynamic page

tsx
// app/<segment>/[param]/page.tsx
type Props = { params: Promise<{ param: string }> };

export default async function Page({ params }: Props) {
  const { param } = await params;
  const item = getItem(param);
  if (!item) return <p>Not found</p>;
  return <h1>{item.name}</h1>;
}

The bracket name (param) becomes the key inside the params object. In current Next.js versions params is a Promise, so await it inside an async component before using it.

Part 1 code: the skeleton in five files

Split the code below into files following each // comment. create-next-app already made app/globals.css; add a few styles for .card and .site-header yourself. The framework runs this code, so test it in your own project with npm run dev rather than with a Run button here.

link-stash (Part 1)
// lib/bookmarks.ts - the data model and starter data
export type Bookmark = {
  id: string;
  title: string;
  url: string;
  tags: string[];
};

export const seedBookmarks: Bookmark[] = [
  { id: "1", title: "Next.js Docs", url: "https://nextjs.org/docs",
    tags: ["docs", "nextjs"] },
  { id: "2", title: "MDN Web Docs", url: "https://developer.mozilla.org",
    tags: ["docs"] },
  { id: "3", title: "Can I use", url: "https://caniuse.com", tags: ["reference"] },
];

// lib/db.ts - the only file that knows where bookmarks live
import { seedBookmarks, type Bookmark } from "./bookmarks";

export function getBookmarks(): Bookmark[] {
  return seedBookmarks;
}

export function getBookmark(id: string): Bookmark | undefined {
  return seedBookmarks.find((b) => b.id === id);
}

// app/layout.tsx - wraps every page
import Link from "next/link";
import "./globals.css";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <header className="site-header">
          <Link href="/" className="logo">Link Stash</Link>
          <nav>
            <Link href="/">All bookmarks</Link>
            <Link href="/bookmarks/new">Add bookmark</Link>
          </nav>
        </header>
        <main>{children}</main>
      </body>
    </html>
  );
}

// app/page.tsx - the home page, URL "/"
import Link from "next/link";
import { getBookmarks } from "@/lib/db";

export default function HomePage() {
  const bookmarks = getBookmarks();
  return (
    <ul className="bookmark-list">
      {bookmarks.map((b) => (
        <li key={b.id} className="card">
          <Link href={`/bookmarks/${b.id}`}>{b.title}</Link>
          <span className="tags">{b.tags.join(", ")}</span>
        </li>
      ))}
    </ul>
  );
}

// app/bookmarks/[id]/page.tsx - URL "/bookmarks/1", "/bookmarks/2", ...
import { getBookmark } from "@/lib/db";

type Props = { params: Promise<{ id: string }> };

export default async function BookmarkPage({ params }: Props) {
  const { id } = await params;
  const bookmark = getBookmark(id);
  if (!bookmark) return <p>No bookmark with id "{id}".</p>;

  return (
    <article>
      <h1>{bookmark.title}</h1>
      <a href={bookmark.url} target="_blank" rel="noreferrer">{bookmark.url}</a>
      <p>Tags: {bookmark.tags.join(", ")}</p>
    </article>
  );
}

Code breakdown

  1. One shape for every bookmarkexport type Bookmark = {

    Notice id is a string. The id that arrives from the URL is always a string, so storing strings avoids comparing "2" with 2. Parts 2 and 3 keep using exactly this type.

  2. The single data entry pointexport function getBookmark(id: string): Bookmark | undefined {

    Because the return type includes undefined, TypeScript forces every caller to handle the not-found case. Pages never touch the array directly; they call this function.

  3. Navigation in the layout<Link href="/bookmarks/new">Add bookmark</Link>

    Link switches pages through the router, so the header is not redrawn. The /bookmarks/new route itself is built in Part 2.

  4. A link per card<Link href={`/bookmarks/${b.id}`}>{b.title}</Link>

    A template literal puts the id into the URL. Each card has key={b.id} so React can update the list correctly later, when Part 2 adds and removes items.

  5. Awaiting paramsconst { id } = await params;

    The component is async and awaits the params Promise, then passes id to getBookmark(). For now a missing bookmark shows one sentence; Part 3 replaces it with notFound().

You should see
At http://localhost:3000 three bookmark cards appear under the header (Link Stash, All bookmarks, Add bookmark). Clicking "MDN Web Docs" goes to /bookmarks/2 without a page reload and shows the title, the link and "Tags: docs". Opening /bookmarks/99 shows: No bookmark with id "99".

Why /bookmarks/new already seems to exist

Click "Add bookmark" in Part 1. Instead of a 404 you see: No bookmark with id "new". There is no app/bookmarks/new/ folder yet, so the [id] dynamic segment catches "new" as if it were an id.

As soon as Part 2 creates app/bookmarks/new/page.tsx, the static segment wins over the dynamic one and /bookmarks/new reaches the form page, while URLs such as /bookmarks/1 still go to [id]. That is also why words like "new" or "edit" should never be used as bookmark ids.

When to use Link and when <a>

Use Link for moves between pages of your own app; in a production build Next.js can prefetch links that are visible in the viewport, so clicks feel instant. For an external site such as a bookmark's url, a plain <a> with target="_blank" is the right tool.

In real projects

In real projects

Teams often start a new project as a "walking skeleton": every route, the layout and fake data, deployed on day one so designers and product owners can open real URLs. Broken navigation or awkward URL names show up before a single feature exists, when they are cheapest to fix.

Hiding data access behind functions in lib/ is just as common in production code. Whether the data comes from Prisma, Drizzle or an outside API, pages only see names like getBookmarks(). Switching databases, adding a cache or swapping in fake data for tests then happens in one file, and secrets such as a database password stay in these server-side files where the browser never sees them.

Common mistakes

Common mistakes

Forgetting the brackets in the folder name

Writing app/bookmarks/id/ creates exactly one URL, /bookmarks/id, and /bookmarks/1 becomes a 404 with no error message to point you at the cause. Rename the folder to [id] and refresh the dev server.

Using <a> for links inside the app

<a href="/bookmarks/1"> works, but each click reloads the whole document, redraws the layout from scratch and gets no prefetching. Switch internal links to Link.

Reading params.id without awaiting

Older tutorials written for Next.js 14 type { params }: { params: { id: string } } and read params.id directly. In current versions params is a Promise: type it as Promise<{ id: string }> and await params first.

Copying the data into every page

With a separate array in the home page and the detail page, you will eventually edit one and forget the other. Read both from lib/db.ts.

Mini challenge

Write the helpers for a tag strip

You want a tag strip like "docs (3) · reference (2)" at the top of the home page. Write the logic as pure functions that will live in lib/, so the page only has to render. The links point at /?tag=..., which Part 2 makes work.

  • hostnameOf(url) returns the hostname without a leading "www."
  • tagCounts(bookmarks) returns { tag, count } items, highest count first, ties in alphabetical order
  • tagHref(tag) returns /?tag=... using encodeURIComponent
  • Reuse the Bookmark type from the lesson
lib/tags.ts
type Bookmark = { id: string; title: string; url: string; tags: string[] };
type TagCount = { tag: string; count: number };

function hostnameOf(url: string): string {
  // TODO: parse with new URL(), drop a leading "www."
}

function tagCounts(bookmarks: Bookmark[]): TagCount[] {
  // TODO: count every tag (a Map works well)
  // TODO: sort by count (desc), then by tag name (asc)
}

function tagHref(tag: string): string {
  // TODO: "/?tag=" + the encoded tag
}

// TODO: print each bookmark's host, then each tag with its count and link

Expected: Each bookmark's host (www.web.dev becomes web.dev), then docs (3), reference (2) and nextjs (1) with their links, and finally the encoded link /?tag=c%23%20%26%20.net.

Show hint

new URL(url).hostname gives the host. For counting, use counts.set(tag, (counts.get(tag) ?? 0) + 1). In the sort, b.count - a.count || a.tag.localeCompare(b.tag) falls back to the name when counts tie.

Show solution
lib/tags.ts
type Bookmark = { id: string; title: string; url: string; tags: string[] };
type TagCount = { tag: string; count: number };

const bookmarks: Bookmark[] = [
  { id: "1", title: "Next.js Docs", url: "https://nextjs.org/docs",
    tags: ["docs", "nextjs"] },
  { id: "2", title: "MDN Web Docs", url: "https://developer.mozilla.org",
    tags: ["docs"] },
  { id: "3", title: "Can I use", url: "https://caniuse.com", tags: ["reference"] },
  { id: "4", title: "web.dev", url: "https://www.web.dev/learn",
    tags: ["reference", "docs"] },
];

function hostnameOf(url: string): string {
  const host = new URL(url).hostname;
  return host.startsWith("www.") ? host.slice(4) : host;
}

function tagCounts(list: Bookmark[]): TagCount[] {
  const counts = new Map<string, number>();
  for (const b of list) {
    for (const tag of b.tags) counts.set(tag, (counts.get(tag) ?? 0) + 1);
  }
  return [...counts]
    .map(([tag, count]) => ({ tag, count }))
    .sort((a, b) => b.count - a.count || a.tag.localeCompare(b.tag));
}

function tagHref(tag: string): string {
  return `/?tag=${encodeURIComponent(tag)}`;
}

for (const b of bookmarks) console.log(`${b.title} -> ${hostnameOf(b.url)}`);
for (const { tag, count } of tagCounts(bookmarks)) {
  console.log(`${tag} (${count}) ${tagHref(tag)}`);
}
console.log(tagHref("c# & .net"));

Quick quiz 1 / 3

In Part 1 there is no app/bookmarks/new/ folder yet. What appears when you click "Add bookmark" (/bookmarks/new) in the nav?

Quick quiz 2 / 3

If the detail page lives at app/bookmarks/id/page.tsx (no brackets), which URL reaches it?

Quick quiz 3 / 3

What is the main benefit of app/page.tsx calling getBookmarks() from lib/db.ts instead of holding the array itself?

What to remember

  • Map every URL to a file under app/ before writing code
  • A bracketed folder like [id] is a dynamic segment; await params before reading it
  • Keep the header and nav in the root layout and use Link for internal links
  • Pages only call functions from lib/db.ts, so Part 2 can swap the storage easily

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.

Mini Project — Link Stash (Part 1): Setup and Core Structure | Thuta Learning