NextJS Firebase 연결

이대현·2024년 9월 17일
0

사이드 프로젝트

목록 보기
2/3
  1. firebase 콘솔에서 프로젝트를 만들어준다.
  2. 프로젝트에 파이어베이스를 설치후
  3. 파이어베이스를 config를 설정해준다.
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";

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,
  measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID,
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);

4.간단한 api를 만들어서 get, post를 테스트해봤다.

// app/api/users/route.js

import { db } from "@/app/firebase";
import { collection, getDocs, addDoc } from "firebase/firestore";

export async function GET() {
  try {
    const userCollection = collection(db, "user");
    const userSnapshot = await getDocs(userCollection);
    const users = userSnapshot.docs.map((doc) => ({
      id: doc.id,
      ...doc.data(),
    }));

    return new Response(JSON.stringify(users), {
      status: 200,
      headers: { "Content-Type": "application/json" },
    });
  } catch (error) {
    return new Response(
      JSON.stringify({ message: "Failed to fetch users", error }),
      {
        status: 500,
        headers: { "Content-Type": "application/json" },
      }
    );
  }
}

export async function POST(request: any) {
  try {
    // 요청에서 JSON 데이터 가져오기
    const body = await request.json();
    const { name } = body;
    // Firestore에서 'users' 컬렉션에 문서 추가
    const userCollection = collection(db, "user");
    const docRef = await addDoc(userCollection, {
      name,
      createdAt: new Date(), // 생성 시간 추가
    });

    // 성공적으로 추가되면 응답
    return new Response(
      JSON.stringify({ message: "User added", id: docRef.id }),
      { status: 200, headers: { "Content-Type": "application/json" } }
    );
  } catch (error) {
    console.error("Error adding user:", error);
    return new Response(
      JSON.stringify({ message: "Error adding user", error }),
      { status: 500, headers: { "Content-Type": "application/json" } }
    );
  }
}
  1. 화면에서 적용될 코드
"use client";
import { useEffect } from "react";
import { Box, Typography, Button } from "@mui/material";
import axiosInstance from "@/app/api";

const TestPage = () => {
  const addUsers = async () => {
    await axiosInstance.post("/api/test", { name: "user add test" });
  };

  const getUsers = async () => {
    const res = await axiosInstance.get("/api/test");
    console.log(res.data);
  };

  useEffect(() => {
    getUsers();
  }, []);

  return (
    <Box>
      <Typography>Test page</Typography>
      <Button variant="contained" onClick={addUsers}>
        Add user
      </Button>
    </Box>
  );
};

export default TestPage;
profile
Frontend Developer

0개의 댓글