Skip to article content
FrontendXLesson 12 / 20

Request APIs: cookies, headers, searchParams

A version-qualified path through the Next.js App Router: server components, client boundaries, data fetching, caching layers, streaming, error handling, proxy, images, performance, testing and deployment, with the Next.js 15 and 16 behavior changes called out where they matter.

intermediate · about 45 minutes · 6 exercises

  • Predict
  • Explain
  • Implement
  • Debug
  • Test
  • Interview

What you will be able to do

#
  • Read and write cookies and headers through the awaited request APIs in every sanctioned context.
  • Explain which contexts may set cookies and which may only read them.
  • Handle searchParams as a promise and describe the effect of request APIs on rendering.

Overview

#

Everything is await

The request APIs are async functions whose results you await: const cookieStore = await cookies(), const headersList = await headers(), const draft = await draftMode(). Next.js 15 introduced this as a breaking change with temporary synchronous access; Next.js 16 removed synchronous access entirely, so cookies().get('x') without await is a hard error, not a deprecation warning.

Reading and writing cookies

Reading is allowed in Server Components, Server Actions, Route Handlers and proxy. Writing is narrower: Server Actions and Route Handlers may set or delete cookies; Server Components and proxy may only read. Setting a cookie inside a Server Action triggers a re-render of the current page so the UI reflects the new value:

snippet.ts
'use server';
export async function setTheme(theme: string) {
  const cookieStore = await cookies();
  cookieStore.set('theme', theme, { httpOnly: false, path: '/', maxAge: 31536000 });
}

Cookie options include httpOnly, secure, sameSite, maxAge, expires, domain, path (default '/'), and partitioned. Treat httpOnly plus secure plus sameSite as the default posture for session cookies.

searchParams and rendering impact

searchParams arrives to pages as a promise and is the query-string counterpart of params. Reading any request API makes the containing segment request-time: under the previous model it opts the route into dynamic rendering; under Cache Components the access must be inside a Suspense boundary or the route fails prerender validation. The design consequence: keep request-time reads at the leaves, never in the root layout, so the largest possible subtree stays prerenderable.

Draft mode

draftMode() reads and toggles a preview bypass used by headless CMS integrations: a Route Handler enables it, pages then read uncached draft content, and draft.disable() exits. It is cookie-backed and per-visitor.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    Which of these lines fail in Next.js 16? 1. const theme = cookies().get('theme')?.value 2. const theme = (await cookies()).get('theme')?.value 3. const ua = headers().get('user-agent') 4. const { q } = await searchParams

    Choose the best answer
  2. Exercise 2Explain

    Explain why Server Components may read but not set cookies, and where the write contexts are.

    Reveal the reference answer
    reference.text
    A cookie write changes the HTTP response headers. Rendering a Server Component produces part of a response body, potentially shared across requests when the route is prerendered, so there is no single response to mutate and no single request it belongs to; allowing writes there would make output depend on mutation order. Server Actions and Route Handlers are per-request request-response cycles with a definite response object, so they can set cookies. This is why the theme-toggle pattern puts the write in an action and the read in the component: the action owns the response, the component only observes state.

    Authored expected output: Writes mutate response headers, which only per-request contexts own.

    The restriction follows from render sharing, not arbitrary API design.

  3. Exercise 3Implement

    Implement a locale preference: a Server Action setLocale(locale) that validates against a whitelist, stores it in a cookie for one year, and a server page that reads it and renders a greeting. Keep the read out of the root layout.

    starter.tsx
    // app/actions.ts
    // TODO: setLocale with validation
    
    // app/welcome/page.tsx
    // TODO: read cookie, render greeting

    Reveal the reference answer
    reference.tsx
    // app/actions.ts
    'use server';
    import { cookies } from 'next/headers';
    
    const LOCALES = ['en', 'de', 'fr'] as const;
    
    export async function setLocale(locale: string) {
      if (!LOCALES.includes(locale as (typeof LOCALES)[number])) {
        return { error: 'Unsupported locale' };
      }
      const cookieStore = await cookies();
      cookieStore.set('locale', locale, { maxAge: 31536000, path: '/', sameSite: 'lax' });
    }
    
    // app/welcome/page.tsx
    import { cookies } from 'next/headers';
    
    export default async function WelcomePage() {
      const locale = (await cookies()).get('locale')?.value ?? 'en';
      const greeting = locale === 'de' ? 'Willkommen' : locale === 'fr' ? 'Bienvenue' : 'Welcome';
      return <h1>{greeting}</h1>;
    }
    
    // The read lives in the page, not the root layout, so other routes stay prerenderable.

    Authored expected output: The greeting reflects the stored locale; other routes are unaffected.

    Whitelist validation prevents arbitrary cookie values; leaf placement protects rendering mode.

  4. Exercise 4Debug

    After upgrading to Next.js 16, every page that renders this component crashes. Find the bug. import { cookies } from 'next/headers'; export function ThemeBanner() { const theme = cookies().get('theme')?.value ?? 'light'; return <p>Theme: {theme}</p>; }

    starter.tsx
    import { cookies } from 'next/headers';
    export function ThemeBanner() {
      const theme = cookies().get('theme')?.value ?? 'light';
      return <p>Theme: {theme}</p>;
    }

    Reveal the reference answer
    reference.tsx
    cookies() is called without await, which Next.js 16 rejects because synchronous access was removed. Make the component async and await it: export default async function ThemeBanner() { const theme = (await cookies()).get('theme')?.value ?? 'light'; ... }. The upgrade codemod for async request APIs automates this across a codebase.

    Authored expected output: The banner renders the theme after the await is added.

    The 16 removal is the strictest version-qualified change in the request API family.

  5. Exercise 5Test

    Write a pure function cookieWriteContext(context: 'server-component' | 'server-action' | 'route-handler' | 'proxy') returning 'write' for server-action and route-handler, 'read' for server-component and proxy. Assert all four, and assert that an unknown context returns 'error'.

    starter.ts
    export function cookieWriteContext(
      context: 'server-component' | 'server-action' | 'route-handler' | 'proxy' | string,
    ): 'write' | 'read' | 'error' {
      // TODO
    }

    Reveal the reference answer
    reference.ts
    export function cookieWriteContext(
      context: 'server-component' | 'server-action' | 'route-handler' | 'proxy' | string,
    ): 'write' | 'read' | 'error' {
      if (context === 'server-action' || context === 'route-handler') return 'write';
      if (context === 'server-component' || context === 'proxy') return 'read';
      return 'error';
    }
    
    // The matrix encodes the sanctioned contexts from the lesson.

    Authored expected output: All five assertions pass.

    The read/write split is small enough to encode and important enough to memorize.

  6. Exercise 6Interview

    An interviewer asks: your root layout reads a theme cookie and the whole app became dynamic. Walk me through the diagnosis and three possible fixes with trade-offs.

    Reveal the reference answer
    reference.text
    Diagnosis: a request API read in the root layout makes every segment below it request-time, because the layout output depends on per-request state; the build output confirms every route lost its static marker. Fix one: move the theme to a client component reading localStorage or a cookie via document.cookie, trading server knowledge of the theme for full prerenderability; risk is a flash before hydration unless a script sets the attribute early. Fix two: keep the server read but isolate it in a Suspense boundary inside the layout so the shell prerenders and the theme attribute streams in; cost is a small async hole in every page. Fix three: drop the cookie and use a class-on-html default with client-side override only, simplest and fully static, but the server-rendered HTML no longer reflects preference. The right choice depends on how much the first paint depends on the theme.

    Authored expected output: Diagnosis plus three fixes with explicit trade-offs.

    This question fuses request APIs, rendering modes and product trade-offs.

Common misconceptions

#
  • cookies() is synchronous. It returns a promise; awaiting is mandatory and sync access was fully removed in Next.js 16.
  • Any server code can set cookies. Server Components and proxy can only read; writes belong to Server Actions and Route Handlers.
  • Reading cookies in a layout is free. It makes every route below that layout request-time, which is why reads belong in leaves.
  • searchParams is a plain object. It is a promise you await, and its presence in a page shapes rendering mode.

Follow-up practice

#
  • nextjs-static-dynamic-rendering
  • nextjs-proxy-middleware

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.