Next.js Discord

Discord Forum

Struggling to understand the definition of a server action for cookie deletion

Answered
Black-bellied Plover posted this in #help-forum
Open in Discord
Black-bellied PloverOP
(Code snippets here: https://stackoverflow.com/questions/78230375/nextjs-deleting-cookie-in-server-function-throws-an-error)
I use nextjs as a stateless server, so all data is pulled from an external API, and that API manages auth too.
Upon login, nextjs uses the supplied credentials to the API, and stores the token that gets returned into an iron-session. I am trying to implement automatic deletion of the session cookie, if the API returns a 401 to any request (meaning that the stored credential has expired).

Data is loaded by functions decorated with 'use server', and these call out to a function which inspects the API response and deletes the cookie if the response is a 401. What I'm struggling to understand, is if these data loading functions are called in client components, it works fine, but if they are called by a server component, it throws an error about modifying cookies only being possible in server actions. The crux of my question is, why can I not delete a cookie in a server component, and does that mean that the only way to achieve this is to make any page that loads data a client component?
Answered by Ray
server action need to be invoked on client side (eg, form, event handler). if you call fetchWrapper in a server component which isn't a server action
View full answer

5 Replies

Answer
because we cannot set cookie in the page component
Black-bellied PloverOP
Ah, interesting. Presumably though, after the SSR, we still send a response to the browser. Why can't that response include a set-cookie header?
Black-bellied PloverOP
Makes sense, I really appreciate the response. Thank you!