DEV Community

Cover image for Firebase: The google API for building Apps
Sean
Sean

Posted on

8 1

Firebase: The google API for building Apps

Firebase is tool used for the backend and database of any app or website you might create. It's a template for your app, that can be configured to your specific needs while delivering the basics. It's made owned by google which makes it even more accessible. I use google for pretty much everything. Emails, writing, and countless other things. I actually didn't know that something like Firebase existed a year ago. I mean who's gonna give up a service like this for free-ish. Anyway lets get right into it.

Firebase offers Authentication

This is literally the bread and butter of any application. Users need to be identified and have a secure way of doing so. Firebase authentication consists of google auth, facebook auth, email only auth, github auth, email and password auth, and a few others. Users can safely change passwords, confirm their email, and even change the email they are using. Here's the link to the docs for auth.

Firebase offers 2 different Databases and storage

Firebase is flexible, like really flexible. There are 2 different databases available: the real-time database, and the firestore. Both are great but personally I recommend the firestore. Storage is just for storing things that you cant keep in either database in your google cloud bucket.

  1. Storage: https://firebase.google.com/docs/storage
  2. Firestore: https://firebase.google.com/docs/firestore
  3. Real-time Database: https://firebase.google.com/docs/database

Firebase offers cloud functions

Because of the nature of firebase you don't have direct access to a server, but cloud functions solve that problem. You can export your functions to be called using triggers. So any server side code can be run no stress. Here's the link to the docs
P.S you need to be on a paid plan to use Firebase cloud functions.

Now that all that's been said here's a quick example of how you might implement firebase into a react app.

import { useEffect, useState } from "react";
import firebase from "firebase/app";
import "firebase/auth";
import "firebase/firestore";
const config = {/*firebase project config*/};
try {
firebase.initializeApp(config);
} catch (error) {
!/already exists/.test(error.message) && console.error(error);
}
function App() {
const [show, setShow] = useState(false);
const [messages, setMessages] = useState([]);
useAuth(setShow);
useFirestore(setMessages);
return (
<div>
<h2>
{
show
? "You're signed in yay!"
: "You're not signed in. Please sign in."
}
</h2>
{
show
? <>
<Messages addMessage={addMessage} messages={messages} />
<br />
<button onClick={logout}>Log Out</button>
</>
: <button onClick={login}>Log In</button>
}
</div>
);
}
function Messages({ messages, addMessage }) {
const [value, setValue] = useState("");
return (
<div>
<p>
{
messages.map((message, index) => <span key={index}>{message}<br /></span>)
}
</p>
<br />
<form onSubmit={(e) => {
e.preventDefault();
addMessage(value);
setValue("");
}}>
<input value={value} onChange={(e) => setValue(e.target.value)} />
<br />
<button>Send</button>
</form>
</div>
);
}
function useFirestore(setMessages) {
const db = firebase.firestore();
const auth = firebase.auth();
return useEffect(() => {
const unsubscribe = auth.currentUser && db.collection("userMessages").doc(auth.currentUser?.uid).onSnapshot((doc) => {
doc.exists && setMessages([...doc.data().messages]);
});
return () => typeof(unsubscribe) === "function" && unsubscribe();
//eslint-disable-next-line
}, [auth.currentUser]);
}
async function login() {
const provider = new firebase.auth.GoogleAuthProvider();
const auth = firebase.auth();
await auth.signInWithPopup(provider);
}
async function logout() {
const auth = firebase.auth();
await auth.signOut();
}
function useAuth(setShow) {
const auth = firebase.auth();
return useEffect(() => {
auth.onAuthStateChanged((user) => {
user?.uid ? setShow(true) : setShow(false);
});
//eslint-disable-next-line
}, []);
}
async function addMessage(message) {
const auth = firebase.auth();
const db = firebase.firestore();
await db.collection("userMessages").doc(auth.currentUser.uid).set({
messages: firebase.firestore.FieldValue.arrayUnion(message)
},{
merge: true
});
};
export default App;

Here's a link to the code in action.

Happy Hacking!

Cat Coder Photo

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (2)

Collapse
 
frondor profile image
Federico Vázquez

Please, refactor that code and use custom hooks for the auth, the storage and the messages system. You'll see the code gets way more readable

Collapse
 
seanolad profile image
Sean

Sure I'll update it, thanks for the feed back tho. 😄

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay