Created
December 9, 2023 14:48
-
-
Save odashi/3c83b05b2ef1b23c37f06fe7e2a435ff to your computer and use it in GitHub Desktop.
Firebase Authentication provider with next.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use client"; | |
import { getApp, getApps, initializeApp } from "firebase/app"; | |
import { | |
getAuth, | |
GoogleAuthProvider, | |
signInWithPopup, | |
User, | |
} from "firebase/auth"; | |
import { | |
ReactNode, | |
createContext, | |
useContext, | |
useEffect, | |
useState, | |
} from "react"; | |
if (!getApps().length) { | |
initializeApp({ | |
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY, | |
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN, | |
}); | |
} | |
const app = getApp(); | |
const auth = getAuth(app); | |
export async function signIn() { | |
await signInWithPopup(auth, new GoogleAuthProvider()); | |
} | |
export async function signOut() { | |
await auth.signOut(); | |
} | |
const UserContext = createContext<User | null>(null); | |
export function useUserContext() { | |
return useContext(UserContext); | |
} | |
export function UserProvider({ children }: { children: ReactNode }) { | |
const [user, setUser] = useState<User | null>(null); | |
// Unsubscribe when unmount | |
useEffect(() => auth.onAuthStateChanged(setUser), []); | |
return <UserContext.Provider value={user}>{children}</UserContext.Provider>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment