'refresh access token with apollo client in Next.js

I'm working with next.js and apollo client to get an access token with a refresh token from the server and I searched the web and find apollo-link-token-refresh that does something like silent refresh, so I follow along with example and was happy that after 2 days I finish my project Authentication but no it didn't work. is there any problem in my code?

const refreshLink = new TokenRefreshLink({
  accessTokenField: "token",
  isTokenValidOrUndefined: () => {
    if (!cookie.get("JWT")) {
      return true;
    }

    if (token && jwt.decode(token)?.exp * 1000 > Date.now()) {
      return true;
    }
  },
  fetchAccessToken: async () => {
    if (!cookie.get("JWT")) {
      return true;
    }

    const response = await fetch(`${NEXT_PUBLIC_SERVER_API_URL}`, {
      method: "POST",
      headers: {
        authorization: token ? "JWT " + token : "",
        "content-type": "application/json",
      },
      body: JSON.stringify({
        query: `
        mutation {
          refreshToken(refreshToken: "${cookie.get("JWTRefreshToken")}") {
            token
            payload
            refreshToken
            refreshExpiresIn
          }
        }
        `,
      }),
    });
    return response.json();
  },
  handleFetch: (newToken) => {
    cookie.remove("JWT", { path: "" });
    cookie.set("JWT", newToken, {
      expires: data.tokenAuth.payload.exp,
      secure: process.env.NODE_ENV !== "production",
      path: "",
    });
  },
  handleResponse: (operation, accessTokenField) => (response) => {
    if (!response) return { newToken: null };
    return { newToken: response.data?.refreshUserToken?.token };
  },
  handleError: (error) => {
    console.error("Cannot refresh access token:", error);
  },
});
function createApolloClient() {
  return new ApolloClient({
    ssrMode: typeof window === "undefined",
    link: authLink.concat(refreshLink).concat(
      new HttpLink({
        uri: process.env.NEXT_PUBLIC_SERVER_API_URL,
        credentials: "same-origin",
      }),
    ),
cache
})
)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source