Navigation

Define a Function

On this page

Overview

You can create and configure functions in your application at any time from the Stitch UI or by importing a function configuration file.

Procedure

1

Create a New Function

To define a new server-side function from the Stitch UI:

  1. Click Functions in the left-hand navigation.
  2. Click New Function in the top right of the Functions page.
2

Name the New Function

Enter a unique, identifying name for the function in the Name field. This name must be distinct from all other functions in the application.

3

Configure User Authentication

Functions in Stitch always execute in the context of a specific application user or as a system user that bypasses rules. To configure the function’s execution user, specify the type of authentication that Stitch should use.

Authentication Type Description
Application Authentication This type of authentication configures a function to run in the context of the existing application user that was logged in when the client application called the function. If the function was called from another function then it inherits the execution user from that function.
System This type of authentication configures a function to run as a system user that has full access to MongoDB CRUD and Aggregation APIs and is not affected by any rules, roles, or permissions.
User ID This type of authentication configures a function to always run as a specific application user.
Script This type of authentication configures a function to run as a specific application user determined based on the result of a custom function that you define. The function must return a specific user’s id string or can specify a system user by returning { "runAsSystemUser": true }.
4

Configure Function Execution Logs

By default, Stitch includes the arguments that a function received in the log entry for each execution of the function. If you want to prevent Stitch from logging the arguments, disable Log Function Arguments.

5

Specify an Authorization Expression

You can dynamically authorize requests based on the contents of each request by defining a Can Evaluate JSON expression. Stitch evaluates the expression whenever the function is called. If you do not specify an expression then Stitch automatically authorizes all authenticated incoming requests.

The expression can expand standard expression variables, including the %%request and %%user expansions.

6

Configure the Function’s Privacy Level

By default, you can call a function from client applications as well as other functions in the same application. You can prevent client applications from seeing or calling a function by setting Private to true.

You can still call a private function from JSON expressions and other functions, including incoming webhooks and triggers.

7

Write the Function Code

Once you’ve created and configured the new function, it’s time to write the actual javascript code that runs when you call the function. You can write the code directly in the Stitch UI using the function editor.

Note

You can use most modern (ES6+) JavaScript features in functions, including async/await, destructuring, and template literals.

From the function’s Settings page:

  1. Click the Function Editor tab.

  2. Add javascript code to the function. At minimum, the code must assign a function to the global variable exports, as in the following example:

    exports = function() {
      return "Hello, world!";
    };
    
8

Save the Function

Once you’ve written the function code, click Save from either the Function Editor or Settings tab.

After you save the function, you can begin using it immediately. For more information on using the function, see Call a Function.

1

Export Your Stitch Application

To create new function with stitch-cli, you need a previously created application configuration.

You can export your application configuration from the Export tab of the Settings page in the Stitch UI, or by running the following command from an authenticated instance of stitch-cli:

stitch-cli export --app-id=<App ID>
2

Add a Function Configuration Directory

Create a new subdirectory with the same name as the function in the /functions folder of the application directory that you exported.

mkdir -p functions/<function name>
3

Add a Function Configuration File

Add a file named config.json to the new function directory. The configuration file should have the following form:

{
  "name": "<Unique Function Name>",
  "run_as_authed_user": <boolean>,
  "run_as_user_id": "<Stitch User ID>",
  "run_as_user_id_script_source": "<Stringified Function>",
  "disable_arg_logs": <boolean>,
  "can_evaluate": <JSON Expression>,
  "options": <document>
}
4

Name the New Webhook

Enter a unique, identifying name for the webhook in the Name field. This name must be distinct from all other functions in the application.

{
  "name": "<Unique Webhook Name>"
}
5

Configure User Authentication

Specify the type of authentication that Stitch should use for the webhook. Stitch supports the following webhook authentication methods:

Authentication Method Description
Application Authentication

This type of authentication configures a function to run in the context of the existing application user that was logged in when the client application called the function. If the function was called from another function then it inherits the execution user from that function.

To configure a webhook to use application authentication, set the value of run_as_authed_user to true:

{
  "run_as_authed_user": true,
  "run_as_user_id": "",
  "run_as_user_id_script_source": "",
}
System

This type of authentication configures a function to run as a system user that has full access to MongoDB CRUD and Aggregation APIs and is not affected by any rules, roles, or permissions.

To configure a webhook to run as a system user, do not set any other authentication fields:

{
  "run_as_authed_user": false,
  "run_as_user_id": "",
  "run_as_user_id_script_source": "",
}
User ID

This type of authentication configures a function to always run as a specific application user.

To configure a webhook to always run as a specific user, set run_as_user_id to the user’s id:

{
  "run_as_authed_user": false,
  "run_as_user_id": "<Stitch User ID>",
  "run_as_user_id_script_source": "",
}
Script

This type of authentication configures a function to run as a specific application user determined based on the result of a custom function that you define. The function must return a specific user’s id string or can specify a system user by returning { "runAsSystemUser": true }.

To configure a webhook to run as a user determined by a function, set run_as_user_id_script_source to the stringified function code:

{
  "run_as_authed_user": false,
  "run_as_user_id": "",
  "run_as_user_id_script_source": "<Stringified Function>",
}
6

Configure Function Execution Logs

To include any values that the function receives as arguments in its log entry, set disable_arg_logs to false.

7

Specify an Authorization Expression

You can dynamically authorize requests based on the contents of each request by defining a Can Evaluate JSON expression. Stitch evaluates the expression whenever the function is called. If you do not specify an expression then Stitch automatically authorizes all authenticated incoming requests.

The expression can expand standard expression variables, including the %%request and %%user expansions.

Example

The following expression only authorizes incoming requests if the sender’s IP address is not included in the list of addresses.

{
    "%%request.remoteIPAddress": {
        "%nin": [
            "248.88.57.58",
            "19.241.23.116",
            "147.64.232.1"
        ]
    }
}
8

Configure the Function’s Privacy Level

By default, you can call a function from client applications as well as other functions in the same application. You can prevent client applications from seeing or calling a function by setting private to true.

You can still call a private function from JSON expressions and other functions, including incoming webhooks and triggers.

9

Write the Function Code

Once you’ve created and configured the new function, it’s time to write the actual javascript code that runs when you call the function.

Add a file named source.js that contains the javascript code for the function to the new function directory.

Note

You can use most modern (ES6+) JavaScript features in functions, including async/await, destructuring, and template literals.

10

Import the Function

Once you’ve configured the function and written the source code, all that’s left is to import the function.

  1. Ensure that config.json and source.js are saved.

  2. Navigate to the root of the exported application directory.

  3. Log in to MongoDB Atlas with stitch-cli:

    stitch-cli login --username="<MongoDB Cloud Username>" --api-key="<MongoDB Cloud API Key>"
    
  4. Import the directory:

    stitch-cli import
    

Now that you have imported the function, you can begin using it immediately.

For more information on using the function, see Call a Function.