Skip to content

Normalize Request Values

The Course
•
18 min study

The decision

A URL is an input boundary, even when your own links created it. The Study Library accepts a search term, but a repeated query key arrives as an array. Normalize at the page boundary so the rest of the app sees one shape.

Read, predict, run

Open app/page.jsx and lib/contract.js. The page unwraps searchParams; the function picks the first string, trims it and caps its length. The case table deliberately includes a repeated value and a missing one. Decide whether first-value-wins is the right policy before copying it:

JSX
export default async function Page({ searchParams }) {
  const { q } = await searchParams;
  return (
    <main>
      <h1>Normalize Request Values</h1>
      <nav>
        <Link href="/?q=cache">Cache</Link>
        <Link href="/?q=first&q=second">Repeated q</Link>
        <Link href="/">Clear</Link>
      </nav>
      <p>Current query: {run(q) || "(empty)"}</p>
      <Cases />
    </main>
  );
}
JavaScript
export function run(value) {
  const first = Array.isArray(value) ? value[0] : value;
  return typeof first === "string" ? first.trim().slice(0, 60) : "";
}

Before pressing Run, predict what run returns for null, " cache " and [" first ", "second"], from the code above. Write your answers down first: after Run, the case table shows the expected values beside the actual ones.

Normalize Request Values Next.js · 5 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library · Practice lab</strong> </header> {children} </body> </html> ); } import Link from "next/link"; import { run } from "@/lib/contract.js"; import Cases from "./Cases.jsx"; export default async function Page({ searchParams }) { const { q } = await searchParams; return ( <main> <h1>Normalize Request Values</h1> <nav> <Link href="/?q=cache">Cache</Link> <Link href="/?q=first&q=second">Repeated q</Link> <Link href="/">Clear</Link> </nav> <p>Current query: {run(q) || "(empty)"}</p> <Cases /> </main> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run(value) { const first = Array.isArray(value) ? value[0] : value; return typeof first === "string" ? first.trim().slice(0, 60) : ""; } export const examples = [ [null, ""], [" cache ", "cache"], [[" first ", "second"], "first"], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Check your prediction
  • Input null → "".
  • Input " cache " → "cache".
  • Input [" first ", "second"] → "first".

The case table computes these results on the server side of the simulation. It compares values; it does not prove a production deployment or database works.

The failure to avoid

Calling trim on an array crashes the page. Converting everything with String hides the malformed shape instead of choosing a policy.

Trace [" first ", "second"] through run: which line turns the array into one string, and what would trim() do if that line were missing?

Exercise

Extend the contract

Collapse repeated spaces inside a search term as well. Keep first-value-wins, trimming and the 60-character limit.

Edit lib/contract.js, then rerun the original cases. If the requested rule changes an earlier result, update that expected value deliberately. Keep the other cases. Add the acceptance cases to examples so the preview checks them too.

  • Input " server actions " must return "server actions".
  • Input "a\tb" must return "a b".
Your working space Next.js · 5 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library · Practice lab</strong> </header> {children} </body> </html> ); } import Link from "next/link"; import { run } from "@/lib/contract.js"; import Cases from "./Cases.jsx"; export default async function Page({ searchParams }) { const { q } = await searchParams; return ( <main> <h1>Normalize Request Values</h1> <nav> <Link href="/?q=cache">Cache</Link> <Link href="/?q=first&q=second">Repeated q</Link> <Link href="/">Clear</Link> </nav> <p>Current query: {run(q) || "(empty)"}</p> <Cases /> </main> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run(value) { const first = Array.isArray(value) ? value[0] : value; return typeof first === "string" ? first.trim().slice(0, 60) : ""; } export const examples = [ [null, ""], [" cache ", "cache"], [[" first ", "second"], "first"], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Hint 1: the idea

Normalizing means choosing one form for many spellings of the same search. A run of spaces or a tab inside a term is another spelling, just like the spaces around it.

Hint 2: a first step

Normalize internal whitespace before taking the final length limit; test a tab as well as two spaces.

Show one solution

Replace the exported run function and any constants shown here; keep the examples export underneath it. Compare the result with your own approach.

JavaScript
export function run(value) {
  const first = Array.isArray(value) ? value[0] : value;
  return typeof first === "string"
    ? first.trim().replace(/\s+/g, " ").slice(0, 60)
    : "";
}

\s matches any whitespace character, tabs and line breaks included, and + takes a whole run of them, so a tab or three spaces become one space in one step. The replacement comes after trim() and before slice(0, 60), so the limit counts the cleaned text. Replacing only two spaces with one would miss tabs and runs of three.

Explain it without the code

A reader opens /?q=Server%20%20Actions. Write the value the page receives, what run returns, and why searching with the raw value could miss results.

Going further

Read the Next.js guide for the framework boundary around this rule. The preview runs code-playpad's Next.js simulation. Real caching, hydration, authentication and persistence require the real-server checks described on Day 7.

Was this article helpful?

Your response is saved on this device.