Thuta Learning
Next.js
ProjectsWeb DevelopmentIntermediate

Mini Project — Link Stash (Part 2): Add/Delete Feature and Filtering

Next.jsLesson 3040 min

What you'll walk away with

  • Turn lib/db.ts into a store with add, delete and filter without touching the page files
  • Wire an action from a "use server" file to <form action> and read FormData on the server
  • Explain why revalidatePath("/") is called after every change
  • Send an id to a delete action with action.bind(null, id)
  • Read ?tag= with await searchParams and filter the list

Explain it simply

Explain it simply

Part 1's Link Stash can only display data. This part adds a form for new bookmarks, a delete button on each card, and tag links like #docs that filter the list.

Think of an order slip in a restaurant. The waiter (the form) carries the slip to the kitchen (the Server Action), the kitchen changes the storeroom (lib/db.ts), then shouts "rewrite the menu board" (revalidatePath) so everyone in the room sees the new state. The order is handled on the server, not inside one visitor's browser.

Problem → Why → Solution

The problem: bookmarks that only exist in one browser

Using the approach familiar from the React lessons, you make the home page "use client", keep the array in useState, and push a new item when a button is clicked. At first it seems to work.

Then you refresh the page and the new bookmark is gone. Opening the site on your phone does not show it either, because the data only ever lived in one browser tab's memory. A click that happens before the JavaScript has loaded does nothing at all.

app/page.tsx (client-only attempt)
"use client";
import { useState } from "react";

export default function HomePage() {
  const [items, setItems] = useState([{ id: "1", title: "Next.js Docs" }]);
  const add = () => setItems([...items, { id: "2", title: "React Docs" }]);
  // Lives only in this tab: refresh, another device, or no JS = nothing saved
  return <button onClick={add}>Add ({items.length})</button>;
}

Why the change must reach the server

Data that every user should see must be owned by the server. Client state is for temporary UI details such as which panel is open in this tab. A Server Action sends a form submission straight to a server function, so you can change server data without writing a separate API route.

Core concept: form, Server Action, store, revalidate

Because Part 1 made every page call lib/db.ts, only the inside of lib/db.ts changes now. It copies the seed data into a let array and adds getBookmarks(tag?), addBookmark() and deleteBookmark(). It is not a database yet, so every server restart brings back the three seed bookmarks. Here is the journey of one new bookmark.

1. A "use server" file

The first statement of app/actions.ts is "use server". Next.js turns every async function this file exports into a Server Action the browser can call, while the function's code stays on the server.

2. <form action={createBookmark}>

On submit, the browser sends the inputs as a POST request and the action receives a FormData object. Because the form is rendered by a Server Component, it works even before any JavaScript has loaded. This is called progressive enhancement.

3. Read, check, store

formData.get("title") returns a string, a File or null, so String(... ?? "") turns it into a string and trim() cleans it. Anyone can call a Server Action, so check the values again on the server instead of trusting the browser's required attribute. Only then call addBookmark().

4. revalidatePath("/") and redirect("/")

revalidatePath("/") marks the cached result for the "/" page as stale; called from an action, it also updates the UI right away. redirect("/") then sends the user back to the list.

text
One submit, end to end
----------------------
browser                       server
-------                       ------
<form action={createBookmark}>
   | POST (FormData)
   +----------------------->  createBookmark(formData)
                                 read + trim + check
                                 addBookmark()      -> lib/db.ts array
                                 revalidatePath("/")
                                 redirect("/")
   <-----------------------+  fresh "/" with the new card
list shows 4 bookmarks
app/actions.ts
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { addBookmark, deleteBookmark } from "@/lib/db";

export async function createBookmark(formData: FormData) {
  const title = String(formData.get("title") ?? "").trim();
  const url = String(formData.get("url") ?? "").trim();
  const tags = String(formData.get("tags") ?? "")
    .split(",")
    .map((t) => t.trim())
    .filter(Boolean);
  if (!title || !url) return; // Part 3 shows these errors in the form

  addBookmark({ title, url, tags });
  revalidatePath("/");
  redirect("/");
}

export async function removeBookmark(id: string) {
  deleteBookmark(id);
  revalidatePath("/");
}

