Next.js Discord

Discord Forum

Do Server Actions need necessarily to be called via <form action="">?

Unanswered
Serengeti posted this in #help-forum
Open in Discord
SerengetiOP
Why I can't just do this?:
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