Firebase multiple "apps" - client side and server side - javascript

So, I wanted to add another firebase app into the project. I already had one for SSR (firebase-admin), so server could pre-render sites. Now I want to add firebase#8, so I can start using it on client side, and later apply firestore rules to it. The problem is, when I'm trying to use it I get this error:
/node_modules/#google-cloud/storage/build/src/bucket.js:22:0
Module not found: Can't resolve 'fs'
Import trace for requested module:
./node_modules/#google-cloud/storage/build/src/index.js
./node_modules/firebase-admin/lib/storage/storage.js
./node_modules/firebase-admin/lib/app/firebase-namespace.js
./node_modules/firebase-admin/lib/default-namespace.js
./node_modules/firebase-admin/lib/index.js
./firebase/config.js
./firebase/createDocument.js
./components/form/Form.js
./pages/opinia/index.js
https://nextjs.org/docs/messages/module-not-found
Here is my config file:
import * as admin from 'firebase-admin';
import firebase from 'firebase';
import 'firebase/firestore';
// initialize firebase on CLIENT
const firebaseConfig = {
apiKey: process.env.FIREBASE_KEY,
authDomain: process.env.FIREBASE_DOMAIN,
projectId: process.env.FIREBASE_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.APP_ID,
};
export const clientApp = initializeApp(firebaseConfig);
// firestore
export const projectFirestoreClient = firebase.firestore(clientApp);
// timestamp
export const timestampClient = firebase.firestore.Timestamp;
// initialize firebase on SERVER
if (!admin.apps.length) {
const serviceAccount = require('./firebase-adminsdk.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
}
// firestore
export const projectFirestoreAdmin = admin.firestore();
// timestamp
export const timestampAdmin = admin.firestore.Timestamp;
So, my question is, how do I fix this error? And what's causing it? Thanks in advance.

Firebase Admin is not meant to be used on client side. When you run the app, Firebase Admin is also being imported and causing that error. Ideally you should initialize Firebase Admin in a different file that can be accessed on server side only.
Checkout this blog for step-by-step explanation on how to use Firebase Admin with NextJS.

Related

Initialize Firebase realtime database

I have the following code:
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import {
getDatabase,
} from "firebase/database";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey:
"XXXXXXXXXXXXXXXXXX",
authDomain:
"XXXXXXX-XX-XXXXX.firebaseapp.com",
databaseUrl:
"https://XXXXXXX-XX-XXXXX-default-rtdb.europe-west1.firebasedatabase.app",
projectId: "XXXXXXX-XX-XXXXX",
storageBucket:
"XXXXXXX-XX-XXXXX.appspot.com",
messagingSenderId: "AAAAAAAAAAAA",
appId:
"1:AAAAAAAAAAAA:web:BBBBBBBBBBBBBBB",
measurementId: "G-XXXXXXXXX",
};
// Initialize Firebase
const app = initializeApp(
firebaseConfig
);
const db = getDatabase();
When running my code, Firebase kindly tells me the following:
[2022-11-23T22:45:42.778Z] #firebase/database: FIREBASE WARNING: Database lives in a different region. Please change your database URL to https://XXXXXXX-XX-XXXXX-default-rtdb.europe-west1.firebasedatabase.app (https://XXXXXXX-XX-XXXXX-default-rtdb.firebaseio.com/)
I as a friend of order reads the outputed message and CHANGES the databaseUrl in my code as the one STATED by Firebase in above message.
I then run my code again and get the SAME message. What am I doing wrong?

Firebase .listUsers() is not function

I have been looking for some time, but without answers, so I ask my question:
I work with firebase and I make a function 'getAllUsers' (which must return all registered user uid) :
function getAllusers(nextPageToken){
app.auth().listUsers(1000, nextPageToken)
.then(function(listUsersResult) {
listUsersResult.users.forEach(function(userRecord) {
console.log('user', userRecord.toJSON());
});
if (listUsersResult.pageToken) {
// List next batch of users.
listAllUsers(listUsersResult.pageToken);
}
})
.catch(function(error) {
console.log('Error listing users:', error);
});
}
(yes, this is the doc example)
but I get
Uncaught TypeError: app.auth is not a function
I tested :
auth().listUsers()
getAuth.listUsers()
I think this is my imports:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-app.js";
import { getAuth, signInWithPopup, createUserWithEmailAndPassword, signInWithEmailAndPassword, GoogleAuthProvider, signOut, getAdditionalUserInfo, reauthenticateWithCredential } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-auth.js";
import { getDatabase, set, ref, update, child, onValue, get } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-database.js";
import { getStorage, ref as sRef, uploadBytes, getDownloadURL, deleteObject } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-storage.js";
const firebaseConfig = {
apiKey: "XX",
authDomain: "XX",
databaseURL: "XX",
projectId: "XX",
storageBucket: "XX",
messagingSenderId: "XX",
appId: "XX",
measurementId: "XX"
};
const app = initializeApp(firebaseConfig);
const database = getDatabase(app);
const auth = getAuth(app);
const storage = getStorage(app);
I am currently researching how to use 'admin' for this
Hoping someone can help me, I keep looking, thanks in advance
The Firebase Admin SDK run code with elevated/administrative permissions and thus can only be used in a trusted environment, such as your development machine, a server that you control, or Cloud Functions/Cloud Run. They cannot be used in client-side application code, as that would be a security concern.
The regular Firebase SDKs only allow a user access to their own profile data, as doing otherwise on an SDK level would be a security concern.
If the application needs to show information about other users, you will have to build (and secure) that yourself on top of Firebase. The two most common options:
Implement the functionality in a custom server-side API that uses the Admin SDK and that you can call from your client-side application code. The custom server-side code you write should then ensure that only data that the caller is authorized to see is returned.
Have each user write to a cloud-hosted database (such as Firestore or the Realtime Database or Firebase), and then have other users read it from there. In this scenario you'll want to use Firebase's security rules to ensure each user can only access the data they're authorized for.
This topic has been covered frequently before, so I recommend also checking out:
Firebase list all users
How do I return a list of users if I use the Firebase simple username & password authentication
Can't retrieve list of all users from firebase authetication
Retrieving a list of users who have registered using Firebase Auth

