Q41: How do you read, set, and delete cookies in Server Components and Server Actions?
Next.js provides the cookies() API (next/headers). Inside Server Components, cookies() is read-only. Inside Server Actions and Route Handlers, cookies() supports setting (set()) and deleting (delete()) HTTP-only cookies.
Setting HTTP-Only Cookies in Server Action
'use server';
import { cookies } from 'next/headers';
export async function loginAction() {
const cookieStore = await cookies();
cookieStore.set('session', 'token123', {
httpOnly: true,
secure: true,
sameSite: 'lax',
path: '/',
});
}cookieStore.set writes secure HTTP-only cookies directly from server functions.
Key Takeaways
Server Components: Read-only access to cookies.
Server Actions & Route Handlers: Full read, write, and delete cookie mutations.
Knowledge Check
Can you call cookies().set('key', 'value') directly inside a standard Server Component render function?