Post

firestore - 400 에러 해결하기 + 컬렉션 저장하기

📝 400에러 해결하기기

Firebase를 이용해 로그인 기능을 구현후, 사용자 정보를 firestore에 저장하려는 생각을 가지고 있었지만… 저장이 안되는 문제가 발생했다. 🤨

에러 메세지는 다음과 같다.

1
2
3
4
400. That’s an error.

Your client has issued a malformed or illegal request.
Unknown SID That’s all we know.

구글 검색을 해봐도 비슷한 원인을 찾기 어려웠고 😥 점점 미궁에 빠지던 차에.. rule이 잘못되었을 수 있다고 해서 확인해보았더니 원인이 바로 rule 이었다 (…)

해당 firestore를 만든지 시간이 지났던 지라, requestime이 만료되었던 것이다!

1
allow read, write: if request.time < timestamp.date(2025, 12, 31); 🌟

이 부분을 바로 올해 말까지로 명시해주니 firestore에 컬렉션도 잘 생기고 저장도 문제 없이 진행되었다.

✅ firestore에 컬렉션 저장

참고로 firestore에 컬렉션 저장은 다음과 같이 진행했다. 나는 firebase.tsfirestore.ts를 따로 나누어 작성했다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//firebase.ts
import { initializeApp } from "firebase/app"

const firebaseConfig = {
  apiKey: process.env.NEXT_PUBLIC_API_KEY,
  authDomain: process.env.NEXT_PUBLIC_AUTH_DOMAIN,
  projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
  storageBucket: process.env.NEXT_PUBLIC_STORAGE_BUCKET,
  messagingSenderId: process.env.NEXT_PUBLIC_MESSAGING_SENDER_ID,
  appId: process.env.NEXT_PUBLIC_APP_ID,
}

const firebaseApp = initializeApp(firebaseConfig)

export default firebaseApp
1
2
3
4
5
6
7
//firestore.ts
import { getFirestore } from "firebase/firestore"
import firebaseApp from "./firebase"

const db = getFirestore(firebaseApp)

export default db

먼저 이렇게 기본 세팅을 해두고, 컬렉션에 저장하는 테스트코드는 공식 문서에 나온 내용으로 간단하게 세팅해 주었다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
"use client"

import db from "@utils/firestore"
import { collection, addDoc } from "firebase/firestore"

export default function SigninFireStore() {
  const handleSave = async () => {
    try {
      const docRef = await addDoc(collection(db, "users"), {
        first: "Ada",
        last: "Lovelace",
        born: 1815,
      })
      console.log("Document written with ID: ", docRef.id)
    } catch (e) {
      console.error("Error adding document: ", e)
    }
  }

  return <button onClick={handleSave}>Firestore에 저장</button>
}

이제 Create가 잘 되었으니, 나머지 RUD도 작성해보자! 이 내용은 투비컨티뉴…🌟

This post is licensed under CC BY 4.0 by the author.