Getting Error Code 400 ( Bad Request ) when trying to add a document in firebase firestore #8352
-
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 |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 10 replies
-
Seeing the same issue did you find a fix? @Shailendra1703 |
Beta Was this translation helpful? Give feedback.
-
They moved to google cloud and it seems like now we have to deal with service accounts. https://firebase.google.com/docs/firestore/quickstart#node.js This is what they have in their docs:
|
Beta Was this translation helpful? Give feedback.
@dennismunene Hey hii, in my case the culprit was a comma inside my env variables, which I came to now recently, due to which my app was not Initializing.