Sharryhong's Front-End
  • About Sharryhong's Front-End Blog.
  • Front-End Dev
    • Flutter
      • API Key 안전하게 숨기기. Cloudflare Workers!
      • Web CORS 에러
    • Vue.js
      • usePagination - composition api (vue2)
      • Pagination Component
      • Vue Image Skeleton
      • Sort an Array of Objects by Boolean property
      • Dynamic Components
      • LoadingBar Component
      • composition-api 사용하여 menu 의 outside click 시 close
      • vue+TypeScript
      • Vue.js 개발자를 위한 VS Code
      • Vue3 Chrome Extension
      • input file 선택된 파일 명 reset하기
      • element 내부 scroll 될 때, ScrollTop 값에 따라 div를 보이게, 안보이게 제어하기
      • 진입한 url path에 맞게 메서드 실행
    • React
      • 절대경로(absolute path) 설정, jsx파일로 이동 설정
      • useContext rerender issue
      • Firebase v9 Auth with React
      • Firebase v9 Realtime Database with React
      • React Star Rating (별점 표시)
      • React App deploying (배포)
    • Next.js
      • CSR, SSR, Next.js
    • API Mocking
      • Vue 에서 msw 적용하기
    • Storybook
      • styled-component theme.ts가 storybook엔 적용안되는 이슈
      • storybook에서 alias path 안되는 이슈
      • storybook에 Global Style 적용하기
  • etc
    • brew update
    • npm upgrade (mac)
  • DEV BETTER
    • Clean Code
      • Clean Code JavaScript 강의
        • Variables - 변수 다루기
        • Boundary - 경계 다루기
        • Conditional - 분기 다루기
        • Array - 배열 다루기
      • Tip. 클린 코드를 위한 5가지 팁
      • Tip. 코딩 잘하는 팁 3가지
    • 웹 성능 최적화 (performance)
      • performance 강의
        • loading, rendering performance
        • Tools
        • Image size optimization
        • bottleneck (병목) code 탐색
Powered by GitBook
On this page
  • 파이어베이스 버전9. 인증 setup
  • React Project에 firebase SDK setup하기
  • login, logout 설정 (Google, Github Sign-In)
  • firebase config 와 연결 후 dependency injection
  • login , logout 함수

Was this helpful?

  1. Front-End Dev
  2. React

Firebase v9 Auth with React

2022-02-24

PrevioususeContext rerender issueNextFirebase v9 Realtime Database with React

Last updated 3 years ago

Was this helpful?

토이프로젝트에 사용한 파이어베이스 관련 코드를 정리해보겠습니다.

파이어베이스 버전9. 인증 setup

Firebase 'Go to console'에서 project를 생성합니다.

'Add on app to get stated' (web) 클릭 후 app을 등록합니다.

app 등록시 config 코드가 나오고, 나중에 확인시에는 왼쪽 상단 '설정'버튼 -> '프로젝트 설정'을 클릭하면 나옵니다.

databaseURL 의 경우 Realtime Database 에서 Create Database

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: "...",
  authDomain: "...",
  databaseURL: "...", 
  projectId: "...",
  storageBucket: "...",
  messagingSenderId: "...",
  appId: "...",
  measurementId: "..."
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);

React Project에 firebase SDK setup하기

코드에 노출되면 안되는 중요한 키값들

.env 예)

REACT_APP_FIREBASE_APIKEY=keyvalue

service/firebase.js

import { initializeApp } from "firebase/app";

const firebaseConfig = {
  apiKey: process.env.REACT_APP_FIREBASE_APIKEY,
  authDomain: process.env.REACT_APP_FIREBASE_AUTHDOMAIN,
  databaseURL: process.env.REACT_APP_FIREBASE_DATABASEURL,
  projectId: process.env.REACT_APP_FIREBASE_PROJECTID,
};

const firebaseApp = initializeApp(firebaseConfig);

export default firebaseApp;

login, logout 설정 (Google, Github Sign-In)

로그인, 로그아웃 등 authentication에 관련된 일을 하는 클래스

service/auth_service.js

import {
  getAuth,
  signInWithPopup,
  GoogleAuthProvider,
  GithubAuthProvider,
} from "firebase/auth";

class AuthService {
  constructor() {
    this.auth = getAuth();
    this.GoogleProvider = new GoogleAuthProvider();
    this.GithubProvider = new GithubAuthProvider();
  }
  login(provider) {
    signInWithPopup(this.auth, this[`${provider}Provider`]);
  }
  logout() {
    this.auth.signOut();
  }
  // 나중에 session 관련 코드 분리하여 사용 
  onAuthStateChanged(onChangedUser) {
    this.auth.onAuthStateChanged((user) => {
      onChangedUser(user);
    });
  }
}

export default AuthService;

firebase config 와 연결 후 dependency injection

index.js

import firebaseApp from "./service/firebase.js";
import AuthService from "./service/auth_service.js";

// firebase config 와 연결 
const authService = new AuthService(firebaseApp);

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
        // dependency injection 
        <App authService={authService} />
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById("root")
);

login , logout 함수

App.jsx

function App({ authService }) {
  const onLogin = (event) => {
    authService.login(event.target.innerText);
  };

  const onLogout = useCallback(() => {
    authService.logout();
    navigate("/");
  }, [authService]);

관련 링크 :

관련 링크 :

👍
https://create-react-app.dev/docs/adding-custom-environment-variables/
https://firebase.google.com/docs/auth/web/google-signin?authuser=0