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.41k stars 2.11k forks source link

ERROR in ./src/App.js 53:27-54 export 'Auth' (imported as 'Auth') was not found in 'aws-amplify' (possible exports: Amplify) #12591

Closed chrchng closed 9 months ago

chrchng commented 9 months ago

Before opening, please confirm:

JavaScript Framework

React

Amplify APIs

Authentication

Amplify Categories

auth

Environment information

``` # Put output below this line System: OS: Windows 10 10.0.19045 CPU: (4) x64 Intel(R) Core(TM) i5-6600K CPU @ 3.50GHz Memory: 4.49 GB / 15.94 GB Binaries: Node: 20.9.0 - C:\Program Files\nodejs\node.EXE npm: 10.2.3 - C:\Program Files\nodejs\npm.CMD Browsers: Chrome: 119.0.6045.160 Edge: Spartan (44.19041.3636.0), Chromium (119.0.2151.72) Internet Explorer: 11.0.19041.3636 npmPackages: @aws-amplify/core: ^3.8.9 => 3.8.24 (6.0.3) @aws-amplify/core/internals/adapter-core: undefined () @aws-amplify/core/internals/aws-client-utils: undefined () @aws-amplify/core/internals/aws-client-utils/composers: undefined () @aws-amplify/core/internals/aws-clients/cognitoIdentity: undefined () @aws-amplify/core/internals/aws-clients/pinpoint: undefined () @aws-amplify/core/internals/providers/pinpoint: undefined () @aws-amplify/core/internals/utils: undefined () @aws-amplify/core/server: undefined () @aws-amplify/ui-react: ^6.0.2 => 6.0.2 @aws-amplify/ui-react-internal: undefined () @mapbox/mapbox-gl-style-spec: 13.18.0-dev @testing-library/jest-dom: ^5.11.4 => 5.17.0 @testing-library/react: ^11.1.0 => 11.2.7 @testing-library/user-event: ^12.1.10 => 12.8.3 aws-amplify: ^6.0.3 => 6.0.3 aws-amplify/adapter-core: undefined () aws-amplify/analytics: undefined () aws-amplify/analytics/kinesis: undefined () aws-amplify/analytics/kinesis-firehose: undefined () aws-amplify/analytics/personalize: undefined () aws-amplify/analytics/pinpoint: undefined () aws-amplify/api: undefined () aws-amplify/api/server: undefined () aws-amplify/auth: undefined () aws-amplify/auth/cognito: undefined () aws-amplify/auth/cognito/server: undefined () aws-amplify/auth/server: undefined () aws-amplify/datastore: undefined () aws-amplify/in-app-messaging: undefined () aws-amplify/in-app-messaging/pinpoint: undefined () aws-amplify/push-notifications: undefined () aws-amplify/push-notifications/pinpoint: undefined () aws-amplify/storage: undefined () aws-amplify/storage/s3: undefined () aws-amplify/storage/s3/server: undefined () aws-amplify/storage/server: undefined () aws-amplify/utils: undefined () aws-sdk: ^2.831.0 => 2.1499.0 dotenv: ^8.2.0 => 8.6.0 (10.0.0) mapbox-gl: ^1.0.0 => 1.13.3 react: ^17.0.1 => 17.0.2 (18.2.0) react-dom: ^17.0.1 => 17.0.2 react-map-gl: ^5.2.11 => 5.3.21 react-scripts: ^5.0.1 => 5.0.1 web-vitals: ^0.2.4 => 0.2.4 npmGlobalPackages: @aws-amplify/cli: 12.8.2 npm: 10.2.3

Describe the bug

I am currently following this tutorial: https://youtu.be/-QcEMHqndzw?list=PLGyRwGktEFqebocpKlgAEoVssEyhXpRFP&t=971 and receive the following error when viewing the app web page: image

The associated code is found here: https://github.com/mavi888/amplify-location

My current App.js code is as:

image image

Expected behavior

The web page should display a map similar to image

Reproduction steps

  1. Followed tutorial to set up react app and modified code
  2. Ran npm start in project directory and receive error

Code Snippet

// Put your code below this line.

`import React, { useState, useEffect } from 'react';

