amplify-js: Next, js, Amplify js.fetchAuthSession({forceRefresh: true}) does not work as expected and returns tokens as undefined. How to manage a refresh token in Amplify v6 in Next.js

Before opening, please confirm:

JavaScript Framework

Next.js

Amplify APIs

Authentication

Amplify Version

v6

Amplify Categories

auth

Backend

None

Environment information

# Put output below this line


Describe the bug

Hello and thanks for the great library. I have the following problem. I need a token to set in the headers of each request as Authorization: Bearer ${token}. I am currently taking the accessToken from the fetchAuthSession and setting it in the headers. For this purpose I use axios interceptor. The problem is that if some time passes, about 15 minutes, and the application is not used, the token expires. Accordingly, you will see that if I do not have a token, the authorization header is not submitted, which is a problem for me. The app only fixes after a refresh, but I want to get the refresh token without forcing the user to refresh because they might lose data.

Expected behavior

Is there a way Amplify to handle the refresh token itself, or to force refresh it when It expires ? I always need a valid token for my Authorization headers.

Reproduction steps

…

Code Snippet

// Put your code below this line.
// _app.tsx
import { type AppType } from "next/dist/shared/lib/utils";
import {
  QueryClient,
  QueryClientProvider,
} from 'react-query'
import NextTopLoader from 'nextjs-toploader';
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { Amplify } from "aws-amplify";
import '@aws-amplify/ui-react/styles.css';
import AuthWrapper from "~/components/auth/AuthWrapper";
import "~/styles/globals.css";
import { DataProvider } from '~/context/globalState';
import { PdfFocusProvider } from "~/context/pdf";
import { CadDataProvider } from "~/context/cadData";

Amplify.configure({
  Auth: {
    Cognito: {
      userPoolClientId: process.env.NEXT_PUBLIC_USER_POOL_CLIENT_ID ?? "",
      userPoolId: process.env.NEXT_PUBLIC_USER_POOL_ID ?? "",
      loginWith: {
        oauth: {
          domain: process.env.OAUTH_DOMAIN ?? "",
          scopes: ['email'],
          redirectSignIn: [process.env.NEXT_PUBLIC_REDIRECT_SIGN_IN ?? ""],
          redirectSignOut: [process.env.NEXT_PUBLIC_REDIRECT_SIGN_OUT ?? ""],
          // I tried to change responseType to "code", but it is not working for me
          responseType: 'token',
        },
        username: false,
        email: true,
        phone: false,
      }
    }
  }
});

const MyApp: AppType = ({ Component, pageProps }) => {
  const queryClient = new QueryClient();

  return (
    <AuthWrapper>
      <QueryClientProvider client={queryClient}>
        <DataProvider>
          <PdfFocusProvider>
            <CadDataProvider>
              <ToastContainer autoClose={1000} />
              <NextTopLoader color="#120264" showSpinner height={3} />
              <Component {...pageProps} />
            </CadDataProvider>
          </PdfFocusProvider>
        </DataProvider>
      </QueryClientProvider>
    </AuthWrapper>
  );
};

export default MyApp;


// apiClient.ts
import axios from "axios";
import { fetchAuthSession } from "aws-amplify/auth";
import { backendUrl } from "~/config";

const apiClient = axios.create({
  baseURL: backendUrl,
  responseType: "json",
});

apiClient.interceptors.request.use(
  async (config) => {
    try {
      // When we get to this block tokens is always different from undefined, even if I pass {forceRefresh: true}
      const session = await fetchAuthSession();
      const accessToken = session.tokens?.accessToken?.toString();
      if (accessToken) {
        // here token is always different from undefined.
        config.headers.Authorization = `Bearer ${accessToken}`;
        console.log("Access Token set in request:", accessToken);
      } else {
        console.warn("No access token available");
      }
    } catch (error) {
      console.error("Error fetching auth token", error);
    }
    return config;
  },
  (error) => Promise.reject(error)
);

apiClient.interceptors.response.use(
  (response) => response,
  async (error) => {
    const originalRequest = error.config;
    if (error?.response?.status === 401 && !originalRequest._retry) {
      console.log("401 Unauthorized error, trying to refresh token");
      // I am getting into this block when token expires
      try {
        const session = await fetchAuthSession({ forceRefresh: true });
         // but here the tokens object is always undefined
        const refreshToken = session.tokens?.accessToken?.toString();
        if (refreshToken) {
          console.log("Refresh token obtained:", refreshToken);
          originalRequest.headers.Authorization = `Bearer ${refreshToken}`;
          originalRequest._retry = true;
          return apiClient(originalRequest);
        } else {
          console.warn("No refresh token available");
        }
      } catch (authError) {
        console.error("Error refreshing auth token", authError);
        return Promise.reject(authError);
      }
    }
    return Promise.reject(error);
  }
);

