Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings
Discussion options

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 )
enter image description here

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

You must be logged in to vote

@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.

Replies: 4 comments · 12 replies

Comment options

Seeing the same issue did you find a fix? @Shailendra1703

You must be logged in to vote
10 replies
@0xGoenka
Comment options

I'm also using firebase inside a chrome extension which is my second guess, will update when I resolve

@dennismunene
Comment options

I changed how I initialized my db object from const db = getFirestore(app') to const db = getFirestore(app,'my_collection') and It started working.

@0xGoenka
Comment options

Yeah, my problem was a renamed my DB name when I created it, and so it was not the default name : (default) which is what caused the problem on my side, after creating a new db with default name everything worked lol,

Would be nice if they had meaningfull error message

@Shailendra1703
Comment options

@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.

Answer selected by dlarocque
@alexandreomiranda
Comment options

@0xGoenka saved the day. I was trying to find a solution to this for two days. Creating a new DB with (default) name made it work. Agreed, no meaningfull error message at all.

@FPan7792
Comment options

Be blessed @dennismunene ! I spent my 3 last days refactoring my code from A to Z thinking I was going to become crazy and losing every piece of trust in my debugging skills until I finally found your solution . This is crazy to realize this details isn't mentioned anywhere easily in firestore docs

@tvadiep
Comment options

@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.

really really appreciate, you saved me

@jaxazam
Comment options

I changed how I initialized my db object from const db = getFirestore(app') to const db = getFirestore(app,'my_collection') and It started working.

I had the same issue for last 3 days and this is what worked for me; needing to explicitly reference the database during getFirestore() initialization. Tysm!

Comment options

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:

const serviceAccount = require('./path/to/serviceAccountKey.json');

initializeApp({
  credential: cert(serviceAccount)
});

const db = getFirestore();
You must be logged in to vote
2 replies
@dlarocque
Comment options

Hi @moza88, I am looking into this for my own understanding.

This is what they have in their docs:

const serviceAccount = require('./path/to/serviceAccountKey.json');

initializeApp({
  credential: cert(serviceAccount)
});

const db = getFirestore();

Where exactly did you find this code snippet? I can't find it in the Firebase documentation, and it's not at the page you linked.

@Shailendra1703
Comment options

Hello @dlarocque , few days back I was working on some app where I need to send json data to firestore, then I asked claude sonnet the new AI model, which also gave me this code snippet. Might be possible he got it from there not sure tbh.

Comment options

I created a firestore default database but I kept getting 400 requests errors when I tried to connect with my app. I thought it was because i set my database location to be europe but my functions and hosting in was us.

But in the end, i just had to define my database name when i get firestore.

const app = initializeApp(firebaseConfig);

const db = getFirestore(app, "default");

I tried debugging for hours with ChatGPT 4o but it didn't know the, it kept telling me to create a datastore database, or change the host name to eur. Hopefully this helps some people and firebase can add some error messages for this kind of error.

You must be logged in to vote
0 replies
Comment options

The solution for me was to add the database nema in the getFirestore init function like:

const db = getFirestore(app, "<the database name>");

It seems that it doesn't work with "default" so you need to name your db when you create it.

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
🙏
Q&A
Labels
None yet
Morty Proxy This is a proxified and sanitized view of the page, visit original site.