#nextjs
#cookies
#headers
#http
Day 18 — Cookies & Headers: The HTTP Context
🧭 Day 18 — Cookies & Headers: The HTTP Context
Zero to Hero — Hands-on Next.js Tutorial
In Client Components, we use document.cookie or localStorage.
In Server Components, we don’t have a document. We act as the server handling the incoming request.
Next.js provides two powerful read-only functions: cookies() and headers().
🟦 1. Reading Cookies (cookies())
If you access cookies(), your page automatically becomes Dynamic (cannot be static cached).
import { cookies } from 'next/headers';
export default async function Page() {
const cookieStore = await cookies(); // Awaitable in newer Next.js versions!
const theme = cookieStore.get('theme')?.value; // 'dark' or 'light'
const token = cookieStore.get('auth_token');
return (
<div className={theme === 'dark' ? 'bg-black text-white' : 'bg-white'}>
<h1>Hello, user!</h1>
<p>Your session token is: {token?.value}</p>
</div>
);
}
🟩 2. Writing Cookies (Server Actions)
You cannot set cookies in a Server Component (because the component is streaming HTML). You MUST set cookies in a Server Action or Route Handler.
'use server';
import { cookies } from 'next/headers';
export async function login(formData: FormData) {
// ... validate user ...
// Set the cookie
(await cookies()).set('auth_token', 'xyz-123', {
secure: true,
httpOnly: true,
path: '/'
});
}
🟧 3. Reading Headers (headers())
Useful for User-Agent detection, IP constraints, or referrers.
import { headers } from 'next/headers';
export default async function Page() {
const headersList = await headers();
const userAgent = headersList.get('user-agent');
const ip = headersList.get('x-forwarded-for');
return (
<div>
<p>You are visiting from: {ip}</p>
<p>Browser: {userAgent}</p>
</div>
);
}
🧪 Challenge: Day 18
- Create a form with a “Dark Mode” toggle button.
- The form calls a server action
toggleTheme. - Inside the action, check the current cookie value.
- If ‘dark’, set it to ‘light’ (and vice-versa).
- In your
layout.tsx, read the cookie and apply the classdarkto the<body>tag. - You just built a Zero-JS Theme Toggle! (It works even if you disable JS in the browser).
See you tomorrow for Middleware! 🛡️