Skip to content

NEXT.JS

Next.js 15 cookies() and headers(): Async Server State

Read request headers, manage authentication cookies, and handle async transitions in Next.js 15 with next/headers, dynamic boundaries, and security flags.

Next.js 15 transforms cookies() and headers() from synchronous utility functions into asynchronous Promises. You must explicitly await both functions before inspecting incoming session tokens or request headers. When we upgraded our App Router architecture in our build website with AI pipeline on Next 15.5.20, unawaited header calls triggered severe compiler warnings and broke downstream middleware handoffs.

This breaking change aligns request-time access with React 19's asynchronous streaming model. Understanding where cookies can be read, where they can be mutated, and how they interact with static prerendering is critical for maintaining zero-leak security boundaries.

Key takeaways

  • Both cookies() and headers() return Promises in Next.js 15; calling them synchronously yields an unresolved Promise rather than a cookie store.
  • Server Components have read-only access to cookies; calling set() or delete() throws a ReadonlyRequestCookiesError.
  • Cookie mutations (writing auth tokens, deleting sessions) must execute inside Server Actions or Route Handlers.
  • Reading await cookies() or await headers() bails out of static prerendering, turning the route or component into a dynamic request-time stream.
  • Always enforce httpOnly: true, secure: true, and sameSite: "lax" on production authentication tokens to prevent XSS exfiltration.

Why cookies() and headers() became async in Next.js 15

In Next.js 14, cookies() and headers() from next/headers were synchronous getters backed by internal AsyncLocalStorage. While convenient, this forced the runtime to block server rendering until the full incoming request context was available.

Next.js 15 changes these APIs into Promises:

app/dashboard/page.tsx
import { cookies, headers } from "next/headers";

export default async function DashboardPage() {
  // Next.js 15 requires awaiting both APIs
  const cookieStore = await cookies();
  const headerList = await headers();

  const session = cookieStore.get("session_id")?.value;
  const userAgent = headerList.get("user-agent") ?? "unknown";

  return (
    <section>
      <h1>Dashboard</h1>
      <p>Session: {session ? "Authenticated" : "Anonymous"}</p>
      <p>Client: {userAgent}</p>
    </section>
  );
}
Terminal
npm run check:cookies-headers
# check:cookies-headers — 6 guards
# ok   all 6 cookies/headers contract assertions passed.

By making these functions asynchronous, Next.js enables Partial Prerendering (PPR). The build engine can prerender the static shell of your layout immediately, deferring only the specific components that await request-specific headers.

APINext.js 14 BehaviorNext.js 15 ContractMutation Allowed?
cookies()Synchronous getterAsynchronous Promise (await cookies())Read-only in RSC; Read/Write in Actions
headers()Synchronous getterAsynchronous Promise (await headers())Read-only across all components
draftMode()Synchronous getterAsynchronous Promise (await draftMode())Read/Write (enable() / disable())
paramsSynchronous props objectAsynchronous Promise (await params)Read-only route segment parameters

Reading request headers in Server Components

Server Components run strictly on the Node.js or Edge runtime. When inspecting request telemetry, client IP addresses, or Authorization bearer tokens, you retrieve headers via standard Web API Headers methods:

app/api/profile/route.ts
import { headers } from "next/headers";
import { NextResponse } from "next/server";

export async function GET() {
  const headerList = await headers();
  const authHeader = headerList.get("authorization");

  if (!authHeader || !authHeader.startsWith("Bearer ")) {
    return NextResponse.json({ error: "Missing bearer token" }, { status: 401 });
  }

  const token = authHeader.slice(7);
  const clientIp = headerList.get("x-forwarded-for")?.split(",")[0].trim() ?? "127.0.0.1";

  return NextResponse.json({ authenticated: true, token, clientIp });
}

Because header names in HTTP/1.1 and HTTP/2 are case-insensitive, headerList.get("authorization") and headerList.get("Authorization") return the same value.

Managing cookies: Server Components vs Server Actions

A fundamental architectural rule of the App Router is that rendering is pure. Server Components cannot modify HTTP response headers because rendering may stream chunks after the HTTP response status and headers are already dispatched over the socket.

To mutate cookies, delegate the operation to a Server Action or a dedicated Route Handler:

app/actions/auth.ts
"use server";

import { cookies } from "next/headers";
import { redirect } from "next/navigation";

export async function loginAction(formData: FormData) {
  const email = formData.get("email") as string;
  const password = formData.get("password") as string;

  // Validate credentials and generate session token
  const sessionToken = "token_abc123_verified";

  const cookieStore = await cookies();
  cookieStore.set("auth_session", sessionToken, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "lax",
    path: "/",
    maxAge: 60 * 60 * 24 * 7, // 7 days
  });

  redirect("/dashboard");
}

export async function logoutAction() {
  const cookieStore = await cookies();
  cookieStore.delete("auth_session");
  redirect("/login");
}

In this Server Action, calling cookieStore.set() appends a Set-Cookie directive to the HTTP response payload before the redirect executes.

Dynamic rendering and Partial Prerendering impact

When your route imports and calls await cookies() or await headers(), Next.js detects an explicit dependency on request state. The compiler tags the component with DYNAMIC_SERVER_USAGE.

If the component is rendered directly in app/layout.tsx without a <Suspense> wrapper:

app/layout.tsx
import { cookies } from "next/headers";

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  // Trap: Awaiting cookies at the root level de-optimizes every page
  const cookieStore = await cookies();
  const theme = cookieStore.get("theme")?.value ?? "dark";

  return (
    <html lang="en" className={theme}>
      <body>{children}</body>
    </html>
  );
}

This root-level call forces every child route into dynamic on-demand rendering, completely forfeiting static HTML generation.

To isolate dynamic request state while keeping static routes pre-built, push the dynamic read down into a leaf component wrapped in Suspense:

components/UserBadge.tsx
import { cookies } from "next/headers";

export async function UserBadge() {
  const cookieStore = await cookies();
  const user = cookieStore.get("username")?.value ?? "Guest";
  return <div className="badge">{user}</div>;
}
app/page.tsx
import { Suspense } from "react";
import { UserBadge } from "@/components/UserBadge";

export default function HomePage() {
  return (
    <main>
      <h1>Pre-rendered Static Marketing Shell</h1>
      <Suspense fallback={<span>Loading user...</span>}>
        <UserBadge />
      </Suspense>
    </main>
  );
}

Under Partial Prerendering, the marketing shell is compiled to static HTML at build time, while the UserBadge stream connects dynamically when the request arrives.

Security contract: HttpOnly, SameSite, and Secure flags

Cookie-based authentication requires defense-in-depth flags. Leaving attributes undefined invites cross-site scripting (XSS) extraction and cross-site request forgery (CSRF):

lib/auth/cookies.ts
import { ResponseCookie } from "next/dist/compiled/@edge-runtime/cookies";

export const SESSION_COOKIE_OPTIONS: Partial<ResponseCookie> = {
  httpOnly: true,
  secure: process.env.NODE_ENV === "production",
  sameSite: "lax",
  path: "/",
  maxAge: 86400 * 14,
};
  • httpOnly: true: Prevents client-side JavaScript (document.cookie) from reading the token, mitigating credential theft via injected third-party scripts.
  • secure: true: Directs browsers to transmit the cookie over TLS connections only, preventing plaintext interception.
  • sameSite: "lax": Disallows sending the cookie on cross-site subrequests (such as image loads or iframe embeds) while preserving authentication on top-level incoming navigations.
  • path: "/": Ensures consistent cookie availability across all subsegments of your domain.

What did not work: mutating cookies in Server Components

During our benchmark testing of Next.js 15, we attempted to implement an auto-refreshing session cookie mechanism directly inside a Server Component layout:

app/admin/layout.tsx
import { cookies } from "next/headers";

export default async function AdminLayout({ children }: { children: React.ReactNode }) {
  const cookieStore = await cookies();
  // Attempting to extend session timestamp during render
  cookieStore.set("last_active", Date.now().toString()); // Throws!

  return <section>{children}</section>;
}

