Bird
Raised Fist0
Firebasecloud~20 mins

Firebase with Next.js - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Firebase with Next.js Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ service_behavior
intermediate
2:00remaining
How does Next.js handle Firebase client SDK initialization?

In a Next.js app using Firebase client SDK, what is the best way to initialize Firebase to avoid multiple instances during hot reloads?

Firebase
import { initializeApp, getApps } from 'firebase/app';

const firebaseConfig = { /* config */ };

const app = !getApps().length ? initializeApp(firebaseConfig) : getApps()[0];

export default app;
AInitialize Firebase only on the server side and never on the client.
BInitialize Firebase inside a React component directly without checking existing apps.
CInitialize Firebase once globally and reuse the instance by checking if apps exist.
DInitialize Firebase multiple times in different files without sharing the instance.
Attempts:
2 left
💡 Hint

Think about how Next.js hot reloads can cause multiple initializations.

❓ Architecture
intermediate
2:00remaining
Where should Firebase Admin SDK be used in a Next.js app?

In a Next.js app, where is the correct place to use Firebase Admin SDK for secure server-side operations?

AIn static files served to the client.
BInside API routes or server-side functions only.
CDirectly in the browser JavaScript code.
DInside React components rendered on the client side.
Attempts:
2 left
💡 Hint

Consider security and environment where Admin SDK can safely run.

❓ Configuration
advanced
2:00remaining
What is the correct way to protect Firebase API keys in a Next.js app?

Given Firebase API keys are public by design, how should you protect sensitive Firebase operations in Next.js?

AUse Firebase client SDK on the client and restrict sensitive operations to server-side API routes with Admin SDK.
BStore API keys in environment variables and never expose them to the client.
CHardcode API keys in client-side code but obfuscate them with base64 encoding.
DUse Firebase API keys only in serverless functions and never initialize Firebase on the client.
Attempts:
2 left
💡 Hint

Think about what Firebase API keys protect and how Firebase security rules work.

🧠 Conceptual
advanced
2:00remaining
What happens if you call Firebase client SDK inside getStaticProps in Next.js?

Consider calling Firebase client SDK methods inside getStaticProps in Next.js. What is the expected behavior?

Firebase
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()) } };
}
AIt causes runtime errors because client SDK depends on browser APIs not available at build time.
BIt fetches data but with slower performance than Admin SDK.
CIt works fine because getStaticProps runs on the server at build time.
DIt fetches data but exposes Firebase credentials to the client.
Attempts:
2 left
💡 Hint

Think about environment differences between client SDK and server-side functions.

❓ security
expert
3:00remaining
How to securely implement Firebase Authentication with Next.js API routes?

You want to verify Firebase ID tokens sent from the client in Next.js API routes. Which approach is correct?

Firebase
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' });
  }
}
ASkip token verification and rely on Firebase security rules only.
BVerify ID tokens on the client side only and trust client validation.
CSend ID tokens to third-party services for verification outside Next.js.
DVerify ID tokens in API routes using Firebase Admin SDK's verifyIdToken method.
Attempts:
2 left
💡 Hint

Consider where token verification should happen for secure backend validation.

Practice

(1/5)
1. What is the main purpose of integrating Firebase with a Next.js application?
easy
A. To add backend features like database and user authentication easily
B. To replace Next.js routing with Firebase functions
C. To convert Next.js into a mobile app framework
D. To remove the need for React components in Next.js

Solution

  1. Step 1: Understand Firebase role

    Firebase provides backend services such as database and authentication that can be added to frontend apps.
  2. Step 2: Understand Next.js role

    Next.js is a frontend framework for React apps, which can use Firebase to add backend features.
  3. Final Answer:

    To add backend features like database and user authentication easily -> Option A
  4. Quick Check:

    Firebase adds backend features to Next.js apps = C [OK]
Hint: Firebase adds backend features to frontend apps [OK]
Common Mistakes:
  • Thinking Firebase replaces Next.js routing
  • Confusing Firebase with mobile app frameworks
  • Assuming Firebase removes React components
2. Which of the following is the correct way to initialize Firebase in a Next.js project?
easy
A. import { initializeApp } from 'firebase/app'; const app = initializeApp(firebaseConfig);
B. const app = new Firebase(firebaseConfig);
C. firebase.initialize(firebaseConfig);
D. import firebase from 'firebase'; firebase.init(firebaseConfig);

