aws-amplify / amplify-js

A declarative JavaScript library for application development using cloud services.
https://docs.amplify.aws/lib/q/platform/js
Apache License 2.0
9.43k stars 2.13k forks source link

Unhandled TypeError with Auth.currentAuthenticatedUser() #12594

Closed zackseyun closed 9 months ago

zackseyun commented 11 months ago

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 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.

nadetastic commented 11 months ago

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.

zackseyun commented 11 months ago

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 commented 11 months ago

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 commented 11 months ago

@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 commented 11 months ago

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 commented 11 months ago

@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 commented 11 months ago

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 commented 11 months ago

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 🙂

HurYur commented 11 months ago

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 commented 11 months ago

Hi Dan, nowhere in my code am I using Auth or v5 code.

On Mon, Nov 20, 2023, 8:06 AM Dan Kiuna @.***> wrote:

Hi @zackseyun https://urldefense.com/v3/__https://github.com/zackseyun__;!!LIr3w8kk_Xxm!sku3_jxSAlMaDF8ju9PLPt-ZYi6ezjfLGxA-IyLbVCjR4i31WpUKkE4BOmo27_ioQ2eJbDoviD25c5OZAtXdTWF6$ 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 https://urldefense.com/v3/__https://docs.amplify.aws/javascript/build-a-backend/troubleshooting/migrate-from-javascript-v5-to-v6/*4-upgrade-category-usage__;Iw!!LIr3w8kk_Xxm!sku3_jxSAlMaDF8ju9PLPt-ZYi6ezjfLGxA-IyLbVCjR4i31WpUKkE4BOmo27_ioQ2eJbDoviD25c5OZAtVoHHie$

Let me know if you have any more questions.

— Reply to this email directly, view it on GitHub https://urldefense.com/v3/__https://github.com/aws-amplify/amplify-js/issues/12594*issuecomment-1819354524__;Iw!!LIr3w8kk_Xxm!sku3_jxSAlMaDF8ju9PLPt-ZYi6ezjfLGxA-IyLbVCjR4i31WpUKkE4BOmo27_ioQ2eJbDoviD25c5OZAum3gLa8$, or unsubscribe https://urldefense.com/v3/__https://github.com/notifications/unsubscribe-auth/ABQ6FL46JT5CLGGIQTNMXLTYFN5Y5AVCNFSM6AAAAAA7TET34WVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMYTQMJZGM2TINJSGQ__;!!LIr3w8kk_Xxm!sku3_jxSAlMaDF8ju9PLPt-ZYi6ezjfLGxA-IyLbVCjR4i31WpUKkE4BOmo27_ioQ2eJbDoviD25c5OZAo5YcJVY$ . You are receiving this because you were mentioned.Message ID: @.***>

nadetastic commented 11 months ago

@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 commented 11 months ago

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:

https://github.com/aws-amplify/amplify-ui/issues/4788

nadetastic commented 11 months ago

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

uclaeamsavino commented 11 months ago

@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.

zackseyun commented 11 months ago

This is resolved.

On Fri, Dec 1, 2023, 8:48 AM Dan Kiuna @.***> wrote:

@HurYur https://urldefense.com/v3/__https://github.com/HurYur__;!!LIr3w8kk_Xxm!shj8GTXh3SP9sfEDYT8bY5ByH-7jfn2bm91B0TNeEF9uxsRl20y5FJJjYn4rMwFVY4sWyCqG4lVjcQ3aXRHTRX4E$ 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 https://urldefense.com/v3/__https://github.com/zackseyun__;!!LIr3w8kk_Xxm!shj8GTXh3SP9sfEDYT8bY5ByH-7jfn2bm91B0TNeEF9uxsRl20y5FJJjYn4rMwFVY4sWyCqG4lVjcQ3aXdrxf0yd$ just to confirm, are you still facing an issue?

— Reply to this email directly, view it on GitHub https://urldefense.com/v3/__https://github.com/aws-amplify/amplify-js/issues/12594*issuecomment-1836447582__;Iw!!LIr3w8kk_Xxm!shj8GTXh3SP9sfEDYT8bY5ByH-7jfn2bm91B0TNeEF9uxsRl20y5FJJjYn4rMwFVY4sWyCqG4lVjcQ3aXTuswb2V$, or unsubscribe https://urldefense.com/v3/__https://github.com/notifications/unsubscribe-auth/ABQ6FLYOKYOLHAJ7NHUTGLLYHIC4DAVCNFSM6AAAAAA7TET34WVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMYTQMZWGQ2DONJYGI__;!!LIr3w8kk_Xxm!shj8GTXh3SP9sfEDYT8bY5ByH-7jfn2bm91B0TNeEF9uxsRl20y5FJJjYn4rMwFVY4sWyCqG4lVjcQ3aXRCBOL0x$ . You are receiving this because you were mentioned.Message ID: @.***>

nadetastic commented 9 months ago

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.

AdonousTech commented 9 months ago

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 commented 9 months ago

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 commented 9 months ago

@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!