Auth0 React SDK sometimes fails with "Login required" for cypress + localstorage cache

  • Which SDK this is regarding: auth0/auth0-react
  • SDK Version: 1.8.0

In our Create React App, we use the auth0 react SDK to secure our application, which works fine. We also use Cypress for E2E testing. After trying many guides, we got auth0 + Cypress working. A guide posted by auth0 has shown to be useless, as they still use cookies to inject the token, but the newest auth0 react SDK only supports memory or localstorage as cacheLocation. Also the auth0 guide by cypress plainly uses an old SDK.

This is what we came up with in the end, which works:

Cypress.Commands.add(
  'login',
  (username: string = Cypress.env('default_login_username'),
    password: string = Cypress.env('default_login_password')) => {
    cy.log(`Logging in as ${username}`);

    const auth0Scope = 'openid email profile [CUSTOM SCOPES]';

    const options = {
      method: 'POST',
      url: `https://${Cypress.env('auth0_domain')}/oauth/token`,
      body: {
        grant_type: 'password',
        username,
        password,
        audience: Cypress.env('auth0_audience'),
        scope: auth0Scope,
        client_id: Cypress.env('auth0_client_id'),
        client_secret: Cypress.env('auth0_client_secret'),
      },
    };
    const localStorageKey = `@@auth0spajs@@::${Cypress.env('auth0_client_id')}::${Cypress.env('auth0_audience')}::${auth0Scope}`;
    return cy.request(options).then((response) => {
      const { body } = response;
      // Adapted from https://medium.com/@turhangur/handling-tests-on-protected-pages-with-cypress-auth0-90dd99fd8cf6
      const claims = jwtDecode<JwtPayload>(body.id_token);

      const tokenInformation = {
        body: {
          ...body,
          decodedToken: {
            claims,
            user: {
              ...claims,
              // In here you can hand pick which properties you want to insert based on your
              // application. It can be different based on your needs.
            },
          },
        },
        expiresAt: claims.exp,
      };
      window.localStorage.setItem(localStorageKey, JSON.stringify(tokenInformation));
    });
  },
);

BUT what’s now bugging us is that some tests became flaky, sometimes failing. Somewhere within the auth0 React SDK, a OAuthError with “Login required” is thrown. BUT only sometimes! I’ve tried calling cy.wait(5000) after every test to see if it’s a rating or timing issue, but even then it sometimes fails:

Any help is much appreciated!