Next.js Discord

Discord Forum

Help with refresh token in next 14 on the server

Unanswered
Giant wood wasp posted this in #help-forum
Open in Discord
Giant wood waspOP
Hello everyone, I have a problem with the refresh token in my app, it does not work. I want to refresh it in the server, because i have request on the client and the server components. This is my code, it iis a server action, this function that I execute in case that there is a error with code 401 . I hace this error (Cookies can only be modified in a server action or route handler.) in the line cookies().set(). Someone can help me please.

'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)
})
}

0 Replies