Some data isn't in any database: the visitor brings it. Which address they requested, with which filters, what language they browse in, what they chose last time. It arrives with the request and only exists for as long as the request lasts.

Next.js provides it through a handful of asynchronous functions, and with Cache Components they all share one property: they mark the point beyond which nothing can be prerendered. Using them well means reading them in exactly the right place, as low down as possible, and not trusting what they contain. In this lesson AgendaViva will remember the visitor's district and show them its events on the home page, without the home page ceasing to be an instant shell.

  1. The request APIs

API Where it's imported from What it gives you Where it's used
params Prop of pages and layouts Dynamic segments Pages, layouts, Route Handlers
searchParams Prop of pages What follows the ? Pages only
cookies() next/headers Cookies sent by the browser Server
headers() next/headers Request headers Server
draftMode() next/headers Whether draft mode is enabled Server
connection() next/server Nothing: it waits until there's a request Server

They all return promises. Up to version 14, cookies() and headers() were synchronous; you'll come across plenty of old code that reads them without await. The change follows from what you've seen in this module: if reading them can mean "this is where we have to wait for the request", the type that expresses that is a promise.

They're available in Server Components, Server Actions and Route Handlers, with two important differences:

  • A Server Component can only read. Writing a cookie requires sending a header, and by the time you're rendering, the headers may already have gone out (04-04).
  • A Client Component can't use them. Importing next/headers on the client is a build error.

1.1. What they do to a component

async function Greeting() {
  const cookieStore = await cookies() // During prerendering, it stops here
  const name = cookieStore.get('name')?.value
  return <p>{name ? `Hi, ${name}` : 'Hi'}</p>
}
When What happens on reaching await cookies()
At build time There's no request: the component is left out of the shell and the fallback of its <Suspense> is used
During a request It resolves immediately with that visitor's cookies
Without a <Suspense> above it Error: request data during prerendering
Inside 'use cache' Error (section 6)

It resembles the treatment of an uncached query, but the message and the ways out are different. A query can be streamed or cached; request data can only be streamed, because there's nothing shared to store.

Notice that the read is instant during the request. It isn't a wait to shorten, like the ones in 04-03; what costs is leaving everything that depends on it out of the shell.

  1. Reading as low down as possible

This is the mistake that destroys the most performance, and it looks harmless:

// Wrong: the read is at the very top
export default async function RootLayout({ children }: LayoutProps<'/'>) {
  const district = (await cookies()).get('agendaviva-district')?.value
  return (
    <html lang="en">
      <body>
        <Header district={district} />
        {children}
      </body>
    </html>
  )
}

Nothing below that await can be prerendered, on any route: the layout doesn't return children until it has the value. With Cache Components it's an outright error. And the usual reaction, wrapping the <body> in a <Suspense>, silences it and leaves an empty shell.

The fix is the same as with params: read in the component that uses the data.

flowchart TD
    subgraph M["Read at the top"]
      A["RootLayout: await cookies()"] --> B["Header"]
      A --> C["Page"]
    end
    subgraph X["Read low down"]
      D["RootLayout"] --> E["Header"]
      D --> F["Page"]
      F --> G["Suspense"]
      G --> H["YourDistrictEvents: await cookies()"]
    end

In the second one, the shell contains everything except one hole. If the component that needs the data is far down, there's no need to pass it along: any component can call cookies(), and doing so several times in a request costs nothing.

You can also pass the unresolved promise, <YourDistrictEvents cookieStore={cookies()} />, but it's rarely worth it: it complicates the signature to save an import.

Visitor preferences already have two homes in AgendaViva: the filters, in the URL, and favorites and the theme, in localStorage. The preferred district fits neither. It isn't part of the address, because it's personal; and localStorage isn't sent to the server, which is the one running the query.

Where Read by the server Shared with the link Size Use it for
URL Yes Yes Small What someone else should see the same way
Cookie Yes, on every request No 4 KB per cookie Preferences that change what's queried; session
localStorage No No Several MB State that only the browser uses
Database Yes No As much as needed Preferences of people with an account

A cookie travels with every request to the domain. Store little in it, and never data that can be looked up some other way.

3.1. Reading and validating

// lib/preferences.ts
import 'server-only'
import { cache } from 'react'
import { cookies } from 'next/headers'
import { listDistricts } from '@/lib/data/venues'

export const DISTRICT_COOKIE = 'agendaviva-district'

