Next.js Discord

Discord Forum

Setting cookies in a server action

Answered
shadow_aya posted this in #help-forum
Open in Discord
I am setting a cookie in JSON form (parse & set) in a Server Action, but still getting an 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

I looked at the example given:
'use server'
 
import { cookies } from 'next/headers'
 
async function create(data) {
  cookies().set('name', 'lee')
  // or
  cookies().set('name', 'lee', { secure: true })
  // or
  cookies().set({
    name: 'name',
    value: 'lee',
    httpOnly: true,
    path: '/',
  })
}

and... isn't that the same thing? kind of at a loss here :FallenQiqi:

I am just calling the Server Action in my asynchronous server component, maybe I got Server Actions wrong
Answered by Jboncz
It has to be called in a client component, think of it as a round trip to set a cookie. Client has to call a server component -> makes a POST call to obfuscated api route then gets a return from the post route with the cookie to set it.
View full answer

15 Replies

for more context, here's the server component that calls it:
export default async function LoginAction({ code }: LoginActionProps) {

    // ...

    const res = // obtain Cookie as string

    if (!res.success) {
        return (
            <div>
                <h3>Error</h3>
                <p>{res.error}</p>
            </div>
        );
    } else {
        setCookieJSON(res.sessionCookie);
        return (
            <div>
                <h3>Success</h3>
                <p>Redirecting...</p>
            </div>
        );
    }

}
It has to be called in a client component, think of it as a round trip to set a cookie. Client has to call a server component -> makes a POST call to obfuscated api route then gets a return from the post route with the cookie to set it.
Answer
a server action can set a cookie but a server component cannot
that hurts, I'm getting into the client/server madness, but it makes sense now that you mention it, my guess is that semantically, the client must send a request for their PC's cookies to modify
At least thats my understanding 🙂
Yes, it does the modify on the receiving of the response.
Its instructions to the client side to do X
I guess I can plug some random client component at the end then
It is really hard to wrap my head around too! 😂
first time this confused me but your response instantly lit up my head, thanks :HuTaoThumbsUp:
Btw I like your site, lol very different.
:HuTaoPhoneLick:
thanks
😂 np. Have a good one.