typescriptintermediate

Cookies and Headers in Server Components

Read and set cookies and headers in Next.js server components and route handlers.

typescript
// 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.