amplify-js icon indicating copy to clipboard operation
amplify-js copied to clipboard

Uncaught ReferenceError: global is not defined

Open FPRM opened this issue 1 year ago • 4 comments

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 avatar Dec 22 '23 17:12 FPRM

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 avatar Dec 22 '23 18:12 cwomack

@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,
  },
})

FPRM avatar Dec 22 '23 21:12 FPRM

@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: {}
  },

huyb1991 avatar Dec 25 '23 07:12 huyb1991

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

nadetastic avatar Feb 13 '24 04:02 nadetastic

@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 avatar Mar 06 '24 21:03 cwomack