In a Next.js app using Firebase client SDK, what is the best way to initialize Firebase to avoid multiple instances during hot reloads?
import { initializeApp, getApps } from 'firebase/app'; const firebaseConfig = { /* config */ }; const app = !getApps().length ? initializeApp(firebaseConfig) : getApps()[0]; export default app;
Think about how Next.js hot reloads can cause multiple initializations.
Next.js hot reloads can cause the Firebase app to initialize multiple times if not checked. Using getApps() to check existing instances prevents this.
In a Next.js app, where is the correct place to use Firebase Admin SDK for secure server-side operations?
Consider security and environment where Admin SDK can safely run.
Firebase Admin SDK requires server-side environment and should only be used in API routes or server-side functions to keep credentials secure.
Given Firebase API keys are public by design, how should you protect sensitive Firebase operations in Next.js?
Think about what Firebase API keys protect and how Firebase security rules work.
Firebase API keys are not secret. Sensitive operations should be done server-side with Admin SDK. Client SDK uses API keys but security is enforced by Firebase rules.
Consider calling Firebase client SDK methods inside getStaticProps in Next.js. What is the expected behavior?
import { initializeApp } from 'firebase/app'; import { getFirestore, collection, getDocs } from 'firebase/firestore'; const firebaseConfig = { /* config */ }; export async function getStaticProps() { const app = initializeApp(firebaseConfig); const db = getFirestore(app); const snapshot = await getDocs(collection(db, 'posts')); return { props: { posts: snapshot.docs.map(doc => doc.data()) } }; }
Think about environment differences between client SDK and server-side functions.
Firebase client SDK relies on browser APIs like IndexedDB and window, which are not available during Next.js build time, causing errors.
You want to verify Firebase ID tokens sent from the client in Next.js API routes. Which approach is correct?
import { getAuth } from 'firebase-admin/auth'; export default async function handler(req, res) { const idToken = req.headers.authorization?.split('Bearer ')[1]; try { const decodedToken = await getAuth().verifyIdToken(idToken); res.status(200).json({ uid: decodedToken.uid }); } catch (error) { res.status(401).json({ error: 'Unauthorized' }); } }
Consider where token verification should happen for secure backend validation.
Firebase ID tokens must be verified on the server using Admin SDK to ensure requests are authenticated and authorized.