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

Uncaught ReferenceError: global is not defined #12746

Closed
3 tasks done
FPRM opened this issue Dec 22, 2023 · 5 comments
Closed
3 tasks done

Uncaught ReferenceError: global is not defined #12746

FPRM opened this issue Dec 22, 2023 · 5 comments
Assignees
Labels
amazon-cognito-identity-js Used for issues related to this specific package within the monorepo documentation Related to documentation feature requests

Comments

@FPRM
Copy link

FPRM commented Dec 22, 2023

Before opening, please confirm:

JavaScript Framework

Vue

Amplify APIs

Not applicable

Amplify Categories

Not applicable

Environment information

  System:
    OS: Windows 10 10.0.19045
    CPU: (16) x64 AMD Ryzen 7 3700X 8-Core Processor
    Memory: 17.08 GB / 31.92 GB
  Binaries:
    Node: 18.18.0 - C:\Program Files\nodejs\node.EXE
    npm: 10.2.3 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Edge: Chromium (120.0.2210.77)
    Internet Explorer: 11.0.19041.3636
  npmPackages:
    amazon-cognito-identity-js: ^6.3.7 => 6.3.7
    amazon-cognito-identity-js/internals:  undefined ()
  npmGlobalPackages:
    @vue/cli: 5.0.8
    corepack: 0.19.0
    create-vite: 4.4.1
    npm: 10.2.3


Describe the bug

After installing the npm package and writing my code to initiate auth connexion, app it not rendering and got error

Uncaught ReferenceError: global is not defined
at ../node_modules/buffer/index.js (amazon-cognito-identity-js.js?v=ef93d19d:215:35)
at __require2 (chunk-AUZ3RYOM.js?v=ef93d19d:18:50)
at amazon-cognito-identity-js.js?v=ef93d19d:2716:29

who send me back to line 215
Buffer5.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== void 0 ? global.TYPED_ARRAY_SUPPORT : typedArraySupport();

Expected behavior

Gehing able to render app and launch authentication with password and username to get tokens

Reproduction steps

  1. install npm librairy
  2. implement code to handle auth
  3. implementing front to collect username and password
  4. trigger auth method

Code Snippet

// import { CognitoUserPool, CognitoUser} from 'amazon-cognito-identity-js';
  import { useUserStore } from '@/store/UserStore.js';
  import { createPinia } from 'pinia';
  import {
    CognitoUser,
    AuthenticationDetails,
    CognitoUserPool,
    CognitoRefreshToken
} from 'amazon-cognito-identity-js';

 const userStore = useUserStore(createPinia())
  
  
  export async function CheckUserAuth(){
    console.log("check from store if user data send auth status")
    if(userStore.is_logged){
      return true
    }
    if(!userStore.is_logged){
      const accessToken = localStorage.getItem("engine_access_token");
      const appToken = localStorage.getItem("engine_app_token");
      const refreshToken = localStorage.getItem("engine_refresh_token");
      const UserName = localStorage.getItem("engine_user_name");
      var tsToken = localStorage.getItem("engine_ts_token");
      tsToken = Number(tsToken);
      const currentTime = Math.floor(Date.now() / 1000);
      if (!accessToken || !appToken || !refreshToken || !tsToken || !UserName) {
        return false
      }
      else if (tsToken && currentTime > tsToken) {
        // Timestamp has passed
        return false;
      }
      else if (tsToken && currentTime < tsToken) {
        const result_re_auth = await reauthenticateUser(UserName,refreshToken)
        console.log("reauth token")
        console.log(result_re_auth)
      }
    }
    
  }

  export async function AuthUser(username,password){
    const poolData = {
      UserPoolId: process.env.VUE_APP_COGNITO_USER_POOL,
      ClientId: process.env.VUE_APP_COGNITO_CLIENT_ID
    };
    const userPool = new CognitoUserPool(poolData);
    const authenticationDetails = new AuthenticationDetails({
      Username: username,
      Password: password
    });

    const cognitoUser = new CognitoUser({
        Username: username,
        Pool: userPool
    });

    return new Promise((resolve, reject) => {
        cognitoUser.authenticateUser(authenticationDetails, {
            onSuccess: (session) => {
                const accessToken = session.getAccessToken().getJwtToken();
                const idToken = session.getIdToken().getJwtToken();
                const refreshToken = session.getRefreshToken().getToken();
                resolve({ accessToken, idToken, refreshToken });
            },
            onFailure: (err) => {
                reject(err);
            }
        });
    });
  }

  function reauthenticateUser(username, refreshTokenValue) {
    const poolData = {
      UserPoolId: process.env.VUE_APP_COGNITO_USER_POOL,
      ClientId: process.env.VUE_APP_COGNITO_CLIENT_ID
    };
    
    const userPool = new CognitoUserPool(poolData);

    const userData = {
      Username: username,
      Pool: userPool
    };
    

    const cognitoUser = new CognitoUser(userData);

    const refreshToken = new CognitoRefreshToken({ RefreshToken: refreshTokenValue });

    return new Promise((resolve, reject) => {
        cognitoUser.refreshSession(refreshToken, (err, session) => {
            if (err) {
                reject(err);
            } else {
                const tokens = {
                    accessToken: session.getAccessToken().getJwtToken(),
                    idToken: session.getIdToken().getJwtToken(),
                    refreshToken: session.getRefreshToken().getToken()
                };
                resolve(tokens);
            }
        });
    });
}
  

  
  