Notice that both actions live in one app/actions.ts file. The form page and the home page both import from it, and in Part 3 a Client Component will reuse the same action. removeBookmark takes an id instead of formData; the deeper section below shows how that id gets sent.

Mental model: the form is an order slip
  1. Form posts FormData to the server
  2. Action reads, checks, edits the store
  3. revalidatePath marks the page stale
  4. Page re-renders from the store

Every piece of code that changes server data must also say which pages are now out of date.

General pattern: a Server Action and its form

tsx
// app/actions.ts
"use server";
export async function saveThing(formData: FormData) {
  const name = String(formData.get("name") ?? "").trim();
  if (!name) return;
  await store.add(name);
  revalidatePath("/things");
}

// any Server Component
<form action={saveThing}><input name="name" /><button>Save</button></form>

Each input's name attribute is the key you pass to formData.get(). After changing data, revalidate the path that displays it.

Testing the store without the framework

lib/db.ts does not import Next.js, so it runs directly in Node. The file below includes the store plus a simulation of what the action does with a real FormData. In the project, import the type and seed from lib/bookmarks.ts and export the functions.

lib/db.ts (+ quick check)
// lib/db.ts - an in-memory store (Part 1's type and seed data are inlined
// here so the file runs on its own)
type Bookmark = { id: string; title: string; url: string; tags: string[] };
type NewBookmark = Omit<Bookmark, "id">;

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"] },
];

let bookmarks: Bookmark[] = [...seedBookmarks];
let nextId = seedBookmarks.length + 1;

function getBookmarks(tag?: string): Bookmark[] {
  if (!tag) return bookmarks;
  return bookmarks.filter((b) => b.tags.includes(tag));
}

function addBookmark(data: NewBookmark): Bookmark {
  const bookmark: Bookmark = { id: String(nextId++), ...data };
  bookmarks = [bookmark, ...bookmarks]; // newest first
  return bookmark;
}

function deleteBookmark(id: string): boolean {
  const before = bookmarks.length;
  bookmarks = bookmarks.filter((b) => b.id !== id);
  return bookmarks.length < before;
}

// --- what the Server Actions will do, simulated with a real FormData ---
const show = (list: Bookmark[]) =>
  list.map((b) => `${b.id}:${b.title}`).join(" | ") || "(none)";

const form = new FormData();
form.set("title", "  React Docs ");
form.set("url", "https://react.dev");
form.set("tags", "docs, react,");

const tags = String(form.get("tags") ?? "")
  .split(",")
  .map((t) => t.trim())
  .filter(Boolean);
const added = addBookmark({
  title: String(form.get("title") ?? "").trim(),
  url: String(form.get("url") ?? "").trim(),
  tags,
});

console.log("added:", added.id, JSON.stringify(added.tags));
console.log("all:", show(getBookmarks()));
console.log("?tag=docs:", show(getBookmarks("docs")));
console.log("?tag=Docs:", show(getBookmarks("Docs")));
console.log("delete 2:", deleteBookmark("2"));
console.log("delete 2 again:", deleteBookmark("2"));
console.log("seed untouched:", seedBookmarks.length);

Code breakdown

  1. A copy, not the seed itselflet bookmarks: Bookmark[] = [...seedBookmarks];

    The spread creates a new array, so adds and deletes never touch seedBookmarks. The last output line confirms the seed still has 3 items.

  2. Deterministic idsconst bookmark: Bookmark = { id: String(nextId++), ...data };

    The counter is converted with String() so ids stay strings, as in Part 1. A real database usually generates the id for you.

  3. Replace, do not mutatebookmarks = [bookmark, ...bookmarks]; // newest first

    Replacing the array puts the newest bookmark first, which is why 4:React Docs leads the "all:" line.

  4. Delete reports what happenedreturn bookmarks.length < before;

    The first delete returns true; the second finds nothing and returns false. That return value tells you when a double click submitted twice.

  5. Tags are compared exactlyreturn bookmarks.filter((b) => b.tags.includes(tag));

    includes() is case-sensitive, so ?tag=Docs finds nothing. The challenge fixes this by lowercasing tags before they are stored.

You should see
added: 4 ["docs","react"]
all: 4:React Docs | 1:Next.js Docs | 2:MDN Web Docs | 3:Can I use
?tag=docs: 4:React Docs | 1:Next.js Docs | 2:MDN Web Docs
?tag=Docs: (none)
delete 2: true
delete 2 again: false
seed untouched: 3

The form page, the delete button and the tag filter

Once app/bookmarks/new/page.tsx exists, /bookmarks/new reaches the form page instead of being caught by [id] as in Part 1. The home page awaits its searchParams prop to read tag. If the key appears twice, as in ?tag=docs&tag=react, the value is an array, so the type is string | string[] and the page only filters when it got a single string.

The delete button needs an id. removeBookmark.bind(null, b.id) returns a new function with the id already filled in as its first argument. Unlike a hidden input it does not put the id into a form field, and it still works without JavaScript.

app/bookmarks/new/page.tsx + app/page.tsx
// app/bookmarks/new/page.tsx
import { createBookmark } from "@/app/actions";

export default function NewBookmarkPage() {
  return (
    <form action={createBookmark} className="bookmark-form">
      <label htmlFor="title">Title</label>
      <input id="title" name="title" required />
      <label htmlFor="url">URL</label>
      <input id="url" name="url" type="url" required placeholder="https://" />
      <label htmlFor="tags">Tags (comma separated)</label>
      <input id="tags" name="tags" placeholder="docs, react" />
      <button type="submit">Save bookmark</button>
    </form>
  );
}

// app/page.tsx - "/" and "/?tag=docs"
import Link from "next/link";
import { getBookmarks } from "@/lib/db";
import { removeBookmark } from "@/app/actions";

type Props = { searchParams: Promise<{ tag?: string | string[] }> };

export default async function HomePage({ searchParams }: Props) {
  const { tag } = await searchParams;
  const activeTag = typeof tag === "string" ? tag : undefined;
  const bookmarks = getBookmarks(activeTag);

  return (
    <section>
      {activeTag && <p>Tag: {activeTag} <Link href="/">clear</Link></p>}
      <ul className="bookmark-list">
        {bookmarks.map((b) => (
          <li key={b.id} className="card">
            <Link href={`/bookmarks/${b.id}`}>{b.title}</Link>
            {b.tags.map((t) => (
              <Link key={t} href={`/?tag=${encodeURIComponent(t)}`}>#{t}</Link>
            ))}
            <form action={removeBookmark.bind(null, b.id)}>
              <button type="submit">Delete</button>
            </form>
          </li>
        ))}
      </ul>
      {bookmarks.length === 0 && <p>No bookmarks here yet.</p>}
    </section>
  );
}

The limits of an in-memory store

A module-level array lives in one server process's memory. A restart wipes it, editing a file in development can reload the module and bring back the seed, and on serverless hosting each instance has its own copy. That is fine for a learning project; for real user data, use a database as in the database-layer lesson.

In real projects

In real projects

Admin panels, comment forms and todo apps all repeat the same shape almost daily: form, server function, database, page refresh. Before Server Actions this meant an API route, client-side fetch code and loading state for each form. Now most simple mutations fit in one action function.

Keeping the filter in the URL, as ?tag=docs, is the pattern you see in shop category filters and search result pages. Copy the URL to a friend and they see the same filtered list; the back button works and the view can be bookmarked. Keeping the filter in useState would give up all of that, and search engines could not index the filtered pages either.

Common mistakes

Common mistakes

Forgetting "use server"

Without the directive createBookmark is an ordinary function. A plain function cannot be sent to the browser, so rendering the form fails; imported into a Client Component, the server code could even end up in the client bundle. Make "use server" the first statement of the file.

Skipping revalidatePath

The bookmark reaches the store, but the user can keep seeing the old list until a manual refresh. Every action that changes data should revalidate the path that shows it.

Putting redirect inside try/catch

redirect() works by throwing a special error. In try { ... redirect("/") } catch {} the catch swallows it and the redirect never happens. Call redirect outside the try block, after the work is done.

Trusting browser validation alone

A Server Action is a public POST endpoint. With curl, anyone can skip required and type="url" and send something dangerous such as a javascript: URL. The challenge adds server-side validation.

Mini challenge

Write lib/validation.ts

