What you'll build
A complete authentication system where your users sign in with their Google account in a single click. You'll implement a custom useAuth hook that handles all authentication state, a login/logout button, route protection for private content, and session persistence. When finished, you'll have a solid authentication foundation that you can reuse in any React or Next.js project.
Firebase Setup
- Go to console.firebase.google.com
- Create project
- Authentication โ Sign-in method โ Google โ Enable
- Copy config
Step 1: Ask an AI for the integration
I need to integrate Firebase Auth with Google in React:
- Custom useAuth hook
- Login/logout button
- Show user info
- Protect routes
- TypeScript
Firebase config: (paste your config)
Give me the complete code.
Typical code
// lib/firebase.ts
import { initializeApp } from 'firebase/app'
import { getAuth, GoogleAuthProvider } from 'firebase/auth'
const app = initializeApp({ /* your config */ })
export const auth = getAuth(app)
export const googleProvider = new GoogleAuthProvider()
// hooks/useAuth.ts
import { signInWithPopup, signOut, onAuthStateChanged } from 'firebase/auth'
export function useAuth() {
const [user, setUser] = useState(null)
useEffect(() => {
return onAuthStateChanged(auth, setUser)
}, [])
const login = () => signInWithPopup(auth, googleProvider)
const logout = () => signOut(auth)
return { user, login, logout }
}
Protect routes
function ProtectedPage() {
const { user, login } = useAuth()
if (!user) {
return <button onClick={login}>Login with Google</button>
}
return <div>Welcome, {user.displayName}</div>
}