export const getPreferredDistrict = cache(async (): Promise<string | null> => {
  const value = (await cookies()).get(DISTRICT_COOKIE)?.value
  if (!value) return null

  const districts = await listDistricts()
  return districts.includes(value) ? value : null
})
  • It's user input. A cookie can be edited from the browser's tools in two seconds. The value is checked against the districts that exist, as was done with the params in 02-02. And for the same reason, a cookie like role=admin proves nothing: in 08-01 you'll see how a session is protected.
  • get returns an object, { name, value }, or undefined. Forgetting .value is a classic.
  • The query comes after the cheap check. Most visitors won't have the cookie, and for them the database isn't touched. It's one of the necessary sequences from 04-03.
  • React.cache lets several components ask without repeating the query.
  • The name has a prefix and lives in a constant. Whatever writes the cookie will use it too.

3.2. The district's events on the home page

Extend listUpcomingEvents with an optional second parameter. Existing calls don't change:

// lib/data/events.ts
export async function listUpcomingEvents(
  limit = 6,
  district?: string,
): Promise<EventWithVenue[]> {
  const db = await getDb()
  const rows = await db
    .select(withVenueColumns)
    .from(events)
    .innerJoin(venues, eq(events.venueId, venues.id))
    .where(and(isPublished, district ? eq(venues.district, district) : undefined))
    .orderBy(...byDate)
    .limit(limit)
  return rows.map(attachVenue)
}
// app/(public)/_components/your-district-events.tsx
import Link from 'next/link'
import { EventCard } from '@/components/event-card'
import { listUpcomingEvents } from '@/lib/data/events'
import { createEventsUrl } from '@/lib/filters'
import { getPreferredDistrict } from '@/lib/preferences'

export async function YourDistrictEvents() {
  const district = await getPreferredDistrict()
  if (!district) return null

  const events = await listUpcomingEvents(3, district)
  if (events.length === 0) return null

  return (
    <section className="mt-12" aria-labelledby="district-title">
      <h2 id="district-title" className="mb-4 text-xl font-semibold">
        In your district: {district}
      </h2>
      <ul className="grid gap-4 sm:grid-cols-3">
        {events.map((event) => (
          <li key={event.id}>
            <EventCard event={event} />
          </li>
        ))}
      </ul>
      <Link href={createEventsUrl({ district })} className="mt-4 inline-block underline">
        See all events in {district}
      </Link>
    </section>
  )
}
// app/(public)/page.tsx, at the end of HomePage's JSX
<Suspense fallback={null}>
  <YourDistrictEvents />
</Suspense>

The fallback is null because, for most people, the block won't exist: a skeleton that then disappears would be worse than nothing. And that's why it's at the end: when it appears, it only pushes the footer. If it were the first thing on the page, every visitor with a preference would get a jump.

Writing the cookie is a job for a Server Action, and we'll see it in 06-01. To test it, create it from the browser console and reload:

document.cookie = 'agendaviva-district=Riverside; path=/; max-age=31536000; samesite=lax'

Also try agendaviva-district=Mars: nothing appears. Run npm run build and check that the home page is still ◐ /. The Navigation Inspector will show the same shell with and without the cookie: the personalization hasn't cost a single millisecond of the first paint.

  1. Headers

headers() returns a read-only Headers object. The names are case-insensitive and get returns string | null:

import { headers } from 'next/headers'

async function BrowserLanguage() {
  const headersList = await headers()
  const preferred = headersList.get('accept-language') ?? ''
  const prefersSpanish = /^es\b/i.test(preferred.trim())

  return prefersSpanish ? <p>Coming soon in Spanish.</p> : null
}

accept-language is a weighted list (es,en;q=0.9,ca;q=0.8), and here only the first entry is checked. Real language selection happens before the request reaches the page, in 09-05.

Headers are, once again, user input. It's worth knowing how far you can trust each one:

Header Useful for Caution
accept-language Suggesting a language Don't impose it: offer a way to change it
user-agent Statistics, bots It can be faked; don't base the design on it
referer Analytics It can be missing or truncated
host Knowing which domain was requested The client sets it: don't build links with it, use SITE_URL
authorization APIs It's checked, not forwarded to third parties
x-forwarded-for The visitor's IP, behind a proxy See below

4.1. The IP address

