I'm working on a simple Nextjs application having some CRUD operation with firebase firestore database , I'm using zustand for state mangement but when I'm trying to add the document I'm getting the error code 400 ( Bad request ) in the console ( image attached below )
Here is the code
firebase.js file
import { initializeApp, getApps, getApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getStorage } from "firebase/storage";
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,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
};
const app = !getApps().length ? initializeApp(firebaseConfig) : getApp()[0];
const db = getFirestore(app);
const storage = getStorage(app);
export { app, db, storage };
Zustand State Mangement file
"use client";
import { create } from "zustand";
import { collection, addDoc, getDocs } from "firebase/firestore";
import { db, storage } from "@/config/firebase";
const useFirestoreStore = create((set) => ({
documents: [],
isLoading: false,
error: null,
addDocument: async (collectionName, data) => {
set({ isLoading: true, error: null });
try {
const docRef = await addDoc(collection(db, collectionName), data);
set((state) => ({
documents: [...state.documents, { id: docRef.id, ...data }],
isLoading: false,
}));
} catch (error) {
set({ error: error.message, isLoading: false });
}
},
getDocuments: async (collectionName) => {
set({ isLoading: true, error: null });
try {
const querySnapshot = await getDocs(collection(db, collectionName));
const docs = querySnapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}));
set({ documents: docs, isLoading: false });
} catch (error) {
set({ error: error.message, isLoading: false });
}
},
}));
export default useFirestoreStore;
A simple form
"use client";
import React, { useState } from "react";
import useFirestoreStore from "@/store/firestore";
import { db } from "@/config/firebase";
export default function Home() {
const { documents, isLoading, error, addDocument, getDocuments } =
useFirestoreStore();
const [formData, setFormData] = useState({ name: "", age: "" });
const handleAddDocument = async () => {
if (!formData.name || !formData.age) {
alert("Please fill in all fields");
return;
}
await addDocument("users", {
name: formData.name,
age: parseInt(formData.age, 10),
});
setFormData({ name: "", age: "" }); // Reset form
};
const handleInputChange = (e) => {
const { name, value } = e.target;
setFormData((prevState) => ({ ...prevState, [name]: value }));
};
return (
<div>
{isLoading && <p>Loading...</p>}
{error && <p>Error: {error}</p>}
<form onSubmit={(e) => e.preventDefault()}>
<label>
Name:
<input
type="text"
name="name"
value={formData.name}
onChange={handleInputChange}
/>
</label>
<label>
Age:
<input
type="number"
name="age"
value={formData.age}
onChange={handleInputChange}
className="text-black"
/>
</label>
<button type="button" onClick={handleAddDocument}>
Add User
</button>
</form>
</div>
);
}
Here are my Firebase firestore Rules
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
GitHub Repo >> https://github.com/Shailendra1703/fb
So After few days of debugging, I found that my env has an extra comma due to which my firestore db object was not setting up properly which resulted in this error.
For more info you can visit this github discussion >> https://github.com/firebase/firebase-js-sdk/discussions/8352