Next.js Discord

Discord Forum

Could we refresh token like this??

Unanswered
Tan posted this in #help-forum
Open in Discord
TanOP
async function refreshToken() {
  try {
    const cookieJar = cookies();
    const refresh = cookieJar.get("refresh");

    if (refresh?.value) {
      const newSession = await r.post({
        endpoint: "/auth/refresh",
        payload: { refreshToken: refresh.value },
      });
      const { accessToken } = newSession;
      cookieJar.set("token", accessToken);
      console.log("Cookie refreshed successfully !!");
    }
  } catch (err) {
    console.log("ERROR WHILE REFRESHING TOKEN", err);
  }
}


And run the function in layout to refresh token ??

9 Replies

@gin u should not fetch your own route handler in a ssr component
TanOP
Yeah.
It is on diff server. So i used this code wrapping it in useEffect with setTimeout. And it was working and updating periodically.
I put that component in layout. Would that be a good idea ?
@gin u can refresh your token on the serverside
TanOP
How ?
yeah I created a serveraction (the above func)
And ran it in client component using setInterval.

What could be the another approach
@gin whats the purpose of your refresh token?
TanOP
to generate accesstoken. Since access tokens have very short expiration time