saolu
saolu

Reputation: 45

Next Auth: How to manually trigger the jwt callback to update an access token

When signing in in my NextJS 13 app with Next Auth using the credentials provider and JWT as the strategy, I am getting an access token from my custom nodejs backend which I update server-side inside [...nextauth].ts if it is invalid, just as described in the Next Auth refresh token rotation guide (https://authjs.dev/guides/basics/refresh-token-rotation#server-side):

    // [...nextauth].ts
    async jwt({ token, user, trigger, session }) {
      if (trigger === "update") {
        return { ...token, ...session.user };
      }
      // Sign in: getting fresh access token from backend
      if (user) {
        console.log("first time login, getting access token");
        return { ...token, ...user };
      }
      // Return previous token if the access token has not expired yet
      if (new Date().getTime() < token.accessTokenExpireIn) {
        return token;
      }
      // Access token has expired, try to update it
      if (token.refreshTokenExpireIn > new Date().getTime()) {
        return await refreshToken(token);
      }
    },
    async session({ session, token, user }) {
      return {
        ...session,
        user: {
          accessToken: token.accessToken,

That access token is being returned inside the session callback and therefore available client-side to be included in API calls to my custom backend. When calling useSession() or other next auth functions client-side, the jwt callback is being triggered (https://next-auth.js.org/configuration/callbacks#jwt-callback) which updates the access token if it is expired using the refresh token.

When testing it by setting my access token lifetime to 10 seconds, the access token is being successfully renewed after 10s when entering a page that uses useSession() or getSession() for the first time.

However, the access token is only being updated when I visit such a page for the first time or manually reload the page. When doing an API call to my backend inside that page using the access token and the access token is not valid, it will not be refreshed since the jwt callback is not being triggered.

How can I manually trigger the jwt callback to update my access token before doing API calls, etc.?

Upvotes: 0

Views: 3093

Answers (1)

saolu
saolu

Reputation: 45

Solved by providing a refetchInterval for the <SessionProvider/> inside _app.ts:

// 24 * 60 * 60 since my access token expires in 1 day
<SessionProvider session={pageProps.session} refetchInterval={24 * 60 * 60}>
  <Layout>
    <Component {...pageProps} />
  </Layout>
</SessionProvider>

Upvotes: 1

Related Questions