Skip to content

Instantly share code, notes, and snippets.

@gragland
Last active March 5, 2024 20:05
Show Gist options
  • Save gragland/4ccd86d4685db33b2c422af0159774a4 to your computer and use it in GitHub Desktop.
Save gragland/4ccd86d4685db33b2c422af0159774a4 to your computer and use it in GitHub Desktop.
How to lazy load Firebase with dynamic imports
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} />
);
}
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;
@SoldierCorp
Copy link

That did the trick, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment