next/headers — cookies / headers / redirect / notFound Helpers
next/headers — cookies / headers / redirect / notFound Helpers
💡 Why Learn This? — 4 Tools Exclusive to Server Code
4 Helpers — Where to Use Them and Their Signatures
1. cookies() — Read Request Cookies, Write Response Cookies
Reading is available anywhere — Server Components, Actions, and Route Handlers. Writing (set/delete) is only allowed in Server Actions and Route Handlers.
2. headers() — Read Request Headers (Read-Only)
Modifying response headers is not possible here (use middleware or NextResponse instead).
3. redirect() — Redirect to Another Path
- ▸Code after
redirect()does not execute (TypeScript even narrows types accordingly). - ▸Available in Server Components, Actions, and Route Handlers.
- ▸For permanent redirects, use
permanentRedirect()(HTTP 308).
4. notFound() — Trigger the 404 Page
If a not-found.tsx exists in the same folder or a nearby ancestor, it will be rendered.
5. Side Effect of Calling These — Page Switches to Dynamic Rendering
Regardless of the fetch cache mode, the page switches to dynamic rendering. This is the #1 reason a page unexpectedly becomes SSR on every request.
6. Commonly Used Together — A Typical Pattern
💡 💡 next/headers in Practice — 5 Tips
1. Calling cookies() switches the page to dynamic rendering
Pages that read cookies are SSR on every request. Avoid this call if you want SSG.
2. headers() does the same — triggers dynamic rendering
User-agent branching, A/B testing, etc. — the response differs per request, so static rendering is not possible.
3. redirect / notFound behave like throw
Code after the call does not run. TypeScript narrows types inside the if block, guaranteeing variables are non-null.
4. cookies().set/delete only works in Server Actions or Route Handlers
In a Server Component you can only read cookies. Writes must happen in a mutation context.
5. Always use optional chaining: cookies().get('x')?.valuecookies().get('x') returns RequestCookie | undefined. Never access .value directly — use ?.value for safe access.