I see the issue with your code. The error âCookies can only be modified in a server actions or route handlerâ is occurring because youâre trying to modify cookies directly in a Server Component layout file.
While both files have the âuse serverâ directive, thereâs an important distinction:
Your killSession.ts is correctly set up as a server action
Your layout component is a Server Component, not a server action
In Next.js, cookies can only be modified in:
Server Actions (functions marked with âuse serverâ)
Route Handlers (API routes)
You probably try something like:
import React from 'react'
import LogoutHandler from './logout-handler'
export default function PageLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<>
<LogoutHandler />
{children}
</>
)
}
Then create a client component that calls your server action:
'use client'
import { useEffect } from 'react'
import { killSession } from '@actions/killSession'
export default function LogoutHandler() {
useEffect(() => {
killSession()
}, [])
return null
}
This approach uses a client component with useEffect to call your server action when the component mounts . The client component is rendered inside your layout, but doesnât affect the UI since it returns null.
Hi @mildfuzz, you can use await in the Server components but you canât write cookies in a server component, you can only read one. As explained in the docs:
cookies is an async function that allows you to read the HTTP incoming request cookies in Server Components, and read/write outgoing request cookies in Server Actions or Route Handlers.
So, as @swarnava pointed out, you should be performing the cookie writes in Server Actions.