No articles found
Try different keywords or browse our categories
Fix: cookies() can only be used in Server Components error Next.js
Quick fix for 'cookies() can only be used in Server Components' error in Next.js. Learn how to properly use cookies in Server Components.
The ‘cookies() can only be used in Server Components’ error occurs when developers try to use Next.js’s cookies() function in Client Components. This error is common when working with cookies in the App Router and understanding the distinction between Server and Client Components.
How the Error Happens
❌ Error Scenario - Client Component with cookies():
// ❌ This will cause an error
// components/ClientComponent.js
'use client';
import { cookies } from 'next/headers';
export default function ClientComponent() {
// ❌ cookies() cannot be used in Client Components
const cookieStore = cookies();
const theme = cookieStore.get('theme');
return (
<div>
<p>Theme: {theme?.value}</p>
</div>
);
}
❌ Error with Other Header Functions:
// ❌ This will also cause an error
// app/page.js
'use client';
import { cookies, headers } from 'next/headers';
export default function HomePage() {
// ❌ Cannot use cookies() in Client Components
const cookieStore = cookies();
const allCookies = cookieStore.getAll();
// ❌ Cannot use headers() in Client Components
const headerStore = headers();
return (
<div>
<p>Cookies: {allCookies.length}</p>
</div>
);
}
✅ Quick Fix - Use Server Components
Solution 1: Move to Server Component
// ✅ Use cookies in Server Component
// app/page.js
import { cookies } from 'next/headers';
export default function HomePage() {
// ✅ cookies() works in Server Components
const cookieStore = cookies();
const theme = cookieStore.get('theme');
return (
<div>
<h1>Home Page</h1>
<p>Theme: {theme?.value || 'default'}</p>
</div>
);
}
Solution 2: Create Server Action for Cookie Operations
// ✅ Server Action for setting cookies
// lib/actions.js
'use server';
import { cookies } from 'next/headers';
export async function setThemeCookie(theme) {
// ✅ cookies() works in Server Actions
cookies().set('theme', theme, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
maxAge: 60 * 60 * 24 * 7, // 1 week
path: '/',
});
}
export async function getThemeCookie() {
// ✅ cookies() works in Server Actions
const cookieStore = cookies();
return cookieStore.get('theme');
}
// ✅ Use Server Action in Client Component
// components/ThemeSelector.js
'use client';
import { setThemeCookie } from '../lib/actions';
export default function ThemeSelector() {
const handleThemeChange = async (theme) => {
// ✅ Call Server Action to set cookie
await setThemeCookie(theme);
window.location.reload(); // Refresh to apply theme
};
return (
<div>
<button onClick={() => handleThemeChange('light')}>
Light Theme
</button>
<button onClick={() => handleThemeChange('dark')}>
Dark Theme
</button>
</div>
);
}
Solution 3: Pass Cookie Data from Server to Client
// ✅ Server Component that gets cookie data
// app/page.js
import { cookies } from 'next/headers';
import ClientComponent from './ClientComponent';
export default function HomePage() {
// ✅ Get cookie in Server Component
const cookieStore = cookies();
const theme = cookieStore.get('theme')?.value || 'light';
return (
<div>
<h1>Home Page</h1>
{/* ✅ Pass cookie data to Client Component */}
<ClientComponent initialTheme={theme} />
</div>
);
}
// ✅ Client Component receives cookie data as prop
// app/ClientComponent.js
'use client';
import { useState, useEffect } from 'react';
export default function ClientComponent({ initialTheme }) {
const [theme, setTheme] = useState(initialTheme);
useEffect(() => {
// ✅ Apply theme on client side
document.documentElement.classList.toggle('dark', theme === 'dark');
}, [theme]);
return (
<div>
<p>Current theme: {theme}</p>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle Theme
</button>
</div>
);
}
Solution 4: Using Cookie Store in Layout
// ✅ Layout with cookie access
// app/layout.js
import { cookies } from 'next/headers';
export default function RootLayout({ children }) {
// ✅ Access cookies in layout
const cookieStore = cookies();
const theme = cookieStore.get('theme')?.value || 'light';
return (
<html lang="en" className={theme === 'dark' ? 'dark' : ''}>
<body>{children}</body>
</html>
);
} Related Articles
Fix: useEffect is not allowed in Server Components - Quick Fix in Next.js
Quick fix for 'useEffect is not allowed in Server Components' error in Next.js. Learn how to properly use useEffect in Client Components.
Fix: useState is not allowed in Server Components error Next.js
Quick fix for 'useState is not allowed in Server Components' error in Next.js. Learn how to properly use useState in Client Components.
Fix: useRouter only works in Client Components Error
Learn how to fix the 'useRouter only works in Client Components' error in Next.js applications. This comprehensive guide covers client components, server components, and proper routing implementation.