Log output

// Put your logs below this line


aws-exports.js

No response

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

@FPRM FPRM added the pending-triage Issue is pending triage label Dec 22, 2023
@cwomack
Copy link
Member

cwomack commented Dec 22, 2023

Hello, @FPRM 👋. Would you mind sharing your full package.json and (if this is a vite project) your vite.config.js as well? I believe you can resolve this by defining global in your config similar to what's shown in this comment from another issue where others experienced this error.

@cwomack cwomack self-assigned this Dec 22, 2023
@cwomack cwomack added investigating This issue is being investigated dependencies Pull requests that update a dependency file pending-response and removed pending-triage Issue is pending triage labels Dec 22, 2023
@FPRM
Copy link
Author

FPRM commented Dec 22, 2023

@cwomack sure i tried what you mentionned in comment as i tried 'global': 'window' and 'global': {'window'} but none of 3 worked.
i give you my package json as my vite.config

Package.json

{
  "name": "RI_APP",
  "version": "0.0.0",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "lint": "eslint . --fix --ignore-path .gitignore"
  },
  "dependencies": {
    "@mdi/font": "7.0.96",
    "amazon-cognito-identity-js": "^6.3.7",
    "pinia": "^2.0.23",
    "roboto-fontface": "*",
    "vue": "^3.2.0",
    "vue-router": "^4.0.0",
    "vuetify": "^3.0.0",
    "webfontloader": "^1.0.0"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^4.0.0",
    "eslint": "^8.22.0",
    "eslint-plugin-vue": "^9.3.0",
    "vite": "^4.2.0",
    "vite-plugin-vuetify": "^1.0.0"
  }
}

vite.config.js

// Plugins
import vue from '@vitejs/plugin-vue'
import vuetify, { transformAssetUrls } from 'vite-plugin-vuetify'

// Utilities
import { defineConfig } from 'vite'
import { fileURLToPath, URL } from 'node:url'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue({ 
      template: { transformAssetUrls }
    }),
    // https://github.com/vuetifyjs/vuetify-loader/tree/next/packages/vite-plugin
    vuetify({
      autoImport: true,
    }),
  ],
  define: {
    'process.env': {},
    'globale':{}
  },
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    },
    extensions: [
      '.js',
      '.json',
      '.jsx',
      '.mjs',
      '.ts',
      '.tsx',
      '.vue',
    ],
  },
  server: {
    port: 3000,
  },
})

@huyb1991
Copy link

@FPRM As your post, I saw your config is:

  define: {
    'process.env': {},
    'globale':{}
  },

The globale is incorrect, should be global, the config for define should be:

  define: {
    process.env: process.env
    global: {}
  },

@nadetastic nadetastic added amazon-cognito-identity-js Used for issues related to this specific package within the monorepo and removed dependencies Pull requests that update a dependency file labels Dec 28, 2023
@nadetastic
Copy link
Member

Hi @FPRM were you able to get this resolved, or do you still need assitance?

@nadetastic nadetastic added question General question pending-response and removed investigating This issue is being investigated labels Feb 13, 2024
@cwomack cwomack added the documentation Related to documentation feature requests label Mar 5, 2024
@cwomack
Copy link
Member

cwomack commented Mar 6, 2024

@FPRM, it looks like there were steps missing from the Vue.js block switcher to ensure the polyfills needed to avoid these build errors are added into each project. I've created an issue on the amplify-docs repo to get this updated, but it looks like this would only impact apps that are either on v5 of Amplify or using the amplify-cognito-identity-js package. If anyone is following the v6 docs, this shouldn't be an issue.

We'll track the progress of the docs updates separately, and I'll close this issue out on the JS side since this should be resolved in v6 as well as have an easy workaround to implement the missing polyfills. Feel free to reply back if you disagree or have further questions on this. Thanks!

@cwomack cwomack closed this as completed Mar 6, 2024
@cwomack cwomack removed the question General question label Mar 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
amazon-cognito-identity-js Used for issues related to this specific package within the monorepo documentation Related to documentation feature requests
Projects
None yet
Development

No branches or pull requests

4 participants