Next.js Discord

Discord Forum

Is there any way to manually set response headers in a server action?

Answered
West African Lion posted this in #help-forum
Open in Discord
Avatar
West African LionOP
Or do I need to use a route handler to be able to do this? I have a form I submit from a client component that is handled by a server action. The server action response sets a cookie on the client through cookies().set(...).

The issue is that Next.js v14 edge runtime (and v15 as well from what I've seen in the source code, not tested) currently [always encodes](https://github.com/vercel/next.js/issues/64346) the cookie value. Which the BE which parses this cookie later on cannot handle.

Using a route handler would allow me to manually put a Set-Cookie header on the response. But then I assume I lose out on hooks like useFormStatus() and useFormState(). So I'm curious to know if there is a trick to set headers on the response of a server action. I would like to avoid providing the cookie in the server action payload itself and having the client set the cookie. Since you lose out on the default security measures the browser uses to handle Set-Cookie headers.
Answered by Alfonsus Ardani
No, there isn't a way to manually set response headers in a server action since those are all abstracted by React and is part of the React's action specification
View full answer

9 Replies

Avatar
No, there isn't a way to manually set response headers in a server action since those are all abstracted by React and is part of the React's action specification
Answer
Avatar
Im not sure I understand why this is needed?
"Which the BE which parses this cookie later on cannot handle."
Why can't they handle encoded cookie? Just decode it
Avatar
West African LionOP
The BE is a 3rd-party solution so it cannot be modified itself to decode the cookie. But I can put something in between to do it. Feels a bit unnecessary but that is how it is for now. Thanks for the insight.
Avatar
ayayay
encoding cookies is standard practice :Crying:
Avatar
West African LionOP
Tell that to the 3rd-party solution, maybe I will šŸ˜„
Avatar
well you usually can raise an issue to them or contact support or ask around in community forums? idk just giving an idea
Avatar
West African LionOP
That's the idea indeed. Thanks šŸ™‚