How do we set up apiKey and storageBucket in environment url for firebaseConfig? I have tried using environment variable but it throws error for no bucket url set up before initializing app. I tried clearing .next folder and recompiled but still same error. Without securing storageBucket url, it is exposed to be added by anyone as the apiKey is also not being read from firebase storage. How to configure firebase storage from firebase security rules, so that user can upload only with valid API key from my .env file. I searched internet and also took help of chatGPT but did not find relevant answer. I’m working with NextJS 14.2.3.
firebase configuration provided by firebase.
/firebase.js
import { initializeApp } from 'firebase/app';
const firebaseConfig = {
apiKey: process.env.FIREBASE,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_SENDER_ID,
appId: process.env.FIREBASE_APP_ID,
};
export const app = initializeApp(firebaseConfig);
/.env
FIREBASE = firebase-api-string
FIREBASE_AUTH_DOMAIN = auth-domain-string
FIREBASE_PROJECT_ID = project-id-string
FIREBASE_STORAGE_BUCKET = storage-bucket-string
FIREBASE_SENDER_ID = sender-id-string
FIREBASE_APP_ID = app-id-string
/page.js
import { getStorage, ref, uploadBytesResumable, getDownloadURL } from 'firebase/storage';
import { app } from '@/utils/firebase';
const storage = getStorage(app);
const upload = () => {
const name = new Date().getTime();
const storageRef = ref(storage, name + file.name);
const uploadTask = uploadBytesResumable(storageRef, file);
uploadTask.on(
'state_changed',
(snapshot) => {
const progress =
(snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case 'paused':
console.log('Upload is paused');
break;
case 'running':
console.log('Upload is running');
break;
}
},
(error) => {
console.log(error.code);
},
() => {
getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
console.log(downloadURL);
setMedia(downloadURL);
});
}
);
};
file && upload();
But this doesn’t work by taking storageBucket into environment variable .env file. I want to configure such that I my storageBucket url is not exposed to public. Also, it is not validating apiKey from firebase storage rule.
/firebase
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read;
allow write: if request.resource.size < 200 * 1024 && request.auth != null;
}
}
}
I have recently started with backend development and I’m not able to understand firebase documentation accurately. If there is better resource to learn these things, please help me to reach that. TIA.
shailendrakrsk is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.