How to configure clientMaxAge/keepAlive with refresh tokens? (next-auth)

Viewed 1437

Using the credentials provider from next-auth for a simple email/pw login flow for our users, and I'm trying to work out the best combination of the session options to deal with refresh tokens.

Currently, on successful login, our API sends back the JWT and a config property USER_SESSION_LENGTH of 30 minutes.

I've got a combination of the provider options set to 30 minutes for clientMaxAge and keepAlive, and in the JWT callback, a check to see if the expiry time is less than an 'almostNow' Date.now() call, and if so, refetch a new JWT and reset the expiry.

Whilst this seems to work, I don't think I'm using the clientMaxAge/keepAlive correctly. How should I properly set/configure these values to work together?

// _app.tsx
const sessionOptions = {
    clientMaxAge: 60 * 30, // Re-fetch session if cache is older than 30 minutes 
    keepAlive: 60 * 30
};

<Provider options={sessionOptions} session={pageProps.session}>
    <Component {...pageProps} />
</Provider>

// [...nextauth].ts
const callbacks: CallbacksOptions = {
    async jwt(token: any, user: any) {
        if (user) {
            token.accessToken = user.token;
            token.expires = Date.now() + user.config.USER_SESSION_LENGTH * 1000;
        }

        if (token?.accessToken) {
            const tokenExpiry = token.expires;
            const almostNow = Date.now() + 60 * 1000; // random check of a minute past now so it won't run the first time, but on the refetch after 30 minutes.

            if (tokenExpiry !== undefined && tokenExpiry < almostNow) {
                try {
                    const newToken = await api.renewToken(token.accessToken); // hit our backend for new token
                    token.accessToken = newToken.token;
                    token.expires = Date.now() + user.config.USER_SESSION_LENGTH * 1000;
                } catch (error) {
                    console.error(error, 'Error refreshing access token');
                }
            }
        }

        return token;
    },
}
1 Answers

I would recommend reading this github issue which discusses this a bit. Basically, setting maxAge has the effect that I think you're after.

[...nextauth].js
...
session: {
  jwt: true,
  maxAge: 60 * 60,
}
...
Related