An Interest In:
Web News this Week
- March 28, 2024
- March 27, 2024
- March 26, 2024
- March 25, 2024
- March 24, 2024
- March 23, 2024
- March 22, 2024
October 22, 2021 12:44 am GMT
Original Link: https://dev.to/gthinh/how-to-initialize-a-firebase-app-in-the-new-modular-web-sdk-in-nextjs-187i
How to Initialize a Firebase app in the new modular Web SDK in Next.js
Previously in Version 8
Most devs migrating to the new modular approach for delivering the firebase API typically have this code snippet that initializes their firebase app.
We'll start off by exporting the most basic service, being firebase/auth
.
//initFirebase.tsrequire("firebase/auth");import firebase from "firebase/app";const config = { // ...various env variables};export default function initializeFirebase() { if (firebase.apps.length === 0) { return firebase.initializeApp(config); }}export const firebaseAuth = firebase.auth;
Now in V9
In the latest version, we can re-factor the snippet into something like this:
// initFirebase.tsimport { FirebaseOptions, getApp, initializeApp } from "firebase/app";import { getAuth } from "firebase/auth";const config: FirebaseOptions = { // ...various env variables};function createFirebaseApp(config: FirebaseOptions) { try { return getApp(); } catch { return initializeApp(config); }}const firebaseApp = createFirebaseApp(firebaseConfig);export const firebaseAuth = getAuth(firebaseApp);
Bonus: Initialize the latest Admin SDK version 10 for API routes
Similarly for the admin SDK, we create a similar function, but we also handle a check against the number of apps being initialized.
// initFirebaseAdmin.tsimport { AppOptions, cert, getApp, getApps, initializeApp, ServiceAccount,} from "firebase-admin/app";import { getAuth } from "firebase-admin/auth";const credentials: ServiceAccount = { projectId: process.env.projectID, privateKey: process.env.privateKey.replace(/\\n/g, "
"), clientEmail: process.env.clientEmail,};const options: AppOptions = { credential: cert(credentials), databaseURL: process.env.databaseURL,};function createFirebaseAdminApp(config: AppOptions) { if (getApps().length === 0) { return initializeApp(config); } else { return getApp(); }}const firebaseAdmin = createFirebaseAdminApp(options);export const adminAuth = getAuth(firebaseAdmin);
Now we can make use of adminAuth
in any API route handler to manage authenticated users.
And that's really it!
Original Link: https://dev.to/gthinh/how-to-initialize-a-firebase-app-in-the-new-modular-web-sdk-in-nextjs-187i
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To