import logo from './logo.svg';
import './App.css';

import ReactMapGL, {
  NavigationControl,
} from "react-map-gl";

import "mapbox-gl/dist/mapbox-gl.css";
import { Amplify, Auth } from 'aws-amplify';
import { Signer } from "@aws-amplify/core";
import awsconfig from './aws-exports';

const mapName = "TempeMap";

Amplify.configure(awsconfig);

/**
 * Sign requests made by Mapbox GL using AWS SigV4.
 */
const transformRequest = (credentials) => (url, resourceType) => {
  // Resolve to an AWS URL
  if (resourceType === "Style" && !url?.includes("://")) {
    url = `https://maps.geo.${awsconfig.aws_project_region}.amazonaws.com/maps/v0/maps/${url}/style-descriptor`;
  }

  // Only sign AWS requests (with the signature as part of the query string)
  if (url?.includes("amazonaws.com")) {
    return {
      url: Signer.signUrl(url, {
        access_key: credentials.accessKeyId,
        secret_key: credentials.secretAccessKey,
        session_token: credentials.sessionToken,
      })
    };
  }

  // Don't sign
  return { url: url || "" };
};

const App = () => {
  const [credentials, setCredentials] = useState(null);

  const [viewport, setViewport] = useState({
    longitude: -111.93354,
    latitude: 33.41858,
    zoom: 10,
  });

  useEffect(() => {
    const fetchCredentials = async () => {
      setCredentials(await Auth.currentUserCredentials());
    };

    fetchCredentials();
  }, []);

  return (
    <div>
      <header>
        <h1>GPS/IoT Map</h1>
      </header>

      {credentials ? (
        <ReactMapGL
          {...viewport}
          width="100%"
          height="100vh"
          transformRequest={transformRequest(credentials)}
          mapStyle={mapName}
          onViewportChange={setViewport}
        >
          <div style={{ position: "absolute", left: 20, top: 20 }}>
            {/* react-map-gl v5 doesn't support dragging the compass to change bearing */}
            <NavigationControl showCompass={false} />
          </div>
        </ReactMapGL>
      ) : (
        <h1>Loading...</h1>
      )}
    </div>
  );
};

