Vue3, Firebase 프로젝트 - 채팅앱 VSignal

15. Vue 3 + Firebase Auth 예제

그랜파 개발자 2025. 4. 23. 03:12

Vue 3 + Firebase Auth 예제

좋아요! 아래에 Vue 3 + Firebase Authentication (이메일/비밀번호 회원가입 및 로그인) 기능을 갖춘 간단한 예제를 만들어드릴게요.

✅ 목표 기능

  • 이메일/비밀번호 회원가입
  • 로그인
  • 로그아웃
  • 현재 로그인된 유저 표시

🛠️ 기본 프로젝트 설정

Vite로 Vue 3 프로젝트 생성

npm create vite@latest my-app -- --template vue
cd my-app
npm install

Firebase 설치

npm install firebase

📁 폴더 구조

src/
├── firebase.js         🔸 Firebase 설정
├── main.js
├── App.vue
└── views/
    └── Auth.vue        🔸 로그인 & 회원가입 뷰

1. 🔥 firebase.js

// src/firebase.js
import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';

const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
  projectId: "YOUR_PROJECT_ID",
  // ... 생략 가능
};

const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);

2. 🧠 main.js

// src/main.js
import { createApp } from 'vue';
import App from './App.vue';

createApp(App).mount('#app');

3. 📦 App.vue

<!-- src/App.vue -->
<template>
  <div>
    <Auth />
  </div>
</template>

<script setup>
import Auth from './views/Auth.vue';
</script>

4. 👤 views/Auth.vue

<!-- src/views/Auth.vue -->
<template>
  <div class="auth">
    <h2>Firebase Auth (Vue 3)</h2>

    <div v-if="!user">
      <input v-model="email" type="email" placeholder="이메일" />
      <input v-model="password" type="password" placeholder="비밀번호" />

      <button @click="signUp">회원가입</button>
      <button @click="logIn">로그인</button>
    </div>

    <div v-else>
      <p>👋 {{ user.email }} 님 환영합니다!</p>
      <button @click="logOut">로그아웃</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { auth } from '../firebase';
import {
  createUserWithEmailAndPassword,
  signInWithEmailAndPassword,
  signOut,
  onAuthStateChanged
} from 'firebase/auth';

const email = ref('');
const password = ref('');
const user = ref(null);

// 로그인 상태 추적
onMounted(() => {
  onAuthStateChanged(auth, (currentUser) => {
    user.value = currentUser;
  });
});

const signUp = async () => {
  try {
    const userCredential = await createUserWithEmailAndPassword(auth, email.value, password.value);
    user.value = userCredential.user;
    alert("회원가입 성공!");
  } catch (error) {
    alert("회원가입 실패: " + error.message);
  }
};

const logIn = async () => {
  try {
    const userCredential = await signInWithEmailAndPassword(auth, email.value, password.value);
    user.value = userCredential.user;
    alert("로그인 성공!");
  } catch (error) {
    alert("로그인 실패: " + error.message);
  }
};

const logOut = async () => {
  await signOut(auth);
  user.value = null;
};
</script>

<style scoped>
.auth {
  max-width: 300px;
  margin: 50px auto;
  display: flex;
  flex-direction: column;
  gap: 10px;
}
input {
  padding: 8px;
  font-size: 1em;
}
button {
  padding: 8px;
}
</style>

🎉 이제 실행해보세요!

npm run dev

 

이제 회원가입, 로그인, 로그아웃, 그리고 현재 로그인된 유저 확인까지 가능해요!

➕ 다음 단계 아이디어

  • 비밀번호 재설정
  • 이메일 인증 보내기
  • 소셜 로그인 (Google, Kakao 등)
  • Vue Router 연동 (로그인 여부에 따른 페이지 접근 제한)
  • Pinia를 통한 전역 사용자 상태 관리