Admin functions allow server-side access to Firestore with elevated privileges. These functions run on the server and can access all documents and collections securely, bypassing client-side restrictions.
1
Example: Create Task Admin Function
Here’s a basic example of a server-side function to create a task:
import { getCurrentUser } from "@/lib/session";
import { getFirestore } from "firebase-admin/firestore";
import { getFirebaseAdminApp } from "@/app/firebase";
import { toAdminFirestore } from "@/app/shared/user";
export const createTaskAdmin = async (task: Partial<Task>) => {
const user = await getCurrentUser();
if(!user?.uid){
throw new Error("User should be logged in");
}
if (!task.name) {
throw new Error("Missing required param");
}
const now = new Date();
const writeTask: Omit<Task, "id"> = {
userId: user.uid,
name: task.name,
description: task.description ?? "",
createdAt: now,
updatedAt: now,
};
const db = getFirestore(getFirebaseAdminApp());
const docRef = await db.collection("tasks").add(toAdminFirestore(writeTask));
return {
id: docRef.id,
...writeTask,
};
};
Key points:
- Uses
getCurrentUser()to get the authenticated server-side user. - Validates required parameters.
- Writes data to Firestore using the Admin SDK.
- Returns the newly created task including its Firestore
id.
2
Usage in Server Components or API Routes
You can call createTaskAdmin directly from server components, API routes, or server actions:
const newTask = {
name: "My Admin Task",
description: "Task created from server",
};
try {
const task = await createTaskAdmin(newTask);
console.log("Task created:", task);
} catch (error) {
console.error("Failed to create task:", error);
}
Notes:
- Admin functions run on the server and do not expose privileged operations to the client.
- Perfect for creating, updating, or deleting sensitive data securely.
Next, we can create the Firebase Cloud Functions section showing callable server-side functions from the client.