개발새발 로그

firebase admin sdk 초기화(세팅)하기(How to use the firebase-admin.firestore function in firebase-admin) - (nodejs firebase error) 본문

카테고리 없음

firebase admin sdk 초기화(세팅)하기(How to use the firebase-admin.firestore function in firebase-admin) - (nodejs firebase error)

이즈흐 2023. 9. 5. 01:47

 

 

 

파이어베이스에서 비공개 키를 생성했다면 프로젝트에 연결해보자

 

 

 

firebase_admin.ts

const admin = require('firebase-admin');

interface Config {
  credentials: {
    privateKey: string;
    clientEmail: string;
    projectId: string;
  };
}

if (!admin.apps.length) {
  const config: Config = {
    credentials: {
      projectId: process.env.projectId || '',
      clientEmail: process.env.clientEmail || '',
      privateKey: process.env.privateKey?.replace(/\\n/g, '\n') || '',
    },
  };
  admin.initializeApp({
    credential: admin.credential.cert(config.credentials),
  });
  console.info('bootstrap firebase admin');
} else {
  admin.app();
}

module.exports = admin;

1. firebase_admin.ts 파일을 생성해서 서버에 firebase admin sdk를 추가한다.

2. firebase_admin.ts에서 아래 코드를 먼저 복사한다.

var admin = require("firebase-admin");

var serviceAccount = require("path/to/serviceAccountKey.json");

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

- 이 코드는 파이어베이스에서 Admin SDK 구성 스니펫에 있는 코드이다.

- 이 코드를 우리가 사용할 방식으로 바꿔보자

3. 먼저 타입스크립트이므로 interface를 만들어준다.

interface Config {
  credentials: {
    privateKey: string;
    clientEmail: string;
    projectId: string;
  };
}

4. ☝중요

if (!admin.apps.length)

- 해당 if문을 통해서 앱이 실행되어있지 않다면 초기화해주는 것이다.

- 이때 앱이 이미 실행되어서 초기화가 되어있다면 초기화는 하지말고 앱만 실행시키는 부분도 추가했다.

if (!admin.apps.length) {

  ...
  
} else {
  admin.app();
}

5. if문안에서 비공개키를 생성했던 json 파일을 가져와 준다. 

-이때 우리는 .env파일에서 환경변수로 만들어줬으므로 이를 활용한다.

const config: Config = {
    credentials: {
      projectId: process.env.projectId || '',
      clientEmail: process.env.clientEmail || '',
      privateKey: process.env.privateKey?.replace(/\\n/g, '\n') || '',
    },
  };

6. if문 안에서 firebase-admin 모듈을 초기화 해준다.

admin.initializeApp({
    credential: admin.credential.cert(config.credentials),
  });

7. 중요! 이 모듈을 export해줘서 hello.ts에서 사용이 가능하도록 한다.

module.exports = admin;

 

 

 

 

 

이제 파이어베이스가 잘 연결되었는지 확인해보자

 

hello.ts

import { NextApiRequest, NextApiResponse } from 'next';

const admin = require('../../model/firebase_admin');

export default function handler(_: NextApiRequest, res: NextApiResponse) {
  const db = admin.firestore();
  db.collection('test');
  res.status(200).json({ name: 'hello' });
}

-현재  firestore을 통해서 단지 test 콜렉션을 호출하는 명령어만 사용해 호출과 응답이 잘되는지만 확인했다.

 

 

1. 초기화한 모듈을 가져온다.

const admin = require('../../model/firebase_admin');

2. 해당 모듈에서 firestore을 가져온다.

  const db = admin.firestore();

3. test라는 이름의 collection을 호출하고, 이후 응답이 잘 오는지 확인한다.

export default function handler(_: NextApiRequest, res: NextApiResponse) {
  const db = admin.firestore();
  db.collection('test');
  res.status(200).json({ name: 'hello' });
}

 

 

 

 

 

☝중요한 점

1. firebase admin sdk를 초기화해주고 꼭 모듈을 export 해줘야한다.

module.exports = admin;

2. pribateKey값은 줄바꿈이 \n 로 바뀌어서 한줄로 값을 받아오기 때문에 replace를 통해 그 값을 줄바꿈해줘야한다.

privateKey: process.env.privateKey?.replace(/\\n/g, '\n') || '',

3. 모듈을 가져올 때는 import가 아니고 require을 이용한다.

const admin = require('../../model/firebase_admin');

참고 사이트

https://snyk.io/advisor/npm-package/firebase-admin/functions/firebase-admin.firestore

 

Choose the best package - Snyk Open Source Advisor

Find the best open-source package for your project with Snyk Open Source Advisor. Explore over 1 million open source packages.

snyk.io

 

 

 

💢오류

error - Error: The default Firebase app already exists. 
This means you called initializeApp() more than once without providing an app name as the sec to give each app a unique name.

-nodejs에서 firebase를 이용해 푸쉬메시지를 발송할 때 발생하는 에러입니다.

 

-위 에러 메시지를 보면 initializeApp()이 여러번 호출되여 발생하는 에러입니다.

const admin = require("firebase-admin");

const serviceAccount = require("../config/serviceAccount.json");
const databaseURL = "databaseURL";

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: databaseURL,
});

 

nodejs 코드내에서 2번 호출되는 부분이 생겨 문제가 발생합니다.

 

2. 해결 방법

const admin = require("firebase-admin");

const serviceAccount = require("../config/serviceAccount.json");
const databaseURL = "databaseURL";

if (!admin.apps.length) {
    var firebaseAdmin = admin.initializeApp({
        credential: admin.credential.cert(serviceAccount),
        databaseURL: databaseURL,
    });
}

 

  • 위의 코드처럼 있을시에는 저 로직을 안타게끔 설정해주시면 정상적으로 해결이 됩니다.

 

 

추가 수정 부분

https://coding-honeyjam.tistory.com/26

 

Firebase App named '[DEFAULT]' already exists 해결법

stackoverflow.com/questions/43331011/firebase-app-named-default-already-exists-app-duplicate-app Firebase App named '[DEFAULT]' already exists (app/duplicate-app) Hi I am trying to unit test while developing a simple web with AngularJS + Firebase, but I ha

coding-honeyjam.tistory.com

 

728x90
반응형
LIST