How to do page refresh with token management with middleware in NextJS?
Unanswered
Transvaal lion posted this in #help-forum
Transvaal lionOP
I'm developing a Next.js 14 application and have implemented logic for handling refresh and access tokens using middleware and NextAuth for authentication. However, I'm encountering a specific issue related to token expiration and refresh:
When the access_token expires, it shows an error message, but I can see that the cookie is correctly set. The correct content only loads after I manually refresh the page. Additionally, when I tried to implement a redirect within my middleware using
I expected that once the access_token cookie is set (especially after a refresh token cycle), the
Relevant Part of Middleware:
The
How can I resolve this issue so that the new access_token takes effect immediately without needing a page refresh, and without causing a redirect loop? Thanks!
When the access_token expires, it shows an error message, but I can see that the cookie is correctly set. The correct content only loads after I manually refresh the page. Additionally, when I tried to implement a redirect within my middleware using
NextResponse.redirect(new URL(req.url)), it resulted in a loop that led to a "too many requests" error.I expected that once the access_token cookie is set (especially after a refresh token cycle), the
if (!accessToken && refreshToken) block in my middleware would not execute again, thus preventing this issue.Relevant Part of Middleware:
// ... [Initial setup of the middleware]
// Handling refresh token
if (!accessToken && refreshToken) {
try {
const serverResponse = await fetch(`${Backend_URL}/user/refresh-token`, {
method: "POST",
headers: {
Cookie: `refresh_token=${refreshToken}`
},
credentials: "include",
});
if (serverResponse.ok) {
const setCookieHeader = serverResponse.headers.get("set-cookie");
setCookiesFromHeader(response, setCookieHeader);
console.log("set cookie header", setCookieHeader);
return response; // Issues arise here
} else {
req.cookies.clear();
return NextResponse.redirect(`${Frontend_URL}/login`);
}
} catch (error) {
console.error("Middleware error:", error);
return NextResponse.redirect(`${Frontend_URL}/login`);
}
}
return response;
// ... [Rest of the middleware]The
makeFetch function performs HTTP requests with default credentials and retries on a 401 Unauthorized response.How can I resolve this issue so that the new access_token takes effect immediately without needing a page refresh, and without causing a redirect loop? Thanks!