amplify-js: fetchAuthSession is very slow on Angular SSR

Before opening, please confirm:

JavaScript Framework

Angular

Amplify APIs

Authentication

Amplify Version

v6

Amplify Categories

auth

Backend

Other

Environment information

 System:
    OS: macOS 15.3
    CPU: (12) arm64 Apple M3 Pro
    Memory: 1.89 GB / 36.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.18.0 - ~/.nvm/versions/node/v20.18.0/bin/node
    npm: 10.8.2 - ~/.nvm/versions/node/v20.18.0/bin/npm
    pnpm: 8.14.1 - /opt/homebrew/bin/pnpm
  Browsers:
    Chrome: 132.0.6834.160
    Safari: 18.3
  npmPackages:
    @angular-devkit/build-angular: ^19.1.5 => 19.1.5 
    @angular/animations: ^19.1.4 => 19.1.4 
    @angular/cdk: ^19.1.2 => 19.1.2 
    @angular/cli: ^19.1.5 => 19.1.5 
    @angular/common: ^19.1.4 => 19.1.4 
    @angular/compiler: ^19.1.4 => 19.1.4 
    @angular/compiler-cli: ^19.1.4 => 19.1.4 
    @angular/core: ^19.1.4 => 19.1.4 
    @angular/forms: ^19.1.4 => 19.1.4 
    @angular/localize: ^19.1.4 => 19.1.4 
    @angular/platform-browser: ^19.1.4 => 19.1.4 
    @angular/platform-browser-dynamic: ^19.1.4 => 19.1.4 
    @angular/platform-server: ^19.1.4 => 19.1.4 
    @angular/router: ^19.1.4 => 19.1.4 
    @angular/service-worker: ^19.1.4 => 19.1.4 
    @angular/ssr: ^19.1.5 => 19.1.5 
    @apollo/client: 3.11.10 => 3.11.10 
    @aws-crypto/sha256-browser: ^5.2.0 => 5.2.0 
    @aws-sdk/signature-v4: ^3.374.0 => 3.374.0 
    @contentful/rich-text-types: ^17.0.0 => 17.0.0 
    @rive-app/canvas-lite: ^2.25.2 => 2.25.2 
    @segment/analytics-next: ^1.76.0 => 1.76.0 
    @sentry/angular: ^8.41.0 => 8.41.0 
    @types/crypto-js: ^4.1.1 => 4.2.2 
    @types/express: ^4.17.21 => 4.17.21 
    @types/jasmine: ~3.8.0 => 3.8.2 
    @types/node: ^20.17.6 => 20.17.6 
    apollo-angular: ^8.0.0 => 8.0.0 
    aws-amplify: ^6.12.0 => 6.12.0 
    canvas-confetti: ^1.9.2 => 1.9.2 
    contentful: ^11.2.1 => 11.2.1 
    express: ^4.15.2 => 4.18.2 
    graphql: ^16.9.0 => 16.9.0 
    is-mobile: ^4.0.0 => 4.0.0 
    jasmine-core: ~3.8.0 => 3.8.0 
    karma: ~6.3.0 => 6.3.20 
    karma-chrome-launcher: ~3.1.0 => 3.1.1 
    karma-coverage: ~2.0.3 => 2.0.3 
    karma-jasmine: ~4.0.0 => 4.0.2 
    karma-jasmine-html-reporter: ~1.7.0 => 1.7.0 
    plyr: ^3.7.8 => 3.7.8 
    rxjs: ~7.5.6 => 7.5.7 
    tslib: ^2.3.0 => 2.6.2 
    typescript: ~5.6.3 => 5.6.3 
  npmGlobalPackages:
    corepack: 0.29.3
    npm: 10.8.2

Describe the bug

I have noticed fetchAuthSession is very slow initially no matter the package - client/server. It’s especially an issue on the SSR as it’s purpose is to optimize for speed.

It quite commonly takes around 300ms for the first (and only on the SSR) fetchAuthSession to get resolved. I noticed quite some calls are seemingly redundant and synchronous by monkey patching fetch:

