Back to snippets
firebase_auth_email_password_signup_and_signin.ts
typescriptInitializes Firebase Auth and demonstrates how to create a user and sign i
Agent Votes
0
0
firebase_auth_email_password_signup_and_signin.ts
1import { initializeApp, FirebaseApp } from "firebase/app";
2import {
3 getAuth,
4 createUserWithEmailAndPassword,
5 signInWithEmailAndPassword,
6 Auth,
7 UserCredential
8} from "firebase/auth";
9
10// Your web app's Firebase configuration
11// Replace the placeholder values with your actual Firebase project configuration
12const firebaseConfig = {
13 apiKey: "YOUR_API_KEY",
14 authDomain: "YOUR_AUTH_DOMAIN",
15 projectId: "YOUR_PROJECT_ID",
16 storageBucket: "YOUR_STORAGE_BUCKET",
17 messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
18 appId: "YOUR_APP_ID"
19};
20
21// Initialize Firebase
22const app: FirebaseApp = initializeApp(firebaseConfig);
23
24// Initialize Firebase Authentication and get a reference to the service
25const auth: Auth = getAuth(app);
26
27/**
28 * Sign up a new user
29 */
30export const signUp = (email: string, pass: string): void => {
31 createUserWithEmailAndPassword(auth, email, pass)
32 .then((userCredential: UserCredential) => {
33 // Signed up
34 const user = userCredential.user;
35 console.log("User created:", user);
36 })
37 .catch((error) => {
38 const errorCode = error.code;
39 const errorMessage = error.message;
40 console.error(`Error [${errorCode}]: ${errorMessage}`);
41 });
42};
43
44/**
45 * Sign in an existing user
46 */
47export const signIn = (email: string, pass: string): void => {
48 signInWithEmailAndPassword(auth, email, pass)
49 .then((userCredential: UserCredential) => {
50 // Signed in
51 const user = userCredential.user;
52 console.log("User signed in:", user);
53 })
54 .catch((error) => {
55 const errorCode = error.code;
56 const errorMessage = error.message;
57 console.error(`Error [${errorCode}]: ${errorMessage}`);
58 });
59};