Pull the input-reading logic out of the createBookmark action into pure, testable functions. Clean up the tags and only accept http or https URLs. Afterwards the action just calls readBookmarkForm() and returns early when the result is not ok.

  • parseTags(raw): split on commas, trim, lowercase, drop empties and duplicates, keep at most 5
  • normalizeUrl(raw): null when it is not a URL or not http:/https:, otherwise url.href
  • readBookmarkForm(formData) returns { ok: true, data } or { ok: false, error }
  • Reject both javascript:alert(1) and "nextjs.org" (no scheme)
lib/validation.ts
type NewBookmark = { title: string; url: string; tags: string[] };
type ReadResult = { ok: true; data: NewBookmark } | { ok: false; error: string };

function parseTags(raw: string): string[] {
  // TODO: split, trim, lowercase, drop empty strings
  // TODO: remove duplicates (a Set keeps first-seen order), keep at most 5
}

function normalizeUrl(raw: string): string | null {
  // TODO: new URL() throws on bad input - catch it and return null
  // TODO: only "http:" and "https:" protocols are allowed
}

function readBookmarkForm(formData: FormData): ReadResult {
  // TODO: title is required, url must pass normalizeUrl, tags via parseTags
}

// TODO: try a few inputs, including "javascript:alert(1)" and "nextjs.org"

Expected: ["docs","react","css"], https://nextjs.org/docs (host lowercased), two nulls, then one ok:true result (its url gains a trailing slash: https://react.dev/) and two error results.

Show hint

[...new Set(tags)] removes duplicates while keeping first-seen order. new URL("nextjs.org") throws because there is no scheme, while new URL("javascript:alert(1)") succeeds but its protocol is "javascript:".

Show solution
lib/validation.ts
type NewBookmark = { title: string; url: string; tags: string[] };
type ReadResult = { ok: true; data: NewBookmark } | { ok: false; error: string };

const MAX_TAGS = 5;

function parseTags(raw: string): string[] {
  const tags = raw
    .split(",")
    .map((t) => t.trim().toLowerCase())
    .filter((t) => t.length > 0);
  return [...new Set(tags)].slice(0, MAX_TAGS);
}

function normalizeUrl(raw: string): string | null {
  let url: URL;
  try {
    url = new URL(raw.trim());
  } catch {
    return null; // not a URL at all
  }
  if (url.protocol !== "http:" && url.protocol !== "https:") return null;
  return url.href;
}

function readBookmarkForm(formData: FormData): ReadResult {
  const title = String(formData.get("title") ?? "").trim();
  if (title.length === 0) return { ok: false, error: "Title is required" };
  const url = normalizeUrl(String(formData.get("url") ?? ""));
  if (url === null) return { ok: false, error: "Enter an http(s) URL" };
  const tags = parseTags(String(formData.get("tags") ?? ""));
  return { ok: true, data: { title, url, tags } };
}

function form(entries: Record<string, string>): FormData {
  const fd = new FormData();
  for (const [key, value] of Object.entries(entries)) fd.set(key, value);
  return fd;
}

console.log(JSON.stringify(parseTags("Docs, react , ,docs,CSS")));
console.log(normalizeUrl("  https://Nextjs.org/docs "));
console.log(normalizeUrl("nextjs.org"));
console.log(normalizeUrl("javascript:alert(1)"));
const inputs = [
  { title: " React ", url: "https://react.dev", tags: "Docs" },
  { title: "", url: "https://react.dev" },
  { title: "Old files", url: "ftp://files.example.com" },
];
for (const entries of inputs) {
  console.log(JSON.stringify(readBookmarkForm(form(entries))));
}

Quick quiz 1 / 3

With only the three seed bookmarks in the example store, what does getBookmarks("Docs") (capital D) return?

Quick quiz 2 / 3

A user opens /?tag=docs&tag=react. What does the lesson's home page show?

Quick quiz 3 / 3

When <form action={removeBookmark.bind(null, b.id)}> is submitted, what arguments does removeBookmark receive?

What to remember

  • Because pages only call lib/db.ts, the storage changes in one file
  • An async function from a "use server" file wired to <form action> works even without JavaScript
  • Call revalidatePath after every change, and keep redirect outside try/catch
  • A filter kept in the ?tag= search param can be shared, bookmarked and navigated with back
  • A Server Action is a public endpoint, so validate its input on the server

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 2): Add/Delete Feature and Filtering | Thuta Learning