I've been struggling with the process of sending authenticated firebase/firestore calls. I set up firestore in my web app using Next.js as shown below:
import { initializeApp } from "firebase/app";
import { getFirestore } from 'firebase/firestore';
import { GoogleAuthProvider, getAuth } from "firebase/auth";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
};
const app = initializeApp(firebaseConfig);
// firestore
export const db = getFirestore(app);
//auth
export const provider = new GoogleAuthProvider();
export const auth = getAuth();
Here's a snippet from one of my APIs:
import { db } from "../../../utils/db/init";
import {
collection,
addDoc,
serverTimestamp,
setDoc,
doc,
} from "firebase/firestore";
/** [POST] Add user to database.
* req.body requires:
* @param email
* @returns user
*/
export default async function addUserHandler(req, res) {
try {
const data = {
...req.body,
createdAt: serverTimestamp(),
followers: [],
following: [],
};
const { id } = await addDoc(collection(db, "users"), data);
await setDoc(doc(db, "users", id), { seed: id }, { merge: true }); // add seed for sorting posts (same as id)
res.status(200).json({ ...data, id });
} catch (error) {
console.error(error);
res.status(500).json(error.message);
}
}
In my firestore rules:
...
match /users/{userId}{
allow read, write: if request.auth.uid != null;
}
Even though the user is logged in when this API is called, firebase keeps showing
Missing or insufficient permissions
. What am I overlooking? How can I properly include authentication in the request?