Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unhandled TypeError with Auth.currentAuthenticatedUser() #12594

Closed
3 tasks done
zackseyun opened this issue Nov 20, 2023 · 20 comments
Closed
3 tasks done

Unhandled TypeError with Auth.currentAuthenticatedUser() #12594

zackseyun opened this issue Nov 20, 2023 · 20 comments
Assignees
Labels
Auth Related to Auth components/category Core Related to core Amplify issues pending-maintainer-response Issue is pending a response from the Amplify team. V6 V6 of Amplify JS

Comments

@zackseyun
Copy link

Before opening, please confirm:

JavaScript Framework

Next.js

Amplify APIs

Authentication

Amplify Categories

auth

Environment information

  System:
    OS: macOS 13.5
    CPU: (8) arm64 Apple M2
    Memory: 81.22 MB / 16.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.5.0 - /usr/local/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 9.8.0 - /usr/local/bin/npm
  Browsers:
    Chrome: 119.0.6045.159
    Edge: 119.0.2151.72
    Safari: 16.6
  npmGlobalPackages:
    corepack: 0.19.0
    npm: 9.8.0
    yarn: 1.22.19

Describe the bug

TypeError with Auth from AWS Amplify Across Different Components

I am experiencing a persistent TypeError related to the AWS Amplify Auth module in my React application. The error message Module '"aws-amplify"' has no exported member 'Auth'.ts(2305) occurs whenever I attempt to use Auth from @aws-amplify/auth. This issue is not isolated to a specific component but appears across different components where Auth is utilized.

Expected behavior

The expected behavior is that the Auth module from AWS Amplify should be recognized and utilized correctly for authentication purposes throughout the application, without throwing any TypeErrors.

Reproduction steps

Import Auth from @aws-amplify/auth in any component.
Use any method from Auth, such as Auth.signOut() or Auth.currentAuthenticatedUser().
Observe that the application throws a TypeError stating that the Auth module is not exported from aws-amplify.

Code Snippet

// Put your code below this line.
import React, { useState } from 'react';
import { useRouter } from 'next/router';
import { useUser } from '../contexts/UserContext';
import { Auth } from '@aws-amplify/auth';

const Navigation = () => {
  // ... other component logic ...

  const handleLogout = async () => {
    try {
      await Auth.signOut(); // AWS Cognito sign out
      // ... additional logout logic ...
    } catch (error) {
      console.error('Error signing out: ', error);
    }
  };

  // ... remaining component code ...
};

export default Navigation;

Log output

// Put your logs below this line
Uncaught TypeError: Cannot read properties of undefined (reading 'currentAuthenticatedUser')
    at eval (HomePage.tsx:42:10)
    at commitHookEffectListMount (react-dom.development.js:23150:1)
    at commitPassiveMountOnFiber (react-dom.development.js:24926:1)
    at commitPassiveMountEffects_complete (react-dom.development.js:24891:1)
    at commitPassiveMountEffects_begin (react-dom.development.js:24878:1)
    at commitPassiveMountEffects (react-dom.development.js:24866:1)
    at flushPassiveEffectsImpl (react-dom.development.js:27039:1)
    at flushPassiveEffects (react-dom.development.js:26984:1)
    at eval (react-dom.development.js:26769:1)
    at workLoop (scheduler.development.js:266:1)
    at flushWork (scheduler.development.js:239:1)
    at MessagePort.performWorkUntilDeadline (scheduler.development.js:533:1)