Getting user info
runWithAmplifyServerContext: 0.101ms
[SSR Fetch] x-amz-target: AWSCognitoIdentityService.GetId
[SSR Fetch] x-amz-target: AWSCognitoIdentityService.GetId
[SSR Fetch] x-amz-target: AWSCognitoIdentityService.GetCredentialsForIdentity
[SSR Fetch] x-amz-target: AWSCognitoIdentityService.GetCredentialsForIdentity
[SSR Fetch] x-amz-target: AWSCognitoIdentityProviderService.GetUser
userInfo: 450ms

I have found #14079 and linked PR and issue which reports similar for NextJs. Unfortunately the fix seems to only address the issue for nextJs, as I’m on 6.12.0 and still face them.

Are there any plans to address the issue for lower level adapter which we need to use for Angular, too ? Or is my implementation likely wrong ?

Expected behavior

It should fetch fast

Reproduction steps

I only use Amplify Auth v6 gen 1 with backend deployed by terraform. Framework is Angular SSR V19; I tried to remove all the Angular specific code, to make code snippet as small as possible

Code Snippet

export const runWithAmplifyServerContext = <T>(
  cookies: Record<string, string>,
  operation: (contextSpec: AmplifyServer.ContextSpec) => Promise<T>,
): Promise<T> => {
  const cookieStorage = cookieKeyValueStorage(cookies);

  console.time('runWithAmplifyServerContext');
  return runAmplifyServerContext(
    amplifyConfig,
    {
      Auth: {
        tokenProvider: createUserPoolsTokenProvider(
          amplifyConfig.Auth,
          cookieStorage,
        ),
        credentialsProvider: createAWSCredentialsAndIdentityIdProvider(
          amplifyConfig.Auth,
          cookieStorage,
        ),
      },
    },
    (context) => { console.timeEnd('runWithAmplifyServerContext'); return operation(context)},
  );
};

  private async getUserInfo(): Promise<UserInfo | undefined> {
    const taskCleanup = this.taskService.add();

    console.log('Getting user info');
    console.time('userInfo');
    const userInfo = await (this.isPlatformBrowser
      ? this.getClientUserInfo()
      : this.getServerUserInfo());
    console.timeEnd('userInfo');
    taskCleanup();

    return userInfo;
  }

  private async getServerUserInfo(): Promise<UserInfo | undefined> {
    if (!this.cookies) {
      return undefined;
    }

    return await runWithAmplifyServerContext(this.cookies, (contextSpec) =>
      Promise.all([
        serverFetchAuthSession(contextSpec),
        serverFetchUserAttributes(contextSpec),
      ]),
    )
      .then(([session, userAttributes]) => ({
        id: userAttributes['custom:id'] ?? '',
        username: userAttributes.email ?? '',
        groups: new Set<string>(
          session.tokens?.accessToken.payload[
            'cognito:groups'
          ] as Array<string>,
        ),
      }))
      .catch(() => {
        return undefined;
      });
  }

Log output

// Put your logs below this line


aws-exports.js

export const amplifyConfig = {
  Auth: {
    Cognito: {
      allowGuestAccess: true,
      userPoolId: 'eu-central-X,
      identityPoolId: 'eu-central-X',
      userPoolClientId: 'XXXX',
    },
  },
};

Manual configuration

No response

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
  • Comments: 26 (13 by maintainers)

Most upvoted comments

Makes sense,

thank you so much for your assistance, it’s greatly appreciated!

Hi @martin-yumsto if you only use AWS credentials of a unauthenticated role across your server, and if you can identity which use cases are using the unauthenticated role, you can supply a shared key-value storage to create the credentials provider for runWithAmplifyServerContext. For example, with the following pseudo code:

import { sharedInMemoryStorage } from 'aws-amplify/utils';

