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. Functions

Firebase Cloud Functions

How to define and deploy Firebase Cloud Functions in the boilerplate, including a sample createTask function.

Firebase Cloud Functions allow you to run server-side code in response to HTTP requests, Firestore events, or callable requests from your client. This is useful for performing secure operations that should not be exposed to the client.

1

Create a Cloud Function

In this boilerplate, functions are located under /functions/src/yourfunction/. Each function has its own folder. For example, to create a task function:

      import * as functions from "firebase-functions";
      import {db} from "../firebase-admin";
      import { Timestamp } from "firebase-admin/firestore";

      export const createTask = functions.https.onCall(async (request) => {
          const userId = request.auth?.uid;
          const {data} = request.data;

          if (!userId) {
              throw new functions.https.HttpsError("unauthenticated", "User must be logged in");
          }

          if (!data.name) {
              throw new functions.https.HttpsError(
                  "invalid-argument",
                  "Missing required parameter: name"
              );
          }

          const now = Timestamp.now();

          const writeTask = {
              userId: userId,
              name: data.name,
              description: data.description ?? "",
              createdAt: now,
              updatedAt: now,
          };

          const docRef = await db.collection("tasks").add(writeTask);

          return { id: docRef.id, ...writeTask };
      });

This function:

  • Validates that the user is authenticated.
  • Validates required input parameters.
  • Writes a new task to Firestore using the Admin SDK.
  • Returns the newly created task.
2

Deploy the Function

  • Before your deploy, you need to import your function in functions/index.ts

To deploy your Cloud Function, run the following command from your project root:

cd functions
npm run deploy

Notes:

  • This will deploy all functions under /functions/src/.
  • After deployment, the functions can be called from the client using Firebase callable functions (Examples can be found under lib/serbices/tasks-functions.ts):
export const createTask = async (task: Partial<Task>, serverCustomToken: string): Promise<Task> => {
try {
  // Setup
  // https://next-firebase-auth-edge-docs.vercel.app/docs/usage/client-side-apis
  await setupFirebaseAuth(serverCustomToken);

  // Call the function
  const functions = getFunctions(getFirebaseApp())
  const myCallableFunction = httpsCallable(functions, Functions.CREATE_SITE);

  // Connect to the local emulator
  if (process.env.NEXT_PUBLIC_ENV == "local") {
      console.log("connecting emulator ..")
      connectFunctionsEmulator(functions, '127.0.0.1', 5001);
  }

  const response = await myCallableFunction({
      site: task
  })

  return response.data as Task
} catch (error) {
  console.error('Internal Error', error);
  throw error;
}
};

Next, we can cover Firebase Storage for uploading and retrieving files.

Firestore adminStorage

Content

FeedbackEdit page

© 2025 Ship IT.

Rubix Studios logo