Next.js Discord

Discord Forum

Server Actions

Unanswered
Munchkin posted this in #help-forum
Open in Discord
MunchkinOP
Why can't getUserData become a server action? Bare inmind that this is a layout and already should be a server-side action.

import type { Metadata } from 'next'
import { headers } from 'next/headers'
import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'


async function getUserData(token: string | null) {
      "use server";
      cookies().delete('token');    
/// Do stuff
    return null
}

export default async function RootLayout({}: Readonly<{children: React.ReactNode}>) {
    const cookiesStore = cookies()
    const token = cookiesStore.get('at')

    if (token == null) return redirect('/login')
    const response = await getUserData(token.value)
    if (response?.payload == null) return redirect('/login')

    return (
        <div className='App'>
            <main className='page-container'>{children}</main>
        </div>
    )
}


I keep getting the error:

Error: Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#cookiessetname-value-options

4 Replies

According to the docs: https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#behavior
Server Actions are not limited to <form> and can be invoked from event handlers, useEffect, third-party libraries, and other form elements like <button>.


Which is why you are getting that error.

Also a note, layouts are only rendered once between navigation, see more: https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts#layouts
MunchkinOP
So it has to be executed by an event?
Yes, layout is fine to render only once.
@Munchkin So it has to be executed by an event?
Yes event handlers will work, along with the other methods I listed above