New2WebDev
New2WebDev

Reputation: 13

Apollo Client: Auth Middleware; Failed to execute 'fetch' on 'Window'

I am trying to create a middleware for Apollo Client that will allow the JWT to be refreshed from Amazon Cognito Identity. However, when I 'fetch' on 'Window' error. I think this is due to Amazon Cognito Identity having a callback, which makes the function run async. This means that when I try to update the JWT, it processes before the function can get the JWT and errors.

   const createLink = ()=>{

   const httpLink = createHttpLink({
       uri: process.env.REACT_APP_GRAPH_QL_END_POINT
   });
 
   const authLink = setContext((_, { headers }) => {
       return {
           headers: {
               ...headers,
               authorization: updateToken
           }
        }
   })

   return authLink.concat(httpLink);
   }
    const updateToken = ()=> {
    const user = UserPool.getCurrentUser();
    let jwt = ""
    if (user === null || user === undefined) return "";
  
    if(AWS.config.credentials === undefined || AWS.config.credentials === null) return "";
  
        user.getSession((err:Error,session:CognitoUserSession|null) =>{
  
        if(session == null || err != null) return;
        let awsConfigCredentials = AWS.config.credentials as AWS.CognitoIdentityCredentials;
        if(awsConfigCredentials.needsRefresh())
        {
            const refreshJWT = session.getRefreshToken(); 
            user.refreshSession(refreshJWT,(err:Error,session:CognitoUserSession|null)=>{
            if(err || session == null) return;
                jwt = session.getAccessToken().getJwtToken();
  
        })
              }
              else
              {
  
                jwt= session.getAccessToken().getJwtToken();
           
              }
          });
  
      return `Bearer ${jwt}`;
  }

I tried returning a promise but that errors out as well.

Upvotes: 0

Views: 19

Answers (0)

Related Questions