The easiest way to add authentication to your web app is through Firebase authentication.
Before continuing with adding authentication, make sure to add firebase to your project. And I am using Context API as we need authentication on every page of the web app.
The blog doesn't show how to setup context. You can see my other blog on ContextAPI using NextJS and TypeScript
Enough of talking, Let's get started.
1. Install firebase
npm install firebase
2. Firebase setup
import { initializeApp, getApps } from "firebase/app";
import { getAuth } from "firebase/auth";
const firebaseConfig = {
apiKey: "apiKey",
authDomain: "authDomain",
projectId: "projectID",
storageBucket: "storageBucket",
messagingSenderId: "messagingSenderID",
appId: "appID",
measurementId: "measurementID",
};
if (!getApps().length) {
initializeApp(firebaseConfig);
}
export const auth = getAuth();
export default firebaseConfig;
here we are initializing the firebase app then exporting the getAuth function as auth.
3. Setting up auth functionality
//Inside the AuthContext file.
import { GoogleAuthProvider, signInWithPopup } from "firebase/auth";
import { auth } from "../firebase";
// Inside AuthProvider
const provider = new GoogleAuthProvider();
const login = () => {
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;
// The signed-in user info.
const user = result.user;
console.log({ credential, token, user });
})
.catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.email;
// The AuthCredential type that was used.
const credential = GoogleAuthProvider.credentialFromError(error);
console.log({ errorCode, errorMessage, email, credential });
});
};
const logout = () => {
auth.signOut();
console.log("logout");
};
Now as login and logout functions are ready, It's time to use them.
4. Implementing login and logout functionality
// Import useAuth from context
import { useAuth } from "../context/AuthContext";
// Destructure login and logout functions.
const { login, logout } = useAuth();
...
return (
<div>
<button onClick={login}> Login </button>
<button onClick={logout}> Logout </button>
</div>
);
Login and Logout functions are not enough, we also need to listen if the used is login or not, on their next visit.
5. Listening to the auth state.
// Inside Context.
import { useEffect } from "react";
import { onAuthStateChanged } from "firebase/auth";
useEffect(() => {
onAuthStateChanged(auth, (user) => {
if (user) {
const uid = user.uid;
console.log({ uid });
} else {
console.log("no user");
}
});
}, []);
Thanks for reading, I have used ContextAPI here, you can read my blog on ContextAPI with NextJS and TypeScript
Closing here 👋👋👋
This is Shareef.
My recent project yourounotes
My Portfolio
Twitter ShareefBhai99
My other Blogs
Top comments (7)
Not worth reading, as its an incomplete blog without proper referencing!
Yeah! I got the point. I have not covered context API in this blog, that's why it is causing misunderstanding.
Thanks for the comment 👍 😀
In step 4, where do you define "// Import useAuth from context
import { useAuth } from "../context/AuthContext";"? There is not useAuth.
useAuth coming from context, which I haven't explained in this blog, and I have mentioned to ones ready the context blog...
And the code we are writing in step 3 is inside context and we export it as useAuuth
If you still have doubt tell me... I will explain in detail.
If the tutorial needs some previously done components, you at least need us to know the code to paste, if you don't want to share it here. Otherwice it's useless. Let this page be independent from the previous blog post.
Thanks, I have updated the blog and mentioned that this blog doesn't show how to setup context API but you read my other blog on context API using Next.js and Typescript
I need help understanding this. it seems you are omitting the Auth context part which is critical to understanding how all of this works