I am building a project where the frontend is React, and the backend nodejs uses. I have used the firebase Admin SDK to use firestore . Authentication is done using Firebase Authentication, and after login I store the Firebase ID token in a cookie.
When trying to write to Firestore from the backend, I always get this error:
[Firestore] Error: 16 UNAUTHENTICATED: Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie, or other valid authentication credential.
Frontend (React)
After Firebase login:
const token = await user.getIdToken();
document.cookie = `token=${token}; path=/`;
When calling my backend API, I send the token manually:
fetch("/api/saveData", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({ value: "test" }),
});
Backend
I extract the token from the header and set Firestore:
import admin from "firebase-admin";
const serviceAccount = require("./firebase-service.json");
if (!admin.apps.length) {
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
}
const db = admin.firestore();
export async function saveData(req, res) {
const auth = req.headers.authorization; // Bearer token
try {
const decoded = await admin.auth().verifyIdToken(auth.replace("Bearer ", ""));
await db.collection("users").doc(decoded.uid).set({ test: "data" });
res.json({ success: true });
} catch (error) {
console.error(error);
res.status(401).json({ error: error.message });
}
}
But the server still throws:
Error: 16 UNAUTHENTICATED: Request had invalid authentication credentials.
What I tried
✔ Confirmed the Firebase ID token is valid (checked in jwt.io)
✔ Using admin.initializeApp with service account
✔ Sending token in Authorization header
✔ Verified the token before writing to Firestore (it succeeds!)
✔ Ensured the service account JSON is valid
✔ Tried regenerating API key
✔ Disabled Firestore security rules temporarily (still same error)
Why does Firestore Admin SDK still throw 16 UNAUTHENTICATED even though the Firebase ID token is valid and verified? What am I missing?
Project setup details
Frontend: React
Backend: Node.js (Express)
Using Firebase Admin SDK to write to Firestore (server-side)
Using Firebase Auth client SDK in frontend