Search code examples
angularamazon-web-servicesamazon-cognitoaws-amplify

AWS Amplify Cognito | Missing region in config after I refresh page


I am building a web app in Angular using AWS as my backend, and got Cognito running, that I've set up via Amplify.

After I login to my web app in my browser on my localhost, everything runs perfect.

The problem is, as I work on my app, every time I make a change and the browser refreshes, I get the error:

ConfigError: Missing region in config

Since I used Amplify to set it up, I don't know where to set my region and why this keeps happening.

I use authguard to protect my pages, so only auth users are allowed to see all content but the login site.

async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
try {
  let user = await Auth.currentAuthenticatedUser();
  console.log('Yes, Im authenticated', user);
  return true;
} catch (e) {
  console.log('Not authenticated ', e);
  this._router.navigate(['/login']);
  return false;
  }
 }
} 

I'm a bit over my head here and have lost overview of what is what after working on this problem for so long, so if I need to provide some more code or explanation, I will be happy to do so.

Full console error:

ConfigError: Missing region in config
at Request.VALIDATE_REGION (http://localhost:4200/vendor.js:210527:45)
at Request.callListeners (http://localhost:4200/vendor.js:215956:20)
at callNextListener (http://localhost:4200/vendor.js:215946:12)
at http://localhost:4200/vendor.js:210521:9
at finish (http://localhost:4200/vendor.js:206617:7)
at Config.getCredentials (http://localhost:4200/vendor.js:206662:7)
at Request.VALIDATE_CREDENTIALS (http://localhost:4200/vendor.js:210516:26)
at Request.callListeners (http://localhost:4200/vendor.js:215952:18)
at Request.emit (http://localhost:4200/vendor.js:215928:10)
at Request.emit (http://localhost:4200/vendor.js:214552:14)

Solution

  • SOLUTION:

    I used the APP_INITIALIZER to get my regions in before the component was loaded, to fix this issue.

    In my app module on providers I added to following:

    {
      provide: APP_INITIALIZER,
      useFactory: startupServiceFactory,
      multi: true
    }
    

    I then added a ts file in /app with the following:

    import {Auth} from 'aws-amplify';
    import * as AWS from 'aws-sdk';
    
    
    export function startupServiceFactory() {
      return () => {
        return new Promise(async (resolve) => {
          const credentials = await Auth.currentCredentials();
          AWS.config.region = 'eu-central-1';
          AWS.config.credentials = Auth.essentialCredentials(credentials);
          resolve();
        });
      };
    }
    

    Link to tutorial:

    https://dzone.com/articles/how-to-use-the-app-initializer-token-to-hook-into