npx create-next-app
(アプリ名を聞かれるので 「my-first-next-app」 のように入力します。)
cd my-first-next-app
npm install
npm run dev
http://localhost:3000/ へ アクセスできることを確認します
Firebaseのインストール
yarn add firebase @types/firebase
https://console.firebase.google.com/u/0/
へアクセスして「+プロジェクトの追加」をクリックします
(プロジェクト名を聞かれるので「my-first-next-app-firebase」 のように入力します。)
「続行」をクリックしてプロジェクトを作成します。
「ウェブ」アイコンをクリックして「ウェブアプリへの Firebase の追加」画面へ移動します。
(ニックネームを聞かれるので「my-first-next-app-apelido」 のように入力します。)
登録が完了すると firebaseConfig が表示されるのでコピーしておきます。
const firebaseConfig = {
apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
projectId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
storageBucket: "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
messagingSenderId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
appId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
};
コピーした後コンソールに進みます
一番左のメニューの「Authentication」をクリックし「始める」をクリックします。
ログインプロバイダーにGoogleを追加して有効化します。
「Authentication」 →「Users」からログインテスト用アカウントを作成しておきます
npm install 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
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>
)
}
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 Authentication これだけは覚えておけ!テストに出るぞ! - Qiita
firebase.auth().currentUser
firebase v9
await currentUser();
に現在ログイン中のユーザ情報が帰ってきますのでそこを調べます。
ブラウザのIndexedDB