Google is committed to advancing racial equity for Black communities. See how.

Organize multiple functions

As you integrate Cloud Functions into your project, your code could expand to contain many independent functions. You can modularize and organize your code to make it easy to navigate and manintain while still keeping the basic structure required to deploy your functions.

Write functions in multiple files

When getting started with Cloud Functions you might put your first few functions in a single file:

index.js


const functions = require('firebase-functions');
exports.foo = functions.https.onRequest((request, response) => {
  // ...
});
exports.bar = functions.https.onRequest((request, response) => {
  // ...
});

This can become hard to manage with more than a few functions. Instead, you can put all of your logic for each function in its own file and use your index.js file as a simple list of exports:

foo.js


const functions = require('firebase-functions');
exports.foo = functions.https.onRequest((request, response) => {
  // ...
});

bar.js


const functions = require('firebase-functions');
exports.bar = functions.https.onRequest((request, response) => {
  // ...
});

index.js


const foo = require('./foo');
const bar = require('./bar');
exports.foo = foo.foo;
exports.bar = bar.bar;

Group functions

In many projects, functions can be separated into logical groups that should be deployed and maintained together. For example, you might have a group of functions used for reporting metrics:

metrics.js


const functions = require('firebase-functions');
exports.usageStats = functions.https.onRequest((request, response) => {
  // ...
});
exports.nightlyReport = functions.https.onRequest((request, response) => {
  // ...
});

You can put these functions into a group when exporting them in your index.js file:

index.js


// Export both functions from metrics.js in the "metrics" group:
//  - metrics-usageStats
//  - metrics-nightlyReport
exports.metrics = require('./metrics');

When deployed, functions will be prefixed with the name of their group, so in this example the functions would be named metrics-usageStats and message-nightlyReport.

When deploying functions you can limit the action to a single group:


firebase deploy --only functions:metrics

Next steps

To learn more about Cloud Functions, see: