React で Firebase の Google Auth

● React で Firebase の Google Auth

.env.local


REACT_APP_FIREBASE_API_KEY="XXXXXXXXXXXXXXXXX"
REACT_APP_FIREBASE_AUTH_DOMAIN="XXXXXXXXXXXXXXXXX"
REACT_APP_FIREBASE_PROJECT_ID="XXXXXXXXXXXXXXXXX"
REACT_APP_FIREBASE_STORAGE_BUCKET="XXXXXXXXXXXXXXXXX"
REACT_APP_FIREBASE_MESSAGE_SENDER_ID="XXXXXXXXXXXXXXXXX"
REACT_APP_FIREBASE_APP_ID="XXXXXXXXXXXXXXXXX"
REACT_APP_FIREBASE_MEASUREMENT_ID="XXXXXXXXXXXXXXXXX"

src/FirebaseApp.tsx

import { initializeApp } from "firebase/app";
import { getAuth, GoogleAuthProvider } from "firebase/auth";

const firebaseConfig = {
  apiKey              : process.env.REACT_APP_FIREBASE_API_KEY,
  authDomain          : process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
  projectId           : process.env.REACT_APP_FIREBASE_PROJECT_ID,
  storageBucket       : process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
  messagingSenderId   : process.env.REACT_APP_FIREBASE_MESSAGE_SENDER_ID,
  appId               : process.env.REACT_APP_FIREBASE_SENDER_ID,
};

initializeApp(firebaseConfig);

export const auth = getAuth();
export const provider = new GoogleAuthProvider();

src/App.tsx

import { auth, provider } from './FirebaseApp';
import { signInWithPopup, GoogleAuthProvider } from "firebase/auth";


function App() {

  const doLoginWithGoogle = () => {
    signInWithPopup(auth, provider)
      .then((result) => {
        // This gives you a Google Access Token. You can use it to access the Google API.
        const credential = GoogleAuthProvider.credentialFromResult(result);
        const token = credential?.accessToken;
        const user = result.user;

        console.log('● token');
        console.log(token);
        console.log('● user');
        console.log(user);
      }).catch((error) => {
        console.log('● error');
        console.log(error);
      });
  }

  return (
    <div>
      <h1>Googleログイン</h1>
      <button onClick={doLoginWithGoogle}>googleでログインする</button>
      {/* <button onClick={doLoginWithGoogle}>googleでログインする</button> */}
    </div>
  )

}

export default App;
No.2133
01/08 21:57

edit