Run functions locally

You can run functions locally to test them before deploying to production. To run functions locally, use either:

  • The Cloud Functions shell. This tool emulates all types of function triggers, and provides an interactive shell for invoking the functions with test data.
  • The Firebase CLI's firebase serve command. This tool emulates HTTPS functions, providing a URL to trigger the local function.

For both tools, code changes you make during an active session are automatically reloaded by the emulator. If your code needs to be transpiled (TypeScript, React) make sure to do so before running the emulator.

Set up admin credentials (optional)

If you want your functions tests to interact with Google APIs or other Firebase APIs via the Firebase Admin SDK, you may need to set up admin credentials. Note:

  • Cloud Firestore and Realtime Database triggers already have sufficient credentials, and do not require additional setup.
  • All other APIs, including Firebase APIs such as Authentication and FCM or Google APIs such as Cloud Translation or Cloud Speech, require the setup steps described in this section. This applies whether you're using the functions shell or firebase serve.

To set up admin credentials for emulated functions (other than Cloud Firestore and Realtime Database):

  1. Open the Service Accounts pane of the Google Cloud Console.
  2. Make sure that App Engine default service account is selected, and use the options menu at right to select Create key.
  3. When prompted, select JSON for the key type, and click Create.
  4. Set your Google default credentials to point to the downloaded key:

    Unix

    $ export GOOGLE_APPLICATION_CREDENTIALS="path/to/key.json"
    
    $ firebase functions:shell
    
    OR
    
    $ firebase serve --only functions
    

    Windows

    $ set GOOGLE_APPLICATION_CREDENTIALS=path\to\key.json
    
    $ firebase functions:shell
    
    OR
    
    $ firebase serve --only functions
    

After completing these steps, your functions tests can access Firebase and Google APIs using the Admin SDK. For example, when testing an Authentication trigger, the emulated function could call admin.auth().getUserByEmail(email).

Serve HTTP functions from the command line

You can serve and run your HTTP functions locally using the Firebase CLI. This allows you to view and test your Firebase project before deploying to production.

To use this feature, make sure both firebase-tools and firebase-functions SDK are the latest versions available. To update both, run the following two commands in the functions/ directory of your project:

npm install --save firebase-functions@latest
npm install -g firebase-tools

To serve your Firebase project locally, run the following command from your project directory. This command will emulate hosting and functions on locally hosted URLs.

firebase serve
If you’re using Cloud Functions to generate dynamic content for Firebase Hosting, firebase serve, by default, uses your local HTTP functions as proxies for hosting. For more configuration options for Firebase Hosting and Cloud Functions, see the Firebase CLI Reference.

If you're using custom functions configuration variables, run the following command in the functions directory of your project before running firebase serve.

firebase functions:config:get > .runtimeconfig.json

However, if you're using Windows PowerShell, replace the above command with:

firebase functions:config:get | ac .runtimeconfig.json

Serve functions using a Cloud Functions shell

The Cloud Functions shell emulates all types of function triggers with an interactive shell for invoking the functions with test data. Options vary by function type, but the basic usage format is:

myFunctionName(data, options)

The data parameter is required for Realtime Database and PubSub triggers, and optional for all other function types. Also, the optional options parameter is valid only for Realtime Database functions.

Optionally, you can load test data from a local file by saving the file as a variable and invoking a function with it:

var data = require('./path/to/testData.json');
myFunction(data);

Install and configure the Cloud Functions shell

To use this feature, firebase-tools must have minimum version 3.11.0, and firebase-functions SDK must have minimum version 0.6.2. To update both, run the following commands in the functions/ directory for your project:

npm install --save firebase-functions@latest
npm install -g firebase-tools

If you are not using custom functions configuration variables, run the shell with the following command:

firebase functions:shell

If you're using custom functions configuration variables, first run the command to get your custom config (run this within the functions directory), and then run the shell:

firebase functions:config:get > .runtimeconfig.json
# If using Windows PowerShell, replace the above with:
# firebase functions:config:get | ac .runtimeconfig.json
firebase functions:shell

Invoke HTTPS functions

For invoking HTTPS functions in the shell, usage is the same as the request NPM module, but replace request with the name of the function you want to emulate. For example:

# invoke
myHttpsFunction()
myHttpsFunction.get()
myHttpsFunction.post()

# invoke at sub-path
myHttpsFunction('/path')
myHttpsFunction.get('/path')
myHttpsFunction.post('/path')

# send POST request with form data
myHttpsFunction.post('/path').form( {foo: 'bar' })

Invoke Realtime Database functions

When running Realtime Database functions locally, you'll need to provide appropriate test data. This generally means providing new test data for onCreate operations, old/removed data for onDelete operations, and both for onUpdate or onWrite functions:

# invoke onCreate function
myDatabaseFunction('new_data')

# invoke onDelete function
myDatabaseFunction('old_data')

# invoke onUpdate or onWrite function
myDatabaseFunction({before: 'old_data', after: 'new_data' })

In addition to the before/after options, the shell provides the params option to use in mocking wildcards in a path:

# mock wildcards in path, for example: if the path was input/{group}/{id}
myDatabaseFunction('data', {params: {group: 'a', id: 123}})

By default, the shell runs Realtime Database functions with administrative privileges. Use the auth option to instead run functions as a particular end user, or as an unauthenticated user:

# to mock unauthenticated user
myDatabaseFunction('data', {authMode: 'USER'})
# to mock end user
myDatabaseFunction('data', {auth: {uid: 'abcd'}})

Invoke Firestore functions

When running Firestore functions locally, you'll need to provide appropriate test data. This generally means providing new test data for onCreate operations, old/removed data for onDelete operations, and both for onUpdate or onWrite functions. Note that Firestore data has to be key-value pairs; see Supported Data Types.

# invoke onCreate function
myFirestoreFunction({foo: ‘new’})

# invoke onDelete function
myFirestoreFunction({foo: ‘old’})

# invoke onUpdate or onWrite function
myFirestoreFunction({before: {foo: ‘old’}, after: {foo: ‘new’} })

In addition to the before/after options, the shell provides the params option to use in mocking wildcards in a document name:

# mock wildcards in document name, for example: if the name was input/{group}/{id}
myFirestoreFunction({foo: ‘new’}, {params: {group: 'a', id: 123}})

The shell always runs Firestore functions with administrative privileges, which means it mocks a create/update/delete event as if it were done by an administrative user.

Invoke PubSub functions

For PubSub functions, insert your message payload in a Buffer instance and add optionally data attributes as shown:

// invokes a function with the JSON message { hello: 'world' } and attributes { foo: 'bar' }
myPubsubFunction({data: new Buffer('{"hello":"world"}'), attributes: {foo: 'bar'}})

Invoke Analytics functions

You can invoke an Analytics function without any data by running myAnalyticsFunction() in the shell. To run the function with test data, it is recommended to define a variable for the specific event data fields that your function needs:

var data = {
  eventDim: [{
    // populates event.data.params
    params:{foo:'bar'},
    // populates event.data.name
    name: 'event_name',
    // populates event.data.logTime, specify in microseconds
    timestampMicros: Date.now() * 1000,
    // populates event.data.previousLogTime, specify in microseconds
    previousTimestampMicros: Date.now() * 1000,
    // populates event.data.reportingDate, specify in 'YYYYMMDD' format
    date: '20170930',
    // populates event.data.valueInUSD
    valueInUsd: 230
  }],
  userDim: userDim
};

myAnalyticsFunction(data);

Invoke Storage, Auth, and Crashlytics functions

For Storage, Auth, and Crashlytics functions, invoke the local function with the test data that you’d like to see inside of the function. Your test data must follow the corresponding data formats:

Specify only the fields that your code depends on, or none at all if you only want to run the function.

Logging

Both tools, firebase serve and the Cloud Functions shell, stream logs from your functions to the terminal window where they run. They displays all output from console.log(), console.info(), console.error(), and console.warn() statements inside your functions.

Send feedback about...

Need help? Visit our support page.