Last active
March 5, 2024 20:05
-
-
Save gragland/4ccd86d4685db33b2c422af0159774a4 to your computer and use it in GitHub Desktop.
How to lazy load Firebase with dynamic imports
This file contains 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
import getFirebase from "./firebase.js"; | |
function MyApp() { | |
// Example function that wraps some firebase logic | |
const onSignup = async (email, password) => { | |
// Use await to ensure firebase library is loaded | |
const firebase = await getFirebase(); | |
// Call firebase methods as you normally would | |
const { user } = await firebase.auth() | |
.createUserWithEmailAndPassword(email, password); | |
// Do something with `user` | |
router.push(`/user/${user.uid}`); | |
} | |
return ( | |
<Signup onSubmit={onSignup} /> | |
); | |
} |
This file contains 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
const getFirebase = async () => { | |
// Lazy load Firebase core (must come first) | |
const { default: firebase } = await import("firebase/app"); | |
// Lazy load Firebase services you need | |
await Promise.all([ | |
import("firebase/firestore"), | |
import("firebase/auth"), | |
]); | |
// Make sure not already initialized | |
if (!firebase.apps.length) { | |
firebase.initializeApp(config); | |
} | |
return firebase; | |
}; | |
export default getFirebase; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That did the trick, thanks!