// the wrapper function used only with your use cases that require unauthenticated credentials
export const runWithAmplifyServerContextWithUnauthCreds = <T>(
  operation: (contextSpec: AmplifyServer.ContextSpec) => Promise<T>,
): Promise<T> => {
  return runAmplifyServerContext(
    amplifyConfig,
    {
      Auth: {
        tokenProvider: createUserPoolsTokenProvider(
          amplifyConfig.Auth,
          sharedInMemoryStorage, // <- use shared in-memory storage
        ),
        credentialsProvider: createAWSCredentialsAndIdentityIdProvider(
          amplifyConfig.Auth,
          sharedInMemoryStorage, // <- use shared in-memory storage
        ),
      },
    },
    operation,
  );
};

With this example, the fetched unauthenticated credentials will be persisted in the in-memory storage, the unauthenticated credentials will be shared across your server, they will be fetched again only when they expire.

thank you for taking a look so swiftly @HuiSF !

Just to make sure I understand your point well - my multiple runWithAmplifyServerContext in this branch https://github.com/martin-yumsto/amplify-ssr-repro/tree/multiple-amplify-server-contexts version is perfectly fine and nothing to be changed about that.

I understand your point for the Promise.all and it’s easy fix, however, I need to call amplify to get Authentication header for every single request if I understand it well - thus the interceptor. Please let me know should I implement dummy request, I thought without is enough to illustrate real world. I cannot really guarantee those run sequentially, actually it’s very likely that multiple requests will happen concurrently.

What would you recommend for that use case ?

Hi @martin-yumsto thanks for providing the sample code repo.

Which callsite that the the error “Attempted to get the Amplify Server Context that may have been destroyed.” was thrown from precisely? Is that this getServerUserInfo() function?

This is function it seemed to use an “injected” contextSpec object to call the Amplify server-side fetchAuthSession() and fetchUserAttribute() which could be problematic. You should not cache contextSpec anytime and use it to invoke API at a later time. A contextSpec gets created at the beginning of a runWithAmplifyServerContext call, and gets destroyed before runWithAmplifyServerContext returns. So you should always use runWithAmplifyServerContext to wrap calls of Amplify server-side APIs.

In addition, looking at this Promise.all(), since they are concurrent, two refresh token service calls could initiated so it adds up the latency. You can do the following:

runWithAmplifyServerContext({
  amplifyConfig,
  Auth: {},
  async operation(contextSpec): {
    // fetchAuthSession and fetchUserAttributes will be running in the same context since they
    // are receiving the same contextSpec, so fetchUserAttributes() will use new tokens
    // refreshed by fetchAuthSession()
    const session = await fetchAuthSession(contextSpec);
    const attrs = await fetchUserAttributes(contextSpect);

    return [session, attrs];
  }
})

Hey @HuiSF, I made minimal reproduction repo to make it easier, this is post refactoring version that work locally, however, it doesn’t work when I deploy it to lambda (still haven’t figured why the amplify context gets destroyed before it’s used).

This is my output, you can see userInfo still takes really long to resolve:

Page reload sent to client(s).
req:  { token: { value: Symbol(AmplifyServerContextToken) } }
this.amplifyContext:  { token: { value: Symbol(AmplifyServerContextToken) } }
userInfo: 600.159ms
userInfo:  {
  id: ',
  username: '',
  groups: Set(5) {
  }
}
response:  Response {
  status: 200,
  statusText: '',
  headers: Headers { 'Content-Type': 'text/html;charset=UTF-8' },
  body: ReadableStream { locked: false, state: 'readable', supportsBYOB: true },
  bodyUsed: false,
  ok: true,
  redirected: false,
  type: 'default',
  url: ''
}
finally runWithAmplifyServerContext

EDIT: I created also repro for my first version which uses multiple runWithAmplifyServerContext and works on both local dev as well as lambda deployment, here are logs from that one:

userInfo: 716.035ms
userInfo:  {
  id: '',
  username: '',
  groups: Set(5) {
  }
}

Hi @HuiSF,

I need to spent bit more time on it, did all the refactoringt o wrap my angular ssr with runAmplifyServerContext to call it just once and ended up with breaking my prod Attempted to get the Amplify Server Context that may have been destroyed..

Moreover, I realized previously reported improvement in times was just due to accessing app using unauth session - with identity pool, when I switched to logged user with user pool today I’m back to 700ms.

I’ll keep you posted when I got single runAmplifyServerContext implemented and some progress.