Utilizing the next-auth Credentials
provider, I have set up authentication in my Next.js application with a custom Django backend.
Below is my jwt callback function:
async jwt(token, user, account) {
if (user && account) {
// The user has just logged in.
const decoded = jwt_decode(user.access)
token.accessToken = user.access
token.refreshToken = user.refresh
token.accessTokenExpires = decoded.exp
return token
}
if ((Date.now() + 15 * 1000) <= (token.accessTokenExpires * 1000)) {
// The user was previously logged in and the access token has not yet expired.
return token
}
// The access token has expired and needs to be refreshed using the refresh token.
const newJwt = await refreshJwt(token.refreshToken)
if (newJwt) {
token.accessToken = newJwt
const decoded = jwt_decode(newJwt)
token.accessTokenExpires = decoded.exp
return token
}
// Both the access token and refresh token are expired.
return {}
}
This issue arises when the jwt(token.accessToken
) expires, as the jwt callback
does not trigger for refreshing it. However, manually refreshing the page or changing browser tabs prompts the callback to execute properly and update the jwt(token.accessToken
) using the token.refreshToken
.
I aim to have the jwt callback
execute each time the useSession
hook is utilized throughout all pages of my website, including server-side rendered and statically-generated pages.