How do you read cookies in a Next.js server component?
Short answer
The App Router gives you a cookies function from next/headers that you can call inside a server component to read any cookie sent with the request, letting you access things like a session token or a user's saved preferences without needing any client side code.
Advertisement
AModel answer
The App Router gives you a cookies function from next/headers that you can call inside a server component to read any cookie sent with the request, letting you access things like a session token or a user's saved preferences without needing any client side code.
import { cookies } from 'next/headers';
export default async function Page() {
const cookieStore = await cookies();
const theme = cookieStore.get('theme');
return <p>Current theme: {theme?.value}</p>;
}Real-world example
A website reads a saved theme preference cookie on the server, allowing it to render the page with the correct dark or light theme immediately, without a flash of the wrong theme on load.
Likely follow-ups
- Can you write or set cookies from within a server component?
- What is the difference between reading cookies on the server versus the client?
Related topics