can't set cookie in server action
Answered
Pteromalid wasp posted this in #help-forum
Pteromalid waspOP
what am i doing wrong, i'm literally just following the nextjs docs from here: https://nextjs.org/docs/app/api-reference/functions/cookies#setting-a-cookie
src/app/page.jsx:
/src/actions/testAction.js:
i get this error:
src/app/page.jsx:
const result = await testCookieSet()
console.error("[Home] - result", result);
/src/actions/testAction.js:
'use server'
import { cookies } from 'next/headers'
export async function testCookieSet() {
const cookieStore = cookies()
cookieStore.set('name', 'lee')
// Your other cookie setting logic here
return { success: true }
}
i get this error:
Unhandled Runtime Error
[ Server ] Error: Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#options
Source
src/actions/testAction.js (7:17) @ testCookieSet
5 | export async function testCookieSet() {
6 | const cookieStore = cookies()
> 7 | cookieStore.set('name', 'lee')
| ^
8 | // Your other cookie setting logic here
9 | return { success: true }
10 | }
Answered by joulev
server actions when called inside server components behave like normal functions. and inside server components, cookies().set() doesn't work.
you have to call the server action from the client for the cookies().set() to work
you have to call the server action from the client for the cookies().set() to work
3 Replies
@Pteromalid wasp what am i doing wrong, i'm literally just following the nextjs docs from here: https://nextjs.org/docs/app/api-reference/functions/cookies#setting-a-cookie
src/app/page.jsx:
const result = await testCookieSet()
console.error("[Home] - result", result);
/src/actions/testAction.js:
'use server'
import { cookies } from 'next/headers'
export async function testCookieSet() {
const cookieStore = cookies()
cookieStore.set('name', 'lee')
// Your other cookie setting logic here
return { success: true }
}
i get this error:
Unhandled Runtime Error
[ Server ] Error: Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#options
Source
src/actions/testAction.js (7:17) @ testCookieSet
5 | export async function testCookieSet() {
6 | const cookieStore = cookies()
> 7 | cookieStore.set('name', 'lee')
| ^
8 | // Your other cookie setting logic here
9 | return { success: true }
10 | }
server actions when called inside server components behave like normal functions. and inside server components, cookies().set() doesn't work.
you have to call the server action from the client for the cookies().set() to work
you have to call the server action from the client for the cookies().set() to work
Answer
Pteromalid waspOP
i see, will try from a client component
works, thank you!