export default apiClient;

Log output

// Put your logs below this line


aws-exports.js

/* eslint-disable */ // WARNING: DO NOT EDIT. This file is automatically generated by AWS Amplify. It will be overwritten.

const awsmobile = { “aws_project_region”: “us-east-2” };

export default awsmobile;

Manual configuration

Amplify.configure({ Auth: { Cognito: { userPoolClientId: process.env.NEXT_PUBLIC_USER_POOL_CLIENT_ID ?? “”, userPoolId: process.env.NEXT_PUBLIC_USER_POOL_ID ?? “”, loginWith: { oauth: { domain: process.env.OAUTH_DOMAIN ?? “”, scopes: [‘email’], redirectSignIn: [process.env.NEXT_PUBLIC_REDIRECT_SIGN_IN ?? “”], redirectSignOut: [process.env.NEXT_PUBLIC_REDIRECT_SIGN_OUT ?? “”], responseType: ‘token’, }, username: false, email: true, phone: false, } } } });

Additional configuration

No response

Mobile Device

No response

Mobile Operating System

No response

Mobile Browser

No response

Mobile Browser Version

No response

Additional information and screenshots

No response

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 1
  • Comments: 16 (8 by maintainers)

Most upvoted comments

yes I understand, the problem is the same. We are reproducing the problem - the application is open without interaction in the browser for about 15 minutes. That is, no requests are executed within 15 minutes. Then I get a network error where the request returns a 401 because I don’t have the authorization header set. I think I go in here refreshedToken is undefined and that’s why I don’t have any headers set:

     // Force refresh the token
        const refreshedSession = await fetchAuthSession({ forceRefresh: true });
        console.log("refreshedSession", refreshedSession);
        const refreshedToken = refreshedSession.tokens?.accessToken?.toString();

The interesting thing is that initial fetchAuthSession works and returns tokens, but in this case, which I am describing to you, it does not return them to me. Here are some screenshot of errors while I have responseType set to code. image

this is my apiClient.ts

import axios from "axios";
import { fetchAuthSession } from "aws-amplify/auth";
import { backendUrl } from "~/config";

const apiClient = axios.create({
  baseURL: backendUrl,
  responseType: "json",
});

// Utility to check if the token is expiring soon
function isTokenExpiringSoon(expiryUnix: number): boolean {
  // Get current time in Unix time and check if the token expires within the next 5 minutes
  const currentTime = Math.floor(Date.now() / 1000); // Convert milliseconds to seconds
  return expiryUnix - currentTime < 5 * 60; // 5 minutes buffer
}

apiClient.interceptors.request.use(
  async (config) => {
    try {
      const session = await fetchAuthSession();
      const accessToken = session.tokens?.accessToken?.toString();
      const expiryTime = session.tokens?.accessToken?.payload?.exp;

      if (accessToken && expiryTime && !isTokenExpiringSoon(expiryTime)) {
        config.headers.Authorization = `Bearer ${accessToken}`;
        console.log("Access Token set in request:", accessToken);
      } else {
        console.warn(
          "Access token is expiring soon or not available. Refreshing token..."
        );
        // Force refresh the token
        const refreshedSession = await fetchAuthSession({ forceRefresh: true });
        console.log("refreshedSession", refreshedSession);
        const refreshedToken = refreshedSession.tokens?.accessToken?.toString();
        if (refreshedToken) {
          config.headers.Authorization = `Bearer ${refreshedToken}`;
          console.log("Refreshed Access Token set in request:", refreshedToken);
        } else {
          console.warn("Failed to refresh token");
        }
      }
    } catch (error) {
      console.error("Error fetching or refreshing auth token", error);
    }
    return config;
  },
  (error) => Promise.reject(error)
);

export default apiClient;

And this is the Amplify config object:

Amplify.configure({
  Auth: {
    Cognito: {
      userPoolClientId: process.env.NEXT_PUBLIC_USER_POOL_CLIENT_ID ?? "",
      userPoolId: process.env.NEXT_PUBLIC_USER_POOL_ID ?? "",
      loginWith: {
        oauth: {
          domain: process.env.OAUTH_DOMAIN ?? "",
          scopes: ['email'],
          redirectSignIn: [process.env.NEXT_PUBLIC_REDIRECT_SIGN_IN ?? ""],
          redirectSignOut: [process.env.NEXT_PUBLIC_REDIRECT_SIGN_OUT ?? ""],
          // responseType: 'token',
          responseType: "code"
        },
        username: false,
        email: true,
        phone: false,
      }
    }
  }
});