Next.js doesn't offer the IP as a property of the request. Behind a proxy, it's usually read from x-forwarded-for, a list to which each proxy appends the address that reached it: client, proxy1, proxy2. The problem is that the client can already send that header with whatever it likes. The first value, which is the one many examples use, is precisely the one an attacker controls.

  • The only reliable values are the ones your infrastructure added, counting from the end, or the specific header your platform documents and overwrites itself.
  • Configure the proxy to replace the incoming header instead of extending it.
  • Don't use it as an identity or as a permission. It's useful for rate-limiting attempts (08-02) and for investigating abuse.
  • It's personal data. If you store it, you need a reason, a retention period and to say so in your privacy policy. Check with whoever handles regulatory compliance.

  1. searchParams, revisited

It's been passed unresolved since 02-02. Let's gather what that implies, because it's the same kind of thing as cookies:

  • It belongs to the request: there are no filters in the /events shell.
  • Only pages receive it. A layout isn't re-rendered when navigating between child pages, and would have a stale value.
  • On the server there's only one way to read it, the prop. On the client, useSearchParams, which requires <Suspense> on the initial load (02-03).
  • A Client Component can also receive the promise and read it with use. It's only worth it if the component needs it once, on load; if it has to react to changes made in the browser, use the hook.

Choosing between prop and hook isn't a matter of style. If the param changes what's queried, it's read on the server. If it changes how what's already loaded looks, on the client.

5.1. Combining the URL with a preference

A reasonable impulse is to use the cookie's district as the default filter for /events. Don't do it silently: two people would open the same link and see different lists, and whoever shares /events wouldn't know what they're sharing. The URL is the source of truth for that page. The preference can suggest ("Show only Riverside", with a link), not decide.

  1. What isn't request data but depends on it

6.1. connection() and io()

Some code doesn't read anything from the visitor and yet has to run on every request: the current time, a random number, an environment variable. That's what these two functions are for:

io(), from next/cache connection(), from next/server
Meaning "What follows is input and output" "Wait until there's a real visitor"
During prerendering Stops Stops
Inside 'use cache' Resolves instantly Error
Recommendation with Cache Components The preferred one Only if the code must wait for a real request

AgendaViva uses io() in getDb, getForecast and SiteNotice. The advantage will show up in module 5: if a function like that is cached, it keeps working without changes.

async function LastUpdated() {
  await io()
  return <p>Updated at {formatTime(new Date())}</p>
}

formatTime would be a function in lib/format.ts. Without the io(), new Date() during prerendering is the error we warned about in 01-04. And watch out for a deduction that seems logical: "if I've already read a cookie, I'm in the request and I can read the clock". With partial prefetching, Next.js can prerender a destination at runtime, and at that moment cookies() does have a value. The documentation warns that a later synchronous read of the clock can still throw an error. The simple rule: before the clock or randomness, await io(), whatever there is above it.

6.2. draftMode

draftMode() addresses another need: letting an editorial team see unpublished content on pages that are cached for everyone else. It's enabled from a Route Handler, which sets a special cookie, and it's checked with const { isEnabled } = await draftMode(). While it's enabled, everything cached runs again on every request. It makes sense with an external content management system. AgendaViva doesn't need it: drafts are visible in the dashboard, with their own queries.

6.3. A warning about use cache

The next module is about storing results and sharing them between visitors. What you've learned here is exactly what can't be stored that way. Inside a function with 'use cache', cookies(), headers() and searchParams throw an error, even if a helper function calls them. And on a route that's rendered during the request, that error may not appear at build time but only at runtime.

It's a safeguard. If a cached function read Ana's cookie, the result would be served to Bruno. The correct pattern is to read outside and pass the value as an argument, which is what YourDistrictEvents already does with listUpcomingEvents(3, district): the first part is personal; the second depends only on a district and can be shared among all its residents. There's also 'use cache: private', which you'll see in 05-02.

  1. Who decides what

To finish, a decision summary:

flowchart TD
    A["What does the content depend on?"] --> B["Nothing: the same for everyone"]
    A --> C["The address"]
    A --> D["The visitor"]
    A --> E["The moment"]
    B --> B1["Shell, or cache if it queries (module 5)"]
    C --> C1["params or searchParams<br/>unresolved, under Suspense"]
    D --> D1{"Does the server need it?"}
    D1 -- No --> D2["localStorage and a Client Component"]
    D1 -- Yes --> D3["cookies() in the component<br/>that uses it, under Suspense"]
    E --> E1["io() and then the clock, under Suspense"]

