#Next-auth: Access token not refreshing when site is left idle
1 messages · Page 1 of 1 (latest)
Hi @pastel meteor. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Based on the information provided in the extracts, it seems like you might be facing an issue similar to the one discussed in the Github issue titled "The huge problem is that I need to UPDATE the cookies so that I have a valid access token at the next request" (source: Github Issue 54266 (https://github.com/vercel/next.js/issues/54266)).
In this issue, the user was trying to update the cookies to have a valid access token for the next request. They used middleware to check the token's validity and refresh it if it had expired. Here's a snippet of their middleware code:
export const SessionMiddleware = defineMiddleware({
global: true,
async handler(req: NextRequest) {
const accessToken = req.cookies.get(StorageKey.AccessToken)?.value;
const refreshToken = req.cookies.get(StorageKey.RefreshToken)?.value;
if (!accessToken || !refreshToken) return;
const { exp } = decodeJwt<TokenPayload>(accessToken) ?? {};
const isValid = dayjs().isBefore(unix(exp!), 'minute');
if (isValid) return;
try {
console.log('INFO: Start refresh tokens');
const { refreshSession } = sessionApi();
const session = await refreshSession(refreshToken);
console.log('INFO: End refresh tokens', session);
This middleware checks if the access token is valid. If it's not, it refreshes the token.
However, it's important to note that this solution might not work in all cases. For example, if the token expiry is very small, you might need to use a custom axios instance to refresh it on the server and on the client calls too.