Skip to content

Instantly share code, notes, and snippets.

@odashi
Created December 9, 2023 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odashi/3c83b05b2ef1b23c37f06fe7e2a435ff to your computer and use it in GitHub Desktop.
Save odashi/3c83b05b2ef1b23c37f06fe7e2a435ff to your computer and use it in GitHub Desktop.
Firebase Authentication provider with next.js
"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