To secure a Next.js + Firebase stack, you need to: (1) replace default test-mode Firestore rules with production security rules, (2) use the client SDK in Client Components and Admin SDK only in API routes/Server Actions, (3) configure Storage rules for file uploads, (4) store service account credentials in environment variables (server-side only), and (5) configure authorized domains in Firebase Console. This blueprint covers Firestore rules and proper SDK separation.
TL;DR
Next.js with Firebase requires proper security rules and careful separation of client vs admin SDK usage. Key tasks: configure Firestore rules, use client SDK in Client Components, use Admin SDK only in API routes/Server Actions, and store service account credentials server-side only.
Firestore Security Rules Firebase
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, update: if request.auth != null
&& request.auth.uid == userId;
}
match /posts/{postId} {
allow read: if true;
allow create: if request.auth != null;
allow update, delete: if request.auth != null
&& resource.data.authorId == request.auth.uid;
}
}
}
Admin SDK (Server-Side Only) Next.js
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) });
}
// Use in API routes only, never in Client Components
Security Checklist
Pre-Launch Checklist
Firestore rules updated from test mode
Storage rules configured
Admin SDK only in server code
Service account key in env vars
Auth domains configured
Alternative Stacks
Consider these related blueprints:
- Next.js + Supabase + Vercel - For PostgreSQL with RLS
- React + Firebase - Client-only SPA version
- Vue + Firebase - Vue alternative