How do I upload images to Firebase, with CDN and version 9.5.0?

I'm trying to upload an image through JavaScript, with Firebase Storage. But, i can't find the method to upload the files on version 9.5.0, using the CDN (<script type="module">)
I've searched around the documenntation, and I found "storageRef.put", but, it gives me Uncaught TypeError: storage.put is not a function on the console.
Can someone help me?
JavaScript code:
import { getStorage, ref } from "https://www.gstatic.com/firebasejs/9.5.0/firebase-storage.js";
const storage = getStorage(app);
const storageRef = ref(storage);
function submit() {
const file = document.getElementById("file").files[0];
storageRef.put(file);
}
document.getElementById("submit").addEventListener("click", submit);
HTML:
<script src="https://cdnjs.cloudflare.com/ajax/libs/firebase/8.2.2/firebase-app.min.js"></script>
<input type="file" id="file"><br><br>
<button id="submit">Enviar</button>
In the change from Firebase v8 (namespaced) to v9 (modular) they had an overhaul of the SDK. Version 9 is not a drop in replacement for v8.
In your code I'm seeing v8 in the HTML and v9 in the javascript.
So using only v9, the example from their docs:
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.5.0/firebase-app.js";
import { getStorage, ref, uploadBytes } from "https://www.gstatic.com/firebasejs/9.5.0/firebase-storage.js";
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
// Initialize Firebase
const firebaseApp = initializeApp(firebaseConfig);
// Get a reference to the storage service, which is used to create references in your storage bucket
const storage = getStorage(firebaseApp);
const storageRef = ref(storage, 'some-child');
// 'file' comes from the Blob or File API
const file = document.getElementById("file").files[0];
uploadBytes(storageRef, file).then((snapshot) => {
console.log('Uploaded a blob or file!');
});
</script>
As a note, you can use v9 with v8 syntax but you need to pull in the compat packages as well. You can check their upgrade guide for more information.

Firebase web. No signInWithUsernameAndPassword function

I am very confused about firebase web because when I create an auth using firebase.auth() then try to call a method directly from the firebase documentation, signInWithUsernameAndPassword, it does not work. I am using
webstorm and is says it is an unrecognized method.
// Initialize Firebase
var config = {
apiKey: "AIzaSyBbmdeersid6XSA4kh_TYsGgVSgVF5BrFs",
authDomain: "eraticators-73723.firebaseapp.com",
databaseURL: "https://eraticators-73723.firebaseio.com",
projectId: "eraticators-73723",
storageBucket: "eraticators-73723.appspot.com",
messagingSenderId: "782651564720"
};
firebase.initializeApp(config);
const txtEmail = document.getElementById("user");
const txtPassword = document.getElementById("password");
const btnLogin = document.getElementById("btnLogin");
btnLogin.addEventListener("click", function() {
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
firebase.auth().signInWithUsernameAndPassword(email, pass);
});
that is my javascript file. The only suggested functions are signInViaPopup() and signInViaRedirect(). Why is there not signInWithUsernameAndPassword function when that is exactly what the documentation says to use????
signInWithUsernameAndPassword does not exist. Firebase Auth does not support sign in with username and password. It only supports sign in with email and password. The equivalent method is signInWithEmailAndPassword.
The Firebase docs and references should not mention the former at all.
can you please check have you enabled authentication with Email/Password.
if you didn't enable it.
Follow the path given below:-
firebase console -> authentication -> sign-in method.
and enable signIn with email/password
You need to add the script auth tag in the html.

Firebase credentials don't work when authenticated

I'm trying to implement an authentication for firebase in my react app. I do that with github but it's not relevant.
So I have some credentials and they work just fine. I can fetch my data from db and manilpulate it.
Until I login...
After successfully executing this: firebase.auth().signInWithPopup(githubProvider).then ...
I start constantly receiving warnings of that kind:
FIREBASE WARNING: Provided authentication credentials for the app named "[DEFAULT]" are invalid. This usually indicates your app was not initialized correctly. Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.
I can't do anything to my DB.
And this continues until I log out with firebase.auth().signOut().then ... then everything works fine again.
inb4: I am 100% confident that my credentials are correct. I have copied and pasted them several times.
Can someone give me insight on what is going on in that case?
And here's how I initialize the App
import firebase from 'firebase';
try {
const config = {
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.REACT_APP_FIREBASE_DATABASE_URL,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
};
firebase.initializeApp(config);
} catch (e) {}
export const githubProvider = new firebase.auth.GithubAuthProvider();
export const firebaseRef = firebase.database().ref();
export default firebase;

Categories

Resources