Could we refresh token like this??
Unanswered
Tan posted this in #help-forum
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
@Tan js
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 ??
if /auth/refresh is a route handler u gotta change that
u should not fetch your own route handler in a ssr component
just test it out if it works 

@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 ?
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 ?
u dont need it to be on client
@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
yeah I created a serveraction (the above func)
And ran it in client component using setInterval.
What could be the another approach
@Tan How ?
yeah I created a serveraction (the above func)
And ran it in client component using setInterval.
What could be the another approach
whats the purpose of your refresh token?
@gin whats the purpose of your refresh token?
TanOP
to generate accesstoken. Since access tokens have very short expiration time