Server-Side Data with Firebase Firestore

6 min read
J

John Smith

Server-Side Data with Firebase Firestore

Why Firestore?

Firestore is a flexible, scalable NoSQL database for mobile, web, and server development from Firebase and Google Cloud.

Advantages:

  • Real-time data synchronization
  • Offline support
  • Powerful querying

Integrating with Next.js Server Components

You can directly query Firestore from your Server Components without needing to create separate API routes.

Setting up the Firebase Admin SDK

Make sure to initialize the SDK in a separate file and handle credentials securely.

import { getFirestore } from 'firebase-admin/firestore';
import { initializeApp, getApps, cert } from 'firebase-admin/app';

const serviceAccount = JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT_KEY);

if (!getApps().length) {
  initializeApp({
    credential: cert(serviceAccount),
  });
}

const db = getFirestore();
export { db };

Fetching Data in a Page

Now you can import db and fetch data directly.

// app/posts/page.tsx
import { db } from '@/lib/firebase-admin';

async function getPosts() {
  const snapshot = await db.collection('posts').get();
  return snapshot.docs.map(doc => doc.data());
}

export default async function PostsPage() {
  const posts = await getPosts();
  // ... render posts
}