Solution

  1. Step 1: Check Firebase v9+ syntax

    Firebase modular SDK uses 'initializeApp' imported from 'firebase/app'.
  2. Step 2: Verify correct usage

    import { initializeApp } from 'firebase/app'; const app = initializeApp(firebaseConfig); correctly imports and calls initializeApp with config.
  3. Final Answer:

    import { initializeApp } from 'firebase/app'; const app = initializeApp(firebaseConfig); -> Option A
  4. Quick Check:

    Use initializeApp from 'firebase/app' = B [OK]
Hint: Use modular import and initializeApp for Firebase v9+ [OK]
Common Mistakes:
  • Using old Firebase namespace syntax
  • Calling non-existent methods like firebase.init
  • Creating Firebase instance with 'new' keyword
3. Given this Next.js Firebase code snippet, what will be logged if the user is not signed in?
import { getAuth, onAuthStateChanged } from 'firebase/auth';
const auth = getAuth();
onAuthStateChanged(auth, user => {
  if (user) {
    console.log('User ID:', user.uid);
  } else {
    console.log('No user signed in');
  }
});
medium
A. Error: user is null
B. User ID: undefined
C. No user signed in
D. Nothing will be logged

Solution

  1. Step 1: Understand onAuthStateChanged behavior

    This function triggers callback with user object if signed in, or null if not.
  2. Step 2: Analyze code branches

    If user is null (not signed in), else branch logs 'No user signed in'.
  3. Final Answer:

    No user signed in -> Option C
  4. Quick Check:

    Null user triggers else branch = A [OK]
Hint: Null user means else branch runs [OK]
Common Mistakes:
  • Assuming user object is always defined
  • Expecting an error when user is null
  • Thinking nothing logs if no user
4. You wrote this code to fetch data from Firestore in Next.js but get an error:
import { getFirestore, collection, getDocs } from 'firebase/firestore';
const db = getFirestore();
async function fetchData() {
  const querySnapshot = await getDocs(collection(db, 'users'));
  querySnapshot.forEach(doc => {
    console.log(doc.data());
  });
}
fetchData();

What is the most likely cause of the error?
medium
A. doc.data() is not a function
B. The collection name 'users' is invalid
C. getDocs does not support async/await
D. Firebase app was not initialized before calling getFirestore()

Solution

  1. Step 1: Check Firebase initialization requirement

    Firestore requires Firebase app to be initialized before calling getFirestore().
  2. Step 2: Analyze other options

    'users' is valid collection name; getDocs supports async/await; doc.data() is valid method.
  3. Final Answer:

    Firebase app was not initialized before calling getFirestore() -> Option D
  4. Quick Check:

    Initialize Firebase app before Firestore = D [OK]
Hint: Always initialize Firebase app before Firestore calls [OK]
Common Mistakes:
  • Skipping Firebase initialization
  • Misunderstanding async/await with getDocs
  • Assuming collection names cause errors
5. You want to secure a Next.js page so only authenticated users can access it using Firebase Auth. Which approach is best?
hard
A. Check user authentication only in getStaticProps and serve static content
B. Use Firebase Admin SDK on server side to verify user token in getServerSideProps
C. Use Firebase Auth on client side and redirect unauthenticated users to login page
D. Store user password in cookies and check it manually in the page component

Solution

  1. Step 1: Understand authentication in Next.js

    Client-side checks can be bypassed; server-side verification is more secure.
  2. Step 2: Use Firebase Admin SDK in getServerSideProps

    This allows verifying user tokens securely on server before rendering page.
  3. Step 3: Analyze other options

    getStaticProps runs at build time, not per request; storing passwords in cookies is insecure.
  4. Final Answer:

    Use Firebase Admin SDK on server side to verify user token in getServerSideProps -> Option B
  5. Quick Check:

    Server-side token verification = A [OK]
Hint: Verify user token server-side with Firebase Admin SDK [OK]
Common Mistakes:
  • Relying only on client-side auth checks
  • Using getStaticProps for auth checks
  • Storing passwords insecurely in cookies
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard