Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Next.js
Next.jsmedium

How do you read cookies or headers in a Server Component in Next.js?

Tags
#cookies#headers#server-components
Back to categoryPractice quiz

Answer

Use `cookies()` and `headers()` from `next/headers` in a Server Component. They read the incoming request on the server; in the browser you read cookies differently (and headers aren’t available the same way).

import { cookies, headers } from 'next/headers'

export default function Page() {
  const cookieStore = cookies()
  const theme = cookieStore.get('theme')?.value
  const ua = headers().get('user-agent')
  return <div>{theme} {ua}</div>
}

Advanced answer

Deep dive

Expanding on the short answer — what usually matters in practice:

  • Context (tags): cookies, headers, server-components
  • Lifecycle: what happens at runtime (render/build, request/response, background jobs).
  • Caching: where cache lives, cache keys, how to invalidate without chaos.
  • Security: authn/authz, secrets, attack surface (SSRF/CSRF).
  • Explain the "why", not just the "what" (intuition + consequences).
  • Trade-offs: what you gain/lose (time, memory, complexity, risk).
  • Edge cases: empty inputs, large inputs, invalid inputs, concurrency.

Examples

Here’s an additional example (building on the short answer):

import { cookies, headers } from 'next/headers'

export default function Page() {
  const cookieStore = cookies()
  const theme = cookieStore.get('theme')?.value
  const ua = headers().get('user-agent')
  return <div>{theme} {ua}</div>
}

Common pitfalls

  • Too generic: no concrete trade-offs or examples.
  • Mixing average-case and worst-case (e.g., complexity).
  • Ignoring constraints: memory, concurrency, network/disk costs.

Interview follow-ups

  • When would you choose an alternative and why?
  • What production issues show up and how do you diagnose them?
  • How would you test edge cases?

Related questions

Next.js
Server Components vs Client Components: when do you choose each?
#nextjs#server-components#client-components
Next.js
Browser-only library in App Router: how do you use it without breaking SSR/Server Components?
#nextjs#server-components#client-components
Next.js
Next.js App Router auth: how do you keep it secure and SSR
-friendly?
#nextjs#auth#cookies
Next.js
Static vs dynamic rendering — how do you force a route to be dynamic and why?
#ssr#dynamic#cache
Next.js
Server Components vs Client Components in Next.js App Router?
#app-router#server-components#client-components