Next.js Discord

Discord Forum

Update Cookie inside server Component.

Answered
Banjara Hound posted this in #help-forum
Open in Discord
Banjara HoundOP
i have a server action method that get data from server and return response.
inside server action i check that token valid or not. if is not, update token. but when token is not valid i can't set cookie because i get exception that cookie can only be modified inside API Route or Server Actions.
i know how to fix this with using useTransition. but i want a way to use it inside serve component. not inside client component. and i know i can use startTransition directly but can't use async/await method inside that. and can't return data inside startTransition .
Answered by Ray
for this case
View full answer

22 Replies

Banjara HoundOP
so what should i do? i want user get data when page rendered.
since that data depend on valid token.
you can read the cookie on the page but not set
Banjara HoundOP
so how to update cookie when it's not valid?
you will have to set the cookie with server action if it is not valid
or do it in middleware
Banjara HoundOP
if i do it in middleware, is not gonna slow down? because i do it now and it's a little slow.
I think the speed should have a little different only if you are doing in on middleware or page?
Banjara HoundOP
my api handle auth and i just want a way to store cookie in browser and update it when it's not valid. i do that with httpOnly cookie. is there any better way or any custom lib that can do that without any problem?
Pollock
Hi

Inside your server action file make sure you put 'use server' at the top. You need to explicitly type 'use server' at the top for it to be a server action otherwise it'll default to a server component - which won't allow you to set a cookie.

You can inline 'use server' but for simplicty sake it'll make it easier
I would do that on middleware
Banjara HoundOP
ok thanks. i will do it with middleware until i find better way to do that.
or may be someone has better way.
currently only middleware
for this case
Answer
hope this will change
Banjara HoundOP
yes i hope that nextjs provide better way for this kind of situation.
thanks for helping
yeah I think it will since its still new