Having trouble hiding the API key and other variables on my website using Javascript. I tried dotenv (npm install dotenv
) but it did not work. I tried it using:
1. import
import * as dotenv from 'dotenv'
dotenv.config();
console.log(process.env);
and it runs to an error
Uncaught SyntaxError: Cannot use import statement outside a module
2. require
require('dotenv').config();
also runs to an error
Uncaught ReferenceError: require is not defined
.env file
apiKey=XXXXXXXXXXXXXXXXXX
authDomain=XXXXXXXXXXXXX
etc=etcetera
where were the .env variables will be used
const firebaseConfig = {
apiKey: process.env.apiKey,
authDomain: process.env.authDomain,
databaseURL: process.env.databaseURL,
projectId: process.env.projectId,
storageBucket: process.env.storageBucket,
messagingSenderId: process.env.messagingSenderId,
appId: process.env.appId,
measurementId: process.env.measurementId
};
firebase.initializeApp(firebaseConfig);
Is there a way to make dotenv work? If none, is there any other way to hide API keys?
PS: I’ve purposely enabled the read and write in firebase and I need to hide api keys and such.
2
Answers
As per @Eddi and @boreddad420 stated that I can't directly use my firebase function on the client side and importing dotenv should be done in the backend of the project.
I have found a youtube video that is easy to follow on how to make a simple backend nodejs using express with firebase firestore. After watching the video I was able to create a fully working backend nodejs.
For you to solve the error:
Uncaught SyntaxError: Cannot use import statement outside a module
, you’ll need to add"type": "module"
in yourpackage.json
, then you’ll be able to useimport
syntax.