Explain it simply
Explain it simply
After Part 2, Link Stash works. But working is not the same as finished. A wrong link shows one bare sentence, every browser tab has the same title, and a form filled in wrongly just sits there silently.
It is like a finished house that still needs paint, room numbers and a "this room does not exist" sign. This part adds those four details and puts the app on the internet. No new features: you look at the existing ones through a user's eyes and fix what they would notice.
Problem → Why → Solution
The problem: rough edges a user notices
Look at two places in the code as Part 2 left it. When the detail page finds no bookmark, it returns a sentence as if it were a normal page, so to a search engine /bookmarks/99 looks like a real page. The action quietly exits with return; when the title is missing, so the user keeps pressing Save and nothing tells them why.
These rough edges hide during development and become obvious the moment real users arrive after deployment.
// app/bookmarks/[id]/page.tsx
if (!bookmark) return <p>No bookmark with id "{id}".</p>; // looks like a real page
// app/actions.ts
if (!title || !url) return; // the form gives the user no feedback at all
// app/layout.tsx: no metadata -> every tab shows the same titleWhy use the framework's conventions
Next.js has dedicated files and functions for "not found", "still loading" and "this page's title". Hand-written if statements only change the visible UI; the conventions also let Next.js set the response status, the <head> tags and the Suspense boundaries correctly.
Core concept: four pieces of polish, then deploy
1. notFound() and not-found.tsx
Calling notFound() from next/navigation stops the function on the spot and renders the nearest not-found.tsx. Next.js also tells search engines not to index the page, normally with a 404 status, or with a noindex tag if the response was already streaming. notFound() returns never, so TypeScript knows bookmark is defined on the lines after it.
2. Metadata: a template plus generateMetadata
In the root layout, export const metadata with title: { default, template: "%s | Link Stash" }. On the detail page, generateMetadata() awaits params and returns the bookmark's title, so the tab reads "MDN Web Docs | Link Stash". Open Graph data improves the preview when the link is shared in chat apps.
3. loading.tsx
A loading.tsx in a folder makes Next.js wrap that segment's page in a Suspense boundary automatically and show the skeleton immediately while data arrives. Our in-memory store is too fast to notice; to see the skeleton, add a short delay inside getBookmarks() during development.
4. Form errors with useActionState
Instead of return;, the action returns an { errors, values } state. In a Client Component, useActionState(createBookmark, initialState) hands you that state, a formAction to put on the form, and a pending flag. Each error is shown next to its field, and the button is disabled while pending.
| File / function | What the user notices |
|---|---|
| notFound() + not-found.tsx | A "Bookmark not found" page with a link home |
| metadata + generateMetadata | Distinct tab titles and share previews |
| loading.tsx | An instant skeleton while data loads |
| useActionState | Errors beside fields; typed values survive |
Once the polish is done, run npm run build locally before deploying. The dev server only compiles a page when you open it, while a build compiles every route and runs the type check, so errors you never saw in development show up here.
- Does it exist? notFound()
- What page is this? metadata
- Still loading? loading.tsx
- What went wrong? useActionState
Each piece of polish answers a question before the user has to ask it.
General pattern: metadata and notFound
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { key } = await params;
const item = await findItem(key);
return item ? { title: item.name } : { title: "Not found" };
}
export default async function Page({ params }: Props) {
const item = await findItem((await params).key);
if (!item) notFound();
return <h1>{item.name}</h1>;
}generateMetadata and the page receive the same params, and both must handle the missing item. With a real database query, wrap the lookup in React's cache() so one request does not query twice.
Polishing the detail page
Replace app/bookmarks/[id]/page.tsx, which has existed since Part 1, with the code below, and add not-found.tsx in the same folder. getBookmark() from lib/db.ts is used unchanged from Part 2.
// app/bookmarks/[id]/page.tsx
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getBookmark } from "@/lib/db";
type Props = { params: Promise<{ id: string }> };
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { id } = await params;
const bookmark = getBookmark(id);
if (!bookmark) return { title: "Bookmark not found" };
return {
title: bookmark.title, // the layout template adds " | Link Stash"
description: `Saved link to ${new URL(bookmark.url).hostname}`,
openGraph: { title: bookmark.title, url: `/bookmarks/${bookmark.id}` },
};
}
export default async function BookmarkPage({ params }: Props) {
const { id } = await params;
const bookmark = getBookmark(id);
if (!bookmark) notFound(); // stops here and renders not-found.tsx
return (
<article>
<h1>{bookmark.title}</h1>
<a href={bookmark.url} target="_blank" rel="noreferrer">{bookmark.url}</a>
<p>Tags: {bookmark.tags.join(", ") || "none"}</p>
</article>
);
}
// app/bookmarks/[id]/not-found.tsx
import Link from "next/link";
export default function BookmarkNotFound() {
return (
<section>
<h1>Bookmark not found</h1>
<p>It may have been deleted, or the link has a typo.</p>
<Link href="/">Back to all bookmarks</Link>
</section>
);
}Code breakdown
- Async metadata from params
export async function generateMetadata({ params }: Props): Promise<Metadata> {params is a Promise, so generateMetadata is async and awaits it. The return value must match Next.js's Metadata type, so a misspelled field is a compile error.
- Only the bookmark's part of the title
title: bookmark.title, // the layout template adds " | Link Stash"Do not repeat "| Link Stash" here. The root layout's template wraps the titles of child segments automatically.
- Stop and show not-found.tsx
if (!bookmark) notFound(); // stops here and renders not-found.tsxnotFound() works by throwing, so the return below is never reached. For the same reason, do not wrap it in try/catch.
- Narrowed after notFound()
<h1>{bookmark.title}</h1>Because notFound() has type never, bookmark is narrowed to Bookmark here, with no ? or ! needed.
- A not-found page with a way out
<Link href="/">Back to all bookmarks</Link>Giving the error page a way out saves the user from hunting for the back button. The file renders inside the layout, so the header stays visible too.
Opening /bookmarks/2 shows the tab title "MDN Web Docs | Link Stash" and the title, link and "Tags: docs" on the page. Opening /bookmarks/99 shows the not-found page with the heading "Bookmark not found" and a "Back to all bookmarks" link, and the tab reads "Bookmark not found | Link Stash".Layout metadata, loading and form feedback
// app/layout.tsx - add above RootLayout
import type { Metadata } from "next";
export const metadata: Metadata = {
title: { default: "Link Stash", template: "%s | Link Stash" },
description: "Save links with tags and find them again.",
openGraph: { siteName: "Link Stash", type: "website" },
};
// app/loading.tsx - shown while a page below it is loading
export default function Loading() {
return (
<ul className="bookmark-list" aria-busy="true">
{[1, 2, 3].map((n) => <li key={n} className="card skeleton" />)}
</ul>
);
}For form feedback, Part 2's createBookmark now accepts (prevState, formData) and returns a FormState, handing validation to validateBookmarkForm(), which you write in the challenge. The form moves into a Client Component because useActionState is a hook; page.tsx stays a Server Component that just renders <BookmarkForm />.
React 19 resets uncontrolled form fields after an action finishes. Returning the values in the state and feeding them back through defaultValue is what keeps the user's typing when an error appears.
// app/actions.ts - createBookmark now returns a FormState
export async function createBookmark(
_prev: FormState,
formData: FormData,
): Promise<FormState> {
const { state, data } = validateBookmarkForm(formData);
if (!data) return state; // the form shows state.errors next to each field
addBookmark(data);
revalidatePath("/");
redirect("/");
}
// app/bookmarks/new/BookmarkForm.tsx
"use client";
import { useActionState } from "react";
import { createBookmark } from "@/app/actions";
import { initialState } from "@/lib/validation";
export function BookmarkForm() {
const [state, formAction, pending] = useActionState(createBookmark, initialState);
return (
<form action={formAction} className="bookmark-form">
<label htmlFor="title">Title</label>
<input id="title" name="title" defaultValue={state.values.title} />
{state.errors.title && <p role="alert">{state.errors.title}</p>}
<label htmlFor="url">URL</label>
<input id="url" name="url" defaultValue={state.values.url} />
{state.errors.url && <p role="alert">{state.errors.url}</p>}
<label htmlFor="tags">Tags</label>
<input id="tags" name="tags" defaultValue={state.values.tags} />
{state.errors.tags && <p role="alert">{state.errors.tags}</p>}
<button type="submit" disabled={pending}>
{pending ? "Saving..." : "Save bookmark"}
</button>
</form>
);
}Check the build, then deploy to Vercel
1. A production build locally
Run npm run build and fix errors until it passes. Then npm run start serves production mode at http://localhost:3000; try add, delete, filter and /bookmarks/99 once more.
2. Push to GitHub
create-next-app already initialised a git repository with a .gitignore. Create a new GitHub repository and push the code.
3. Import it on Vercel
Import the repository from the Vercel dashboard. It detects Next.js, so the default settings deploy it, and this project needs no environment variables. Every later push redeploys automatically.
The in-memory store on Vercel
Vercel runs server code in many short-lived instances. Each one has its own bookmarks array, so an added bookmark can vanish on refresh or appear only sometimes, while the three seed bookmarks are always there. That is fine for a demo; for real use, back lib/db.ts with a database. The pages and actions do not change.
In real projects
In real projects
Product teams usually keep a "definition of done" checklist. A feature only counts as done when it has an empty state, a not-found state, a loading state, error messages and page titles, and "what happens with a wrong id?" is a standard question in almost every code review.
Metadata matters to marketing too: when a product link is shared in chat apps or on social media, a correct title and description are what make people click. For deployment, most teams connect a platform such as Vercel to GitHub and get a preview URL for every pull request, so every change is checked on a real, shareable URL before anyone merges it.
Common mistakes
Common mistakes
Expecting a child openGraph to merge with the parent's
Metadata is merged shallowly. When the detail page returns openGraph: { title, url }, it replaces the layout's whole openGraph object and siteName disappears. Repeat the fields you need in the child, or spread a shared object.
Deploying without a local build
The dev server only compiles pages you open, so a type error in a page you never visited only appears at build time. Running npm run build locally is much faster than reading a failed log on Vercel.
Calling notFound() inside try/catch
Like redirect(), notFound() works by throwing. If a catch block swallows it, the not-found page never appears and the page keeps rendering.
Expecting the deployed app to keep data
An in-memory array is not a database on Vercel. Disappearing bookmarks are not a bug in your code; they are the result of the storage choice.
Mini challenge
validateBookmarkForm() that collects every field error
Part 2's readBookmarkForm() returns only the first error. For the useActionState form, write validateBookmarkForm(), which collects the error for every field and also returns the values the user typed.
- Return { state: { errors, values }, data }, with data null when there are errors
- Title: required, at most 80 characters
- URL: must be http or https; store url.href when valid
- Tags: lowercase, no duplicates, an error when there are more than 5
- Put what the user typed (trimmed) back into values
type FieldErrors = { title?: string; url?: string; tags?: string };
type FormValues = { title: string; url: string; tags: string };
type FormState = { errors: FieldErrors; values: FormValues };
type NewBookmark = { title: string; url: string; tags: string[] };
function httpUrl(raw: string): string | null {
// TODO: new URL() inside try/catch; only http: and https: -> url.href
}
function validateBookmarkForm(formData: FormData): {
state: FormState;
data: NewBookmark | null;
} {
// TODO: read title, url, tags as strings (trim title and url)
// TODO: add an error per field instead of returning at the first problem
// TODO: data is null whenever errors has any key
}
// TODO: run three attempts: empty title + "react.dev", a valid one, 6 tagsExpected: The first attempt reports both the title and url errors and keeps "react.dev" in values. The second has errors {} and data with url https://react.dev/ and tags ["docs","react"]. The third reports only a tags error.
Show hint
Start with errors = {} and set errors.title = ... whenever you find a problem. At the end, Object.keys(errors).length === 0 tells you whether it passed. An if / else if chain for the title gives at most one title message.
Show solution
type FieldErrors = { title?: string; url?: string; tags?: string };
type FormValues = { title: string; url: string; tags: string };
type FormState = { errors: FieldErrors; values: FormValues };
type NewBookmark = { title: string; url: string; tags: string[] };
const MAX_TITLE = 80;
const MAX_TAGS = 5;
function httpUrl(raw: string): string | null {
try {
const url = new URL(raw);
return url.protocol === "http:" || url.protocol === "https:" ? url.href : null;
} catch {
return null;
}
}
function validateBookmarkForm(formData: FormData): {
state: FormState;
data: NewBookmark | null;
} {
const read = (key: string) => String(formData.get(key) ?? "");
const values: FormValues = {
title: read("title").trim(),
url: read("url").trim(),
tags: read("tags"),
};
const errors: FieldErrors = {};
if (!values.title) errors.title = "Give the bookmark a title";
else if (values.title.length > MAX_TITLE) {
errors.title = "Keep the title under 80 characters";
}
const url = httpUrl(values.url);
if (url === null) errors.url = "Enter an http(s) URL";
const tags = [...new Set(values.tags.split(",").map((t) => t.trim().toLowerCase()))]
.filter(Boolean);
if (tags.length > MAX_TAGS) errors.tags = `Use at most ${MAX_TAGS} tags`;
const ok = Object.keys(errors).length === 0 && url !== null;
const data = ok ? { title: values.title, url, tags } : null;
return { state: { errors, values }, data };
}
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;
}
const attempts = [
{ title: "", url: "react.dev", tags: "" },
{ title: "React Docs", url: "https://react.dev", tags: "Docs, react, docs" },
{ title: "Too many", url: "https://example.com", tags: "a,b,c,d,e,f" },
];
for (const entries of attempts) {
const { state, data } = validateBookmarkForm(form(entries));
console.log("errors:", JSON.stringify(state.errors));
console.log(" kept:", JSON.stringify(state.values.url), "data:", JSON.stringify(data));
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Call notFound() for a missing item and add not-found.tsx to the segment; never wrap it in try/catch
- Use a title template in the layout and generateMetadata on dynamic pages; remember openGraph merges shallowly
- loading.tsx wraps a segment in a Suspense boundary automatically
- Returning errors and values through useActionState shows errors beside fields and keeps the user's typing
- Run npm run build locally before deploying; in-memory data does not persist on Vercel
Next.js Documentation — Next.js