NextFire main logoNextFire
Docs X
Introduction
Get Started
Clone repo
Run the app
Configuration
Firebase
Create firebase app
Authentication
Firestore
Storage
Functions
Global configuration
Public
Site config
Payments
Stripe
One time
Subscriptions
Webhooks
Usage
Project structure
Static pages
Public pages
Protected pages
Auth
Client auth
Server auth
Data fetching
Firestore client
Firestore admin
Functions
Storage
Content
Blog
Documentation
Components
Markdown
Cards
Diagrams
Filetree
Lists
Maths
Notes
Steps
Table
Tabs
Public
Deep
Deeper
Even deeper
  1. Data Fetching
  2. Firestore Admin

Firestore Admin Functions

How to define and call Firestore server-side functions with elevated privileges using the Firebase Admin SDK.

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.

Firestore clientFunctions

Content

FeedbackEdit page

© 2025 Ship IT.

Rubix Studios logo