eval @ HomePage.tsx:42
commitHookEffectListMount @ react-dom.development.js:23150
commitPassiveMountOnFiber @ react-dom.development.js:24926
commitPassiveMountEffects_complete @ react-dom.development.js:24891
commitPassiveMountEffects_begin @ react-dom.development.js:24878
commitPassiveMountEffects @ react-dom.development.js:24866
flushPassiveEffectsImpl @ react-dom.development.js:27039
flushPassiveEffects @ react-dom.development.js:26984
eval @ react-dom.development.js:26769
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533
client.js:1 The above error occurred in the <HomePage> component:

    at HomePage (webpack-internal:///./components/HomePage.tsx:41:80)
    at Chat
    at div
    at MotionComponent (webpack-internal:///./node_modules/framer-motion/dist/es/motion/index.mjs:49:65)
    at ToastProvider (webpack-internal:///./contexts/ToastContext.tsx:25:23)
    at UserProvider (webpack-internal:///./contexts/UserContext.tsx:40:23)
    at PresenceChild (webpack-internal:///./node_modules/framer-motion/dist/es/components/AnimatePresence/PresenceChild.mjs:15:26)
    at AnimatePresence (webpack-internal:///./node_modules/framer-motion/dist/es/components/AnimatePresence/index.mjs:72:28)
    at MyApp (webpack-internal:///./pages/_app.tsx:30:24)
    at _PathnameContextProviderAdapter (webpack-internal:///./node_modules/next/dist/shared/lib/router/adapters.js:106:24)
    at ErrorBoundary (webpack-internal:///./node_modules/next/dist/compiled/@next/react-dev-overlay/dist/client.js:2:5389)
    at ReactDevOverlay (webpack-internal:///./node_modules/next/dist/compiled/@next/react-dev-overlay/dist/client.js:2:7785)
    at Container (webpack-internal:///./node_modules/next/dist/client/index.js:153:5)
    at AppContainer (webpack-internal:///./node_modules/next/dist/client/index.js:323:24)
    at Root (webpack-internal:///./node_modules/next/dist/client/index.js:582:25)

React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary.
console.error @ client.js:1
window.console.error @ setup-hydration-warning.js:18
overrideMethod @ console.js:213
logCapturedError @ react-dom.development.js:18687
callback @ react-dom.development.js:18755
callCallback @ react-dom.development.js:13923
commitUpdateQueue @ react-dom.development.js:13944
commitLayoutEffectOnFiber @ react-dom.development.js:23364
commitLayoutMountEffects_complete @ react-dom.development.js:24688
commitLayoutEffects_begin @ react-dom.development.js:24674
commitLayoutEffects @ react-dom.development.js:24612
commitRootImpl @ react-dom.development.js:26823
commitRoot @ react-dom.development.js:26682
performSyncWorkOnRoot @ react-dom.development.js:26117
flushSyncCallbacks @ react-dom.development.js:12042
flushPassiveEffectsImpl @ react-dom.development.js:27060
flushPassiveEffects @ react-dom.development.js:26984
eval @ react-dom.development.js:26769
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533
Show 1 more frame
Show less


aws-exports.js

/* eslint-disable */
// WARNING: DO NOT EDIT. This file is automatically generated by AWS Amplify. It will be overwritten.

const awsmobile = {
"aws_project_region": "us-east-2",
"aws_cognito_region": "us-east-2", // The region your Cognito service is hosted in
"aws_user_pools_id": "us-east-2_9S9WFq6Gx", // Your Cognito User Pool ID
"aws_user_pools_web_client_id": "40ev1t07p25s89s6ru95314t87", // Your Cognito User Pool App Client ID
"oauth": {
"domain": "carthaai.auth.us-east-2.amazoncognito.com", // Your Amazon Cognito domain
"scope": ["email", "openid", "phone"], // The scopes for the OAuth flow
"redirectSignIn": "https://cartha.ai", // The callback URL after sign-in
"redirectSignOut": "", // Since sign out URL is optional, it's left empty
"responseType": "code" // The OAuth response type you want to use
},
Analytics: {
disabled: false,
},
};

export default awsmobile;

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

Additional Context:

The error occurs in various components where Auth is imported and used.
AWS Amplify is configured correctly in _app.tsx.
The application was working fine prior to the recent changes.
No conditional rendering or other major logic changes seem to affect this issue.

@zackseyun zackseyun added the pending-triage Issue is pending triage label Nov 20, 2023
@nadetastic nadetastic self-assigned this Nov 20, 2023
@nadetastic
Copy link
Member

Hi @zackseyun thank you for opening this issue.

Can you verify what version of aws-amplify your project is installed with? It looks like you may have aws-amplify@>6 installed based on the error message. We recently released V6 of the library and the imports have changed. What this means is if your project is using V6, then the error you see (Module '"aws-amplify"' has no exported member 'Auth'.ts) is expected as we no longer export Auth but instead export the specific methods.

For example:

Also note that when migrating to V6, a few other changes include the name of the methods - for example v6 no longer has currentAuthenticatedUser but has the equivalent getCurrentUser.

I also recommend taking a look at the migration guide for further details - https://docs.amplify.aws/javascript/build-a-backend/troubleshooting/migrate-from-javascript-v5-to-v6/#4-upgrade-category-usage

Let me know if you have any more questions.

@nadetastic nadetastic added Auth Related to Auth components/category Core Related to core Amplify issues pending-response and removed pending-triage Issue is pending triage labels Nov 20, 2023
@zackseyun
Copy link
Author

zackseyun commented Nov 20, 2023

I can confirm I was on "aws-amplify": "^6.0.3".

Thanks for pointing out that this could be a versioning change.

I followed: https://docs.amplify.aws/react/build-a-backend/auth/manage-user-session/

This was my final implementation that worked:

    // AWS Cognito synchronization
    const checkCurrentUser = async () => {
      try {
        const { username, userId, signInDetails } = await getCurrentUser();

        setUser({
          isLoggedIn: true,
          userId: userId,
          email: signInDetails?.loginId || null, // Assuming loginId is the email
        });
      } catch (error) {
        console.log('Error getting current authenticated user:', error);
        if (user.isLoggedIn) {
          setUser({
            isLoggedIn: false,
            userId: null,
            email: null,
          });
        }
      }
    };
    checkCurrentUser();
  }, [user, setUser]);

this is resolved. thank you!

@zackseyun
Copy link
Author

zackseyun commented Nov 21, 2023

I have one more question,

in the new docs, what would be the equivalent for the functionality:

import { Auth } from 'aws-amplify'; 
...
const handleResendCode = async () => {
    // when resend button is pressed
    setErrorMessage(''); // Reset error message
    setCanRetry(false);
    setCountdown(60); // Reset countdown
    try {
      await Auth.resendSignUp(email);
      setShowResendButton(false); // Hide the button after successful resend
    } catch (error) {
      console.error('Error resending code: ', error);
      setShowResendButton(true); // Show the button in case of an error
    }
  };

after browsing the developer docs, I cant seem to find the right function that would give me the same effect as previous version usages

@nadetastic
Copy link
Member

@zackseyun glad you were able to get unblocked and the issue was just a version mismatch!

As for you second question, it looks like you are trying to resend the signup/confirmation code. With the new version of the library, you would use the resendSignUpCode() api. Here's an example of what it would look like:

import { 
    resendSignUpCode,
    ResendSignUpCodeInput,
    ResendSignUpCodeOutput
} from 'aws-amplify/auth'; 

const handleResendSignUpCode = async () => {

    const userInfo: ResendSignUpCodeInput = {
        username: email
    }

    try {
      const response: ResendSignUpCodeOutput = await resendSignUpCode(userInfo);
    } catch (error) {
      console.error('Error resending code: ', error);
    }
};

Also note that we have improved type support, and are able to import the input and outputs of the apis.

@zackseyun
Copy link
Author

zackseyun commented Nov 21, 2023

Great, thank you! one more question:

On a previous version of amplify, I could usually have a setup like:

import { Auth } from '@aws-amplify/auth';
import { withAuthenticator, AmplifySignInButton } from '@aws-amplify/ui-react';

function SocialLoginButtons() {
  const handleSignInGoogle = async () => {
    try {
      await Auth.federatedSignIn({ provider: 'Google' });
    } catch (error) {
      console.error('Error signing in with Google:', error);
    }
  };

and then I could use custom button for my social logins, like Google. Without Auth being available, some of the documentation on how to do this seems like it's no longer available.

Instead I'm looking through the amplify codebase to look for an equivalent for federatedSignIn (https://github.com/aws-amplify/amplify-js/blob/main/packages/auth/src/index.ts#L81) and I'm still confused on what to use if I want a handler to help me with either "create an account" or "sign in" with a social provider. Any pointers here?

@nadetastic
Copy link
Member

@zackseyun sure thing! So the federatedSignIn() method has been renamed to signInWithRedirect() since the behavior of this method is to redirect you to a different Social provider - also, you can use it to sign in a regular user through a redirect via the Cognito Hosted UI. Here's a link to the documentation that explains a bit more:

@zackseyun
Copy link
Author

zackseyun commented Nov 23, 2023

hey @nadetastic, I'm experiencing an issue related to the authStatus update in the useAuthenticator hook. My application's components are conditionally rendered based on the authStatus. However, I've noticed that there's a delay in the authStatus changing to 'authenticated' after a successful sign-in. This delay causes a mismatch between the actual authentication state and the UI representation.

So by the time authStatus is triggered the useEffect, if (authStatus === 'authenticated') is evaluating to false. but when I print to my console to see the value of authStatus, it is indeed "authenticated", but only after much delay.

What else I tried:

I also considered using the isSignedIn function from the migration guide, but then I'd have to manage more aspects of the authentication process.
https://docs.amplify.aws/javascript/build-a-backend/troubleshooting/migrate-from-javascript-v5-to-v6/#4-upgrade-category-usage

Do you have a suggestion on an alternative method? I tried as many different methods to no avail and really would like to not install my own delay for these processes, and seems like this should be very simple. (This v6 upgrade has been so cumbersome I tried reverting to v5, but it seemed I wouldnt be able to use amplify ui-react without using v6). Appreciate your help~

Relevant code snippet:

const RegisterAndLogin = () => {
  const router = useRouter();
  const { authStatus } = useAuthenticator((context) => [context.authStatus]);
  console.log('Current auth status:', authStatus);

  useEffect(() => {
    if (authStatus === 'authenticated') {
      console.log('User is authenticated, redirecting to chat page');
      router.push('/Chat');
    }
  }, [authStatus]);

(ill make this my last question so i dont keep trailing, but this documentation is very sparse)

@nadetastic
Copy link
Member

Hi @zackseyun I've created a new issue in the Amplify UI repo based on your last question, in order to get better assistance, please follow up there 🙂

@nadetastic nadetastic added pending-response and removed investigating This issue is being investigated labels Nov 29, 2023
@HurYur
Copy link

HurYur commented Nov 30, 2023

Also note that when migrating to V6, a few other changes include the name of the methods - for example v6 no longer has currentAuthenticatedUser but has the equivalent getCurrentUser.

I also recommend taking a look at the migration guide for further details - https://docs.amplify.aws/javascript/build-a-backend/troubleshooting/migrate-from-javascript-v5-to-v6/#4-upgrade-category-usage

@nadetastic is there a full list of equivalents to methods from v5 to v6? We are going to migrate to new version, and it's really painful, as there is no info about that. For example, there was found nothing about currentAuthenticatedUser replacement in the docs, thanks.

@zackseyun
Copy link
Author

zackseyun commented Nov 30, 2023 via email

@nadetastic
Copy link
Member

@HurYur we are working on expanding the migration guide to show a list of equivalent methods between v5 and v6, will provide an update once it is published.

@zackseyun just to confirm, are you still facing an issue?

@zackseyun
Copy link
Author

got it, yes that would be super helpful (and code examples help a TON).

yes I am still facing the issue, the new question is posted here:

aws-amplify/amplify-ui#4788

@nadetastic nadetastic added documentation Related to documentation feature requests and removed pending-response labels Dec 4, 2023
@nadetastic
Copy link
Member

Hi @HurYur following up - here's a guide showing a list of equivalent Auth methods between v5 and v6

@uclaeamsavino
Copy link

uclaeamsavino commented Dec 6, 2023

@nadetastic Thanks for that guide. I couldn't find that linked to anywhere in the main migration guide page and finally found my way to this issue. A more prominent link on this page would be very helpful: https://docs.amplify.aws/javascript/build-a-backend/troubleshooting/migrate-from-javascript-v5-to-v6/

I'm still really confused about some stuff like verifyCurrentUserAttributeSubmit. But hopefully I'll figure it out.

Also do you know if there's a similar guide for aws-amplify/api? I need to migrate that too and I can't find a replacement for API.configure.

@nadetastic nadetastic added the V6 V6 of Amplify JS label Jan 23, 2024
@nadetastic
Copy link
Member

Hi @uclaeamsavino following up here - we have provided a migration guide for Rest API which can be found here - https://docs.amplify.aws/react/build-a-backend/restapi/restapi-v5-to-v6-migration-guide/

As for GraphQL api, have you had a chance to view the documentation linked here? Additionally configuring the API can be seen here for GraphQL and here for Rest API.

Let me know if you have any other question.

@nadetastic nadetastic added pending-response and removed documentation Related to documentation feature requests labels Jan 23, 2024
@AdonousTech
Copy link

Why is the migration guide nested under React.? Where is the existing API documentation on Auth? I went to https://aws-amplify.github.io/amplify-js/api/index.html and I can't find the v5 docs anymore. For example, I was trying to refresh on Auth.currentAuthenticatedUser and can no longer find the docs.

@nadetastic
Copy link
Member

Hi @AdonousTech, the documentation site is organized by framework however you should be able to access the documentation under any of the Javascript frameworks using the framework selector at the top left. Additionally, for the v5 documentation, you can click the switcher to be able to reference that.

Screenshot 2024-02-05 at 10 01 08 AM

@nadetastic
Copy link
Member

@AdonousTech I'm going to mark this issue as resolved for now as it has been a few weeks since an update. If you still have questions, feel free to respond on this issue or open a new one if you have unrelated questions/issues. Thanks!

@MuhammadAflah
Copy link

@AdonousTech how to do the Auth.forgotPassword in v6, whats the alternative for this ?

@github-actions github-actions bot added the pending-maintainer-response Issue is pending a response from the Amplify team. label Dec 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Auth Related to Auth components/category Core Related to core Amplify issues pending-maintainer-response Issue is pending a response from the Amplify team. V6 V6 of Amplify JS
Projects
None yet
Development

No branches or pull requests

6 participants