Balis 情報マガジン

firebase keyjson

📅 October 29, 2026📖 Verified Publication

Mastering Firebase Service Account Key JSON: A Complete Guide

Key Takeaways

  • The Firebase key JSON (Service Account Key) grants programmatic access to your project via the Admin SDK; it is not an API Key.
  • Always store this file securely in environment variables or secret managers. Never commit it to Git repositories like GitHub or GitLab.
  • Regenerate keys immediately if you suspect leakage. Old keys can be revoked, but new keys are generated as new private keys.
  • Use the GOOGLE_APPLICATION_CREDENTIALS environment variable to point Node.js or Python SDKs to the JSON file location.

What is a Firebase Key JSON and Why Do You Need It?

When you interact with Firebase from a server-side environment (Node.js, Python, PHP, etc.), you cannot use the standard client-side initialization code found in your firebase.json or browser setup. Instead, you need a Service Account. This is a special identity that your backend code assumes to access Firebase resources.

The key JSON file is the credential file that proves to Firebase that your server code is authorized to act on behalf of your project. It contains:

  • Private Key: A cryptographic key pair that signs requests.
  • Client Email: The service account’s email address (e.g., firebase-adminsdk-xyz@project-id.iam.gserviceaccount.com).
  • Project ID: The identifier of your Firebase project.

Without this file, your Admin SDK initialization will fail with authentication errors such as PERMISSION_DENIED or CREDENTIALS_FILE_NOT_FOUND.

How to Generate and Download Your Firebase Key JSON

Generating a new service account key is a security best practice, especially when moving from development to production or if a key has been exposed.

Step-by-Step Process

  1. Navigate to the Firebase Console.
  2. Select your specific project.
  3. Go to Project Settings (gear icon) > Service Accounts.
  4. Find the default service account (usually named firebase-adminsdk) or create a new one.
  5. Click the “Add Key” button next to the account.
  6. Choose JSON as the key type and click Create.
  7. Download the resulting .json file.

Caution: Only one JSON key can be active for a service account at a time for a specific type. Generating a new key may invalidate the previous one depending on your setup, or you may need to add new keys to avoid downtime.

Securing Your Key JSON: Best Practices Checklist

The key JSON file contains a private key. If leaked, an attacker can access your Firestore, Auth, Realtime Database, and Cloud Functions. Treat it like a master password.

Practice Do Don't
Storage Use cloud secret managers (AWS Secrets Manager, GCP Secret Manager) or CI/CD vaults. Do not store in plain text on unencrypted filesystems in production.
VCS Add serviceAccountKey.json to your .gitignore immediately. Never commit the JSON file to Git, even in private repositories.
Access Rotate keys every 90 days. Do not share keys via email, Slack, or clipboard indefinitely.
Validation Scan your codebase with tools like TruffleHog or Gitleaks before pushing to public repos. Do not assume "private" means safe from accidental exposure.

How to Use the Key JSON in Your Code

Different languages handle service account files differently. Here is how to implement it in the two most common server-side runtimes.

Node.js (Admin SDK)

You must set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of your JSON file before initializing Firebase.

// server.js
// 1. Set the environment variable (do this in .env or shell, not in code if possible)
process.env.GOOGLE_APPLICATION_CREDENTIALS = "./serviceAccountKey.json";

// 2. Initialize Firebase Admin
const { initializeApp, cert } = require("firebase-admin/app");
const admin = require("firebase-admin");

if (!admin.apps.length) {
  admin.initializeApp(); // Uses GOOGLE_APPLICATION_CREDENTIALS automatically
}

// 3. Test it
const { getFirestore } = require("firebase-admin/firestore");
const db = getFirestore();
console.log("Connected to Firestore successfully.");

Python (Firebase Admin)

Python uses the same environment variable convention.

# server.py
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "./serviceAccountKey.json"

import firebase_admin
from firebase_admin import credentials

cred = credentials.Certificate("serviceAccountKey.json")
firebase_admin.initialize_app(cred)

# Test connection
from firebase_admin import db
ref = db.reference("/test")
print("Connected to Realtime Database.")

Common Errors and Troubleshooting

Error: "No Firebase App '[default]' has been created"

Cause: You called a Firebase method before initializeApp().

Fix: Ensure admin.initializeApp() is called at the top level of your script before any database calls.

Error: "PERMISSION_DENIED" or "Forbidden"

Cause: The service account lacks the necessary IAM roles.

Fix: Go to Firebase Console > Project Settings > Service Accounts. Ensure the account has roles like Owner (for dev) or specific roles like Service Usage Consumer and Storage Object User. Avoid using "Owner" in production; use least-privilege roles.

Error: "File does not exist" or "Invalid API key"

Cause: Incorrect file path or the key was revoked.

Fix: Verify the absolute path in GOOGLE_APPLICATION_CREDENTIALS. Ensure the JSON file is valid and not corrupted. If it was recently regenerated, confirm the new file is being used.

Frequently Asked Questions (FAQs)

Q1: Is the Firebase Key JSON the same as the Firebase API Key?

No. They are completely different credentials with different scopes and security implications.

  • API Key: Used for client-side (browser/mobile) apps. It is semi-public and should be restricted with HTTP Referrers or App IDs. It does not grant access to server-only resources like Firestore Admin SDK.
  • Key JSON (Service Account): Used for server-side code. It contains a private key that grants full, powerful access to your project. It must be kept strictly secret.

Q2: Can I use the Firebase Key JSON in a client-side browser app?

Never. Browser code is visible to users. If you embed the key JSON in your frontend, anyone can download it and take over your Firebase project, including deleting your databases and incurring massive cloud costs. Client-side apps must use the Firebase Web SDK and API Keys, or call your own secure backend which uses the key JSON.

Q3: What should I do if I accidentally commit the key JSON to GitHub?

  1. Regenerate the Key Immediately: Go to Firebase Console, delete the old key, and create a new one. The old private key will be invalidated.
  2. Purge Git History: Use tools like git-filter-branch or BFG Repo-Cleaner to remove the file from all commit history. Note: GitLab/Git