diff --git a/packages/core/__tests__/Credentials-test.ts b/packages/core/__tests__/Credentials-test.ts index 32f431be51a..1718fc0434a 100644 --- a/packages/core/__tests__/Credentials-test.ts +++ b/packages/core/__tests__/Credentials-test.ts @@ -26,6 +26,30 @@ const cacheClass = { }; describe('Credentials test', () => { + describe('.Auth', () => { + it('should be undefined by default', async () => { + const credentials = new Credentials(null); + + expect(credentials.Auth).toBeUndefined(); + + expect(credentials.get()).rejects.toMatchInlineSnapshot( + `"No Auth module registered in Amplify"` + ); + }); + + it('should be Amplify.Auth if configured through Amplify', () => { + const credentials = new Credentials(null); + + Amplify.register(authClass); + Amplify.register(credentials); + + Amplify.configure({}); + + expect(credentials.Auth).toBe(authClass); + expect(credentials.get()).resolves.toBe('cred'); + }); + }); + describe('configure test', () => { test('happy case', () => { const config = { diff --git a/packages/core/src/Credentials.ts b/packages/core/src/Credentials.ts index dcc8f4b10f8..07fd03efea7 100644 --- a/packages/core/src/Credentials.ts +++ b/packages/core/src/Credentials.ts @@ -33,8 +33,8 @@ export class CredentialsClass { private _identityId; private _nextCredentialsRefresh: Number; - // `Amplify.Auth` will either be `Auth` or `null` depending on if Auth was imported - Auth = Amplify.Auth; + // Allow `Auth` to be injected for SSR, but Auth isn't a required dependency for Credentials + Auth = undefined; constructor(config) { this.configure(config); @@ -105,8 +105,11 @@ export class CredentialsClass { logger.debug('need to get a new credential or refresh the existing one'); // Some use-cases don't require Auth for signing in, but use Credentials for guest users (e.g. Analytics) - if (this.Auth && typeof this.Auth.currentUserCredentials === 'function') { - return this.Auth.currentUserCredentials(); + // Prefer locally scoped `Auth`, but fallback to registered `Amplify.Auth` global otherwise. + const { Auth = Amplify.Auth } = this; + + if (Auth && typeof Auth.currentUserCredentials === 'function') { + return Auth.currentUserCredentials(); } else { return Promise.reject('No Auth module registered in Amplify'); }