Topic 30 of 39
Cookies & Headers
Overview
Next.js provides dynamic functions (cookies() and headers()) to read and mutate incoming request data directly within Server Components and Server Actions. Reading these opts the route into Dynamic Rendering.
Syntax
tsx
import { cookies, headers } from 'next/headers';
export default function UserProfile() {
// Read a cookie
const cookieStore = cookies();
const theme = cookieStore.get('theme')?.value;
// Read headers
const headersList = headers();
const userAgent = headersList.get('user-agent');
return <div>Theme: {theme}</div>;
}Common Pitfalls
- Trying to
set()a cookie from a Server Component. You can only read them in components. To set cookies, you must use a Server Action or Route Handler. - Forgetting that using these functions removes static caching.
Interview Questions
Q:
Can you modify headers or set cookies directly inside a Server Component?
A:
No, you can only read them. To mutate cookies or headers, you must do so in a Server Action, Route Handler, or Middleware.
Real-World Example
Setting a preference cookie via a Server Action.
example
tsx
'use server';
import { cookies } from 'next/headers';
export async function saveThemePreference(theme: string) {
cookies().set('theme', theme, { secure: true, path: '/' });
}Check Your Knowledge
Test your understanding of Cookies & Headers with these quick questions.