Common Mistakes and Tips

  • Reading cookies in a layout "to have them handy". It blocks everything below it.
  • Silencing the error with a <Suspense> around the page. The shell ends up empty.
  • Forgetting await or .value. cookies().get doesn't exist on a promise, and get() returns an object.
  • Trying to set in a Server Component. It isn't allowed; use a Server Action or a Route Handler.
  • Trusting the contents of cookies and headers: not for permissions, not for routes, not without validating.
  • Taking the first value of x-forwarded-for as the real IP.
  • Building absolute links with host.
  • Reserving a large hole for a personal block that most people won't see, or putting it first.
  • Reading the clock after cookies() without io().

Exercises

Exercise 1: choosing the source

State where you'd store it and how you'd read it: (1) the list's sort order, by date or by title; (2) whether the visitor has already dismissed the maintenance notice; (3) the number of results per page they prefer; (4) the event they came from to reach the sign-in page, so they can go back afterwards; (5) the last events visited, shown in a sidebar.

Solution

  1. URL, ?sort=. It changes the result and should be shareable. It's read from searchParams and normalized.
  2. localStorage, or a cookie if you want to avoid it appearing for an instant. The server doesn't need it to query.
  3. Cookie if it's a stable preference: it changes the query and shouldn't be imposed on whoever receives the link. It has to be validated against a list (6, 12, 24): without a limit, someone would ask for a million.
  4. URL, /sign-in?returnTo=/events/jazz-night, validating that it's an internal path (08-02).
  5. localStorage with the identifiers and a Client Component. If they had to be rendered on the server, a small cookie with the identifiers, never with the events.

Exercise 2: suggesting the district in the guide

On /events, if the visitor has a preferred district and hasn't filtered by any, show a "Show only …" link that keeps the other filters. Place the read so that the list doesn't wait for the cookie.

Solution

// app/(public)/events/_components/district-suggestion.tsx
import Link from 'next/link'
import { createEventsUrl, normalizeFilters, type RawSearchParams } from '@/lib/filters'
import { getPreferredDistrict } from '@/lib/preferences'

interface Props {
  searchParams: Promise<RawSearchParams>
}

export async function DistrictSuggestion({ searchParams }: Props) {
  const filters = normalizeFilters(await searchParams)
  if (filters.district) return null

  const district = await getPreferredDistrict()
  if (!district) return null

  return (
    <Link
      href={createEventsUrl({ ...filters, district, page: 1 })}
      className="mb-4 inline-block underline"
    >
      Show only {district}
    </Link>
  )
}
// app/(public)/events/page.tsx, between the form and the results
<Suspense fallback={<div aria-hidden className="mb-4 h-6" />}>
  <DistrictSuggestion searchParams={searchParams} />
</Suspense>

It's a sibling of the results, so they load at the same time. The fallback reserves one line; anyone without a preference will see that gap close, a small jump that could be avoided by always leaving the space. The URL is still in charge: without clicking the link, the list is the same for everyone. The course leaves this as practice.

Exercise 3: fixing a layout

This layout prevents any public page from being prerendered. Explain why and rewrite it without losing its functionality.

export default async function PublicLayout({ children }: LayoutProps<'/'>) {
  const [cookieStore, headersList] = await Promise.all([cookies(), headers()])
  const district = cookieStore.get('agendaviva-district')?.value
  const isMobile = headersList.get('user-agent')?.includes('Mobile')

  return (
    <div className={isMobile ? 'p-2' : 'p-8'}>
      {district && <p>Your district: {district}</p>}
      {children}
    </div>
  )
}

Solution

The await comes before children, so every page waits for the request. Besides, the district is shown without validation, and the padding depends on a header that can be faked when CSS is enough.

export default function PublicLayout({ children }: LayoutProps<'/'>) {
  return (
    <div className="p-2 sm:p-8">
      <Suspense fallback={null}>
        <DistrictNotice />
      </Suspense>
      {children}
    </div>
  )
}

async function DistrictNotice() {
  const district = await getPreferredDistrict()
  return district ? <p>Your district: {district}</p> : null
}

Promise.all gave a false sense of optimization: both promises resolve immediately during the request, and what was expensive was where they were awaited.

Conclusion

The request APIs are asynchronous because they mark a boundary: whatever awaits them can't be in the shell. They're read in the component that uses the data, under an appropriately sized <Suspense>, and always validated, because the visitor writes them. Cookies are for preferences that change a query; headers, with caution; the URL remains the page's source of truth. For the clock and randomness, io().

Everything you've read so far is resolved on the server, at render time. But some data changes while the page is already open, like an event's spots left, and other data is requested while the user types. In Fetching Data on the Client you'll see when the browser needs to be the one asking, and how to do it without going back to the problems from 01-01.

© Copyright 2026. All rights reserved