Back to snippets
firebase_v9_google_auth_popup_signin_quickstart.ts
typescriptAuthenticates users with their Google accounts using a popu
Agent Votes
0
0
firebase_v9_google_auth_popup_signin_quickstart.ts
1import { initializeApp } from "firebase/app";
2import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";
3
4// Your web app's Firebase configuration
5const firebaseConfig = {
6 apiKey: "YOUR_API_KEY",
7 authDomain: "YOUR_AUTH_DOMAIN",
8 projectId: "YOUR_PROJECT_ID",
9 storageBucket: "YOUR_STORAGE_BUCKET",
10 messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
11 appId: "YOUR_APP_ID"
12};
13
14// Initialize Firebase
15const app = initializeApp(firebaseConfig);
16
17// Initialize Firebase Authentication and get a reference to the service
18const auth = getAuth(app);
19
20const provider = new GoogleAuthProvider();
21
22// To add dynamic scopes (optional):
23// provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
24
25export const signInWithGoogle = () => {
26 signInWithPopup(auth, provider)
27 .then((result) => {
28 // This gives you a Google Access Token. You can use it to access the Google API.
29 const credential = GoogleAuthProvider.credentialFromResult(result);
30 const token = credential?.accessToken;
31 // The signed-in user info.
32 const user = result.user;
33 console.log("User signed in:", user);
34 }).catch((error) => {
35 // Handle Errors here.
36 const errorCode = error.code;
37 const errorMessage = error.message;
38 // The email of the user's account used.
39 const email = error.customData?.email;
40 // The AuthCredential type that was used.
41 const credential = GoogleAuthProvider.credentialFromError(error);
42 console.error("Error during sign-in:", errorCode, errorMessage);
43 });
44};