typescriptintermediate
Cookies and Headers in Server Components
Read and set cookies and headers in Next.js server components and route handlers.
typescriptPress ⌘/Ctrl + Shift + C to copy
// Reading cookies in Server Component
import { cookies, headers } from 'next/headers';
export default async function DashboardPage() {
const cookieStore = await cookies();
const theme = cookieStore.get('theme')?.value || 'dark';
const token = cookieStore.get('auth-token')?.value;
const headersList = await headers();
const userAgent = headersList.get('user-agent') || '';
const isMobile = /Mobile|Android/i.test(userAgent);
return (
<div data-theme={theme}>
<p>Device: {isMobile ? 'Mobile' : 'Desktop'}</p>
</div>
);
}
// Setting cookies in Route Handler
import { NextResponse } from 'next/server';
export async function POST(request: Request) {
const { theme } = await request.json();
const response = NextResponse.json({ success: true });
response.cookies.set('theme', theme, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 60 * 60 * 24 * 365, // 1 year
path: '/',
});
return response;
}
// Setting cookies in Server Action
async function setTheme(formData: FormData) {
'use server';
const theme = formData.get('theme') as string;
const cookieStore = await cookies();
cookieStore.set('theme', theme, {
httpOnly: true,
secure: true,
sameSite: 'lax',
maxAge: 60 * 60 * 24 * 365,
});
}Use Cases
- theme preferences
- authentication
- request inspection
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
Authentication Middleware Guard
Next.js middleware that checks auth tokens on protected routes and redirects unauthenticated users to login.
Best for: Dashboard access control
#middleware#authentication
typescriptintermediate
NextAuth Session Check Pattern
Check authentication status in Server Components and redirect unauthorized users with NextAuth.js.
Best for: Protected pages
#authentication#nextauth
typescriptintermediate
Parallel Data Fetching in Server Components
Fetch multiple data sources in parallel using Promise.all in Next.js server components for faster page loads.
Best for: dashboard pages
#nextjs#data-fetching
typescriptbeginner
Server-Only Utility Functions
Ensure utility functions only run on the server using the server-only package to prevent client leakage.
Best for: protecting secrets
#nextjs#server-only