Uncaught ReferenceError: global is not defined
Before opening, please confirm:
- [X] I have searched for duplicate or closed issues and discussions.
- [X] I have read the guide for submitting bug reports.
- [X] I have done my best to include a minimal, self-contained set of instructions for consistently reproducing the issue.
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
- install npm librairy
- implement code to handle auth
- implementing front to collect username and password
- 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
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 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 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: {}
},
Hi @FPRM were you able to get this resolved, or do you still need assitance?
@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!