The server instantly crashed with a descriptive runtime exception:

Terminal
Error: Cookies can only be modified in a Server Action or Route Handler.
Read more: https://nextjs.org/docs/app/api-reference/functions/cookies
    at ReadonlyRequestCookies.set (node_modules/next/dist/server/web/spec-extension/adapters/request-cookies.js:52:15)
    at AdminLayout (app/admin/layout.tsx:6:15)

The Next.js architecture strictly isolates read-only request adapters from mutable response builders. The fix required removing the cookieStore.set() call from the render cycle and moving session timestamp updates into an Edge Middleware or a post-request background task using after().

Best practices for next/headers in Next.js 15

  • Always await before accessing: Treat cookies() and headers() as asynchronous calls. Never destructure properties directly from the function invocation.
  • Isolate dynamic calls in leaf components: Avoid reading headers in top-level layout.tsx files. Push calls into granular child components wrapped with <Suspense>.
  • Restrict mutations to Server Actions: Never attempt to write cookies during JSX rendering. Write mutations inside actions or route handlers.
  • Apply strict security flags: Always configure httpOnly: true, secure: true, and sameSite: "lax" on authentication cookies.
  • Use TypeScript type guards: When reading custom header values, guard against null returns using nullish coalescing or type narrowers.

Common mistakes

  • Omitting the await keyword: Invoking const token = cookies().get("token") fails because cookies() returns a Promise. The .get property does not exist on the unfulfilled Promise, evaluating to undefined.
  • Setting cookies during page render: Placing cookieStore.set() inside a component body triggers a ReadonlyRequestCookiesError and halts page rendering.
  • Bailing out of static generation unintentionally: Reading headers for non-critical features (such as user-agent styling) in root layouts converts every static route into an on-demand dynamic route.
  • Passing raw cookie stores to Client Components: Attempting to pass the ReadonlyRequestCookies object across the 'use client' boundary causes serialization errors. Extract strings before passing props.

Decision guide: headers() vs cookies() vs middleware

Choosing where to inspect and manipulate request headers depends on where in the HTTP lifecycle your code executes:

ScenarioRecommended APIExecution Scope
Verifying authentication on protected pagesawait cookies()Server Component or Layout
Setting or invalidating session cookies(await cookies()).set()Server Action or Route Handler
Inspecting user-agent or geolocationawait headers()Server Component (leaf level)
URL rewrites and cross-route auth redirectsrequest.cookies in middleware.tsEdge network request interception
Non-blocking audit logging after response closesafter() with captured headersPost-response background worker

Use cookies() and headers() inside Server Components when you need read-only request state to render UI. Move to Server Actions for state changes, and reserve middleware.ts for fast routing decisions before rendering begins.

Frequently asked questions

Why does calling cookies() or headers() require await in Next.js 15?
In Next.js 15, reading incoming request data was migrated from synchronous getters to asynchronous Promises. This architectural change allows the React Server Components compiler to prerender static layouts ahead of incoming requests while streaming dynamic data when actual headers or cookies are resolved.
Can I write or delete cookies in a Next.js Server Component?
No. Server Components are executed during the render pass, after response headers have begun streaming to the client. Attempting to call cookies().set() or cookies().delete() inside a Server Component throws a runtime error. Cookie mutations must be performed inside Server Actions or Route Handlers.
Does reading headers() or cookies() disable static page optimization?
Yes. Invoking await cookies() or await headers() informs the Next.js compiler that the route depends on per-request HTTP data. This marks the route as dynamic, disabling build-time static HTML generation unless isolated within a Suspense boundary under Partial Prerendering.
How do I pass cookies or headers to Client Components?
Client Components cannot import next/headers directly because browser runtimes lack access to server request headers. Instead, read the required values in an outer Server Component and pass them as serializable props, or read client-accessible document cookies via browser APIs.

Muhammad Kashif

Founder and editor of Devventa, covering AI coding assistants, Next.js and the modern AI development stack.