Next.js Discord

Discord Forum

I can not set cookies in a server action in next 14

Unanswered
Giant wood wasp posted this in #help-forum
Open in Discord
Giant wood waspOP
Error: Cookies can only be modified in a Server Action
Someone have any idea about it why it doens work.

17 Replies

Holland Lop
could you provide the code? if i had to guess without your code, you probably didn’t put “use server” at the top of your file with the server action.
Giant wood waspOP
import {cookies} from "next/headers";

export default async function Page() {
const pepe = async () => {
'use server'
cookies().set('ss', 'yy')
}

await pepe()

return #Unknown ChannelRecover</>
}
this an example, but I tried of many ways and I always get the same error.
if that was one of your ways, its safe to assume the other ways were incorrect usage as well.
Giant wood waspOP
Its means that a request with get method, I can not do it in a server action
because I cant do it until finish de streaming
'use server'
import {cookies} from "next/headers";
// the other importations i dont put its becase are too longs

export async function handleRefreshTokenInServer(props: RequestProps): Promise<any> {
const getValueFromCookiesInServer = () => {
const loggedUser = cookies().get(Constants.cookie.loggedUser)?.value
if (loggedUser) {
return JSON.parse(loggedUser)
}
}
const loggedUserFromCookiesServer = getValueFromCookiesInServer()
const refreshTokenFromServer = loggedUserFromCookiesServer?.refreshToken
ManagerUserAuthController.refreshToken(refreshTokenFromServer)
.then(async (resp) => {
const token = resp?.data?.accessToken as string
const accessTokenExpiresIn = resp?.data?.accessTokenExpiresIn
cookies().set(Constants.cookie.accessToken, JSON.stringify({
accessToken: token,
}))
cookies().set(Constants.cookie.accessTokenExpiresIn, JSON.stringify({
accessTokenExpiresIn,
}))
return await sendRequest(props)
})
.catch(() => {
cookies().delete(Constants.cookie.accessToken)
cookies().delete(Constants.cookie.accessToken)
cookies().delete(Constants.cookie.accessTokenExpiresIn)
await ManagerUserAuthController.logout(refreshTokenFromServer)
redirect(urlRoutes.login.url)
})
}
with that code I want to refresh token in server, this code is in a file with axios logic
but I get the same erro with the cookies
Giant wood waspOP
But the problem is not axios or fetch, the problem is that I need to refresh on both the client and the server, and after change the cookies of both with the new access token
because all request will fail, because the token is had expired
thats not how cookies work.
Giant wood waspOP
How do you do it ?