フロントエンド開発といえば。
react アプリの初期化( npm init vite@latest <アプリ名> )

Next.js + Firebase で Googleログインのテスト

● Next.js + Firebase で Googleログインのテスト


● Next.js アプリの初期化と実行

1-1. アプリの初期化

npx create-next-app

(アプリ名を聞かれるので 「my-first-next-app」 のように入力します。)

1-2. アプリの実行

cd my-first-next-app
npm install
npm run dev

http://localhost:3000/ へ アクセスできることを確認します


● Firebaseの設定

Firebaseのインストール

yarn add firebase @types/firebase

2-1. Firebaseの新規登録

https://console.firebase.google.com/u/0/
へアクセスして「+プロジェクトの追加」をクリックします

(プロジェクト名を聞かれるので「my-first-next-app-firebase」 のように入力します。)

「続行」をクリックしてプロジェクトを作成します。

2-2. 新規登録したFirebaseのプロジェクトの設定

「ウェブ」アイコンをクリックして「ウェブアプリへの Firebase の追加」画面へ移動します。

(ニックネームを聞かれるので「my-first-next-app-apelido」 のように入力します。)

登録が完了すると firebaseConfig が表示されるのでコピーしておきます。

const firebaseConfig = {
  apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  authDomain: "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  projectId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  storageBucket: "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  messagingSenderId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  appId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
};

コピーした後コンソールに進みます

2-3. FirebaseでGoogle認証を有効にする

一番左のメニューの「Authentication」をクリックし「始める」をクリックします。

ログインプロバイダーにGoogleを追加して有効化します。

2-4. ログインテスト用アカウントを作成しておく

「Authentication」 →「Users」からログインテスト用アカウントを作成しておきます


● Next.js アプリへFirebaseの追加

3-1. Firebaseの新規登録

npm install firebase

3-2. Firebaseアプリ初期化コンポーネントの作成

FirebaseApp.js

import { initializeApp } from "firebase/app";

const firebaseConfig = {
  apiKey              : "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
  authDomain          : "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
  projectId           : "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
  storageBucket       : "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
  messagingSenderId   : "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
  appId               : "xxxxxxxxxxxxxxxxxxxxxxxxxxx"
};

const FirebaseApp = initializeApp(firebaseConfig);

export default FirebaseApp

3-3. Firebaseログインサンプル画面の作成

pages/login.js

import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'
import FirebaseApp from '../FirebaseApp';
import { getAuth, signInWithEmailAndPassword } from "firebase/auth";

export default function Home() {

  const doLogin = () => {
    const auth = getAuth();

    // Firebaseに登録したID,PASSWORD
    const email = 'test@user.com';
    const password = 'XXXXXXXXXX';

    signInWithEmailAndPassword(auth, email, password)
      .then((userCredential) => {
        const user = userCredential.user;
        alert( 'ログインok!' );
        console.log( '● user' );
        console.log( user );
      })
      .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
      });
  }

  return (
    <div className={styles.container}>
      <h1>Googleログイン</h1>
      <button onClick={doLogin}>googleでログインする</button>
    </div>
  )
}

3-4. Firebaseログインの実行

http://localhost:3000/login
にアクセスしてログインボタンをクリックすると「ログインok!」のアラートが表示されます。

● ログイン状態の永続性

import {
  getAuth,
  setPersistence,
  browserLocalPersistence,
  browserSessionPersistence,
  inMemoryPersistence
} from "firebase/auth";

const auth = getAuth()

await setPersistence(auth, browserLocalPersistence);

以下の4パターンが存在します

browserLocalPersistence (LOCAL)
browserSessionPersistence (SESSION)
indexedDBLocalPersistence (LOCAL)
inMemoryPersistence (NONE)

認証状態の永続性  |  Firebase

● 現在ログイン中かどうかを調べる

firebase.auth().currentUser

firebase v9

export async function currentUser() {
  if (firebaseAuth.currentUser) return firebaseAuth.currentUser

  return new Promise<User | null>((resolve) => {
    firebaseAuth.onAuthStateChanged((user) => {
      if (user) return resolve(user)
      else return resolve(null)
    })
  })
}
await currentUser();

に現在ログイン中のユーザ情報が帰ってきますのでそこを調べます。

● そもそも Firebase Auth の情報の保存先

ブラウザのIndexedDB
No.2052
01/30 08:59

edit