export default App;`

### Log output

<details>

// Put your logs below this line



</details>

### 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_identity_pool_id": "us-east-2:81e897c7-5d54-4858-8bb2-ab01b08231df",
    "aws_cognito_region": "us-east-2",
    "aws_user_pools_id": "us-east-2_yqxSAoYzK",
    "aws_user_pools_web_client_id": "3gt4o1t2cpgju4m1scfmmcuntl",
    "oauth": {},
    "aws_cognito_username_attributes": [],
    "aws_cognito_social_providers": [],
    "aws_cognito_signup_attributes": [
        "EMAIL"
    ],
    "aws_cognito_mfa_configuration": "OFF",
    "aws_cognito_mfa_types": [
        "SMS"
    ],
    "aws_cognito_password_protection_settings": {
        "passwordPolicyMinLength": 8,
        "passwordPolicyCharacters": []
    },
    "aws_cognito_verification_mechanisms": [
        "EMAIL"
    ]
};

export default awsmobile;

### Manual configuration

_No response_

### Additional configuration

_No response_

### Mobile Device

_No response_

### Mobile Operating System

_No response_

### Mobile Browser

Chrome

### Mobile Browser Version

_No response_

### Additional information and screenshots

_No response_
yaraboec commented 9 months ago

Hi, check this https://docs.amplify.aws/javascript/build-a-backend/troubleshooting/migrate-from-javascript-v5-to-v6/#4-upgrade-category-usage

nadetastic commented 9 months ago

Hii @chrchng thank you for opening this issue.

Can you verify what version of aws-amplify your project is installed with? We recently released V6 of the library and the import have changed. Essentially, if your project is using V6, then the error you see is expected as we no longer export Auth but instead export the specific methods.

For example:

Also take a look at the migration guide shared by @yaraboec above.

Thanks.

mzagel commented 9 months ago

Hi @nadetastic ,

I'm having the same issues. I studied the documentation, but I still feel lost. My main issue is the basic configuration that we do via the Auth.configure() method:

import { Auth } from '@aws-amplify/auth';

Auth.configure({
    region: Config.cognito.REGION,
    userPoolId: Config.cognito.POOL_ID,
    userPoolWebClientId: Config.cognito.CLIENT_APP_ID,
    authenticationFlowType: 'USER_PASSWORD_AUTH',
    cookieStorage: {
        domain: DOMAIN,
        path: '/',
        expires: 365,
        sameSite: 'lax',
    }
});

I haven't found a way yet to do this with V6.

Can you give me a hint how to do this configuration for V6?

louisthomaspro commented 9 months ago

Hi @mzagel , in V6 you configure auth using Amplify.configure() https://docs.amplify.aws/nextjs/tools/libraries/configure-categories/#scoped-configuration

mzagel commented 9 months ago

Hi @louisthomaspro , thanks for the hint. The scoped configuration looks somewhat like what I need. However when I try to configure it that way the properties don't exist. According to the types the Auth type only contains a property Cognito, nothing else. What am I missing? Do I maybe need another npm package?

louisthomaspro commented 9 months ago

Same for me...

nadetastic commented 9 months ago

@mzagel @louisthomaspro the scoped config is the proper way to do this but the documentation is not inline with how V6 works. Im currently working to udpate however here is how you would set it:

Amplify.configure({
  Auth: {
    Cognito: {
      userPoolClientId: '',
      userPoolId: '',
      identityPoolId: '',
    },
  },
});

The Cognito object is where you would pass your backend resources.

As for the authentication flow, you would set that when you call signIn() as shown here instead of passing it into Amplify.configure()

signIn({
  username,
  password,
  options: {
      authFlowType: 'USER_PASSWORD_AUTH' 
  }
})
McGruck commented 9 months ago

I think the key here is that the imports and calls are different now.

import { signUp } from 'aws-amplify/auth';

async function handleSignUp({ username, password, email, phone_number }) {
  try {
    const { isSignUpComplete, userId, nextStep } = await signUp({
      username,
      password,
      options: {
        userAttributes: {
          email,
          phone_number // E.164 number convention
        },
      }
    });

    console.log(userId);
  } catch (error) {
    console.log('error signing up:', error);
  }
}
mzagel commented 9 months ago

@nadetastic Thanks for the hints. I was now able to get a version running. However I'm still struggling with two configurations:

  1. Where can I set the cookie storage configuration?
    cookieStorage: {
    domain: DOMAIN,
    path: '/',
    expires: 365,
    sameSite: 'lax',
    }
  2. In the old version I could also set the region. This property however does not exist in the Cognito settings. Where did this setting go?
nadetastic commented 9 months ago

@mzagel you can configure your cookie storage as shown in the documentation here and as shown in this code sample:

import { Amplify, type ResourcesConfig } from 'aws-amplify';
import { defaultStorage } from 'aws-amplify/utils';
import { cognitoUserPoolsTokenProvider } from 'aws-amplify/auth/cognito';

const authConfig: ResourcesConfig['Auth'] = {
  Cognito: {
    userPoolId: 'your_user_pool_id',
    userPoolClientId: 'your_user_pool_client_id'
  }
};

Amplify.configure({
  Auth: authConfig
});

cognitoUserPoolsTokenProvider.setKeyValueStorage(defaultStorage);

As for the region, you no longer need to set that value.

nadetastic commented 9 months ago

Hi @mzagel following up - let me know if you still need assistance here, if not I'll go ahead and close out this issue. Thanks!

mzagel commented 9 months ago

Hi @nadetastic , sorry for the late reply. I was on holiday last week.

I just implemented the cookie storage and it seems to work perfectly.

Thanks a lot for your help!

nadetastic commented 9 months ago

@mzagel you're welcome! Glad to hear you are unblocked.