Do Server Actions need necessarily to be called via <form action="">?
Unanswered
Serengeti posted this in #help-forum
SerengetiOP
Why I can't just do this?:
I get this error:
But that is my server action.
How can I forward session cookie then? I'm using nextjs and nestjs as a backend
const getHeaders = () => ({
Cookie: cookies().toString(),
});
export default async function Page({ params }: { params: { slug: string } }) {
async function getProduct(slug: string) {
'use server'
const res = await fetch(`${API_URL}/products/${slug}`, {
headers: { ...getHeaders() },
});
const sessionCookieValue = res.headers.get('set-cookie')?.split('connect.sid=')[1].split(';')[0]
if (sessionCookieValue)
cookies().set({ name: 'connect.sid', value: sessionCookieValue })
const parsedRes = await res.json();
if (!res.ok) {
return { error: getErrorMessage(parsedRes) };
}
return parsedRes;
}
const product = await getProduct(params.slug)
// ...
}I get this error:
Error: Cookies can only be modified in a Server Action or Route Handler...But that is my server action.
How can I forward session cookie then? I'm using nextjs and nestjs as a backend
1 Reply
@Serengeti Why I can't just do this?:
ts
const getHeaders = () => ({
Cookie: cookies().toString(),
});
export default async function Page({ params }: { params: { slug: string } }) {
async function getProduct(slug: string) {
'use server'
const res = await fetch(`${API_URL}/products/${slug}`, {
headers: { ...getHeaders() },
});
const sessionCookieValue = res.headers.get('set-cookie')?.split('connect.sid=')[1].split(';')[0]
if (sessionCookieValue)
cookies().set({ name: 'connect.sid', value: sessionCookieValue })
const parsedRes = await res.json();
if (!res.ok) {
return { error: getErrorMessage(parsedRes) };
}
return parsedRes;
}
const product = await getProduct(params.slug)
// ...
}
I get this error:
Error: Cookies can only be modified in a Server Action or Route Handler...
But that is my server action.
How can I forward session cookie then? I'm using nextjs and nestjs as a backend
server actions can only be executed from the client. for example, a form action, or something like
in your example you are just running a function inside a server component. it just behaves as an ordinary server component. in server component you cannot set cookies, that's a fundamental limitation of the app router.
async function onClick() {
const result = await doStuffAction();
// ...
}in your example you are just running a function inside a server component. it just behaves as an ordinary server component. in server component you cannot set cookies, that's a fundamental limitation of the app router.