I am working on a Project and for the Authentication I have used Amazon Cognito Service. Now, I have a file in which I have defined Userpools and for those Userpool configs I have used Env Variables (With the Prefix REACT_APP_) But when I import this file containing Userpool into another file It gives me an error that it isn't able to fetch those Env variables. I have provided the code below for better Understanding.
Userpool.js
import { CognitoUserPool } from 'amazon-cognito-identity-js'
// This line below is Printing the Env Variable Correctly
// console.log(process.env.REACT_APP_USERPOOL_ID_USER)
const poolData_user = {
UserPoolId: process.env.REACT_APP_USERPOOL_ID_USER,
ClientId: process.env.REACT_APP_CLIENT_ID_USER
}
const poolData_admin = {
UserPoolId: process.env.REACT_APP_USERPOOL_ID_ADMIN,
ClientId: process.env.REACT_APP_CLIENT_ID_ADMIN
}
export const userPool = CognitoUserPool(poolData_user)
export const adminPool = CognitoUserPool(poolData_admin)
SignUpPage.js
import { userPool, adminPool } from './Userpool'
const SignUpPage = () => {
// This method below will be invoked when user clicks on a Button
const handleButtonClick = () => {
userPool.singUp('someEmail','somePassword',[],null,(err,result)=>{
if(err)
console.error(err)
else
console.log(result)
})
}
return ({/* some JSX which has a button*/})
}
But when I use that Button in SignUpPage.js
it is giving me the error as shown below.
Getting the same error even if I use dotenv
module in my file as shown below.
Userpool.js
This file will remain same as shown above.
SignUpPage.js
import dotenv from 'dotenv'
import { userPool, adminPool } from './Userpool'
dotenv.config()
const SignUpPage = () => {
// This method below will be invoked when user clicks on a Button
const handleButtonClick = () => {
userPool.singUp('someEmail','somePassword',[],null,(err,result)=>{
if(err)
console.error(err)
else
console.log(result)
})
}
return ({/* some JSX which has a button*/})
}
CodePudding user response:
It is possible that you need to use environment variables like this when running your project (example for Bash):
REACT_APP_USERPOOL_ID_USER=userId REACT_APP_CLIENT_ID_USER=clientId command_to_start
However, there is something that I would like to recommend to you, which was used in practically every project I have worked on - dotenv. With this, you can avoid the problem that you are having and also have an easier way of working with environment variables.
This package allows you to have a file called .env
where you define your environment variables which will be accessible with process.env
. This helps other devs know which env variables are needed for your project by having all of them in one place.
It works great in all environments such as development, staging and production because you can have one version of .env
file for each of those.