Navigation

Context Modules

Overview

MongoDB Stitch functions can interact with connected services, user information, predefined values, and other functions through modules attached to the global context variable.

The context variable contains the following modules:

Property Description
context.services Access service clients for the services you’ve configured.
context.values Access values that you’ve defined.
context.user Access information about the user that initiated the request.
context.request Access information about the HTTP request that triggered this function call.
context.functions Execute other functions in your Stitch application.
context.http Access the HTTP service for get, post, put, patch, delete, and head actions.

Context Modules

context.services

An object that provides access to service clients for Services in your application, including the MongoDB Service. A service client exposes all actions associated with its service as methods.

context.services.get(serviceName)

Returns a service client object or undefined if no such service exists.

Parameter Type Description
serviceName string

The unique name of the service assigned when the service was created.

You can find the name of the Service associated with a particular external service or linked cluster in the Stitch UI or in an exported application directory:

Stitch UI Refer to the Service Name column of the table on the Services page or the Stitch Service Name column of the table on the Clusters page.
Application Directory Refer to the name field of the service’s config.json file.

MongoDB Service Names

The default name for the MongoDB Service associated with a Stitch application’s initial linked cluster is mongodb-atlas.

context.functions

An object that provides access to other Functions in your application.

context.functions.execute(functionName, args...)

Calls the specified Function with any provided arguments and returns the result.

Parameter Type Description
functionName string The name of the function.
args mixed A variadic list of arguments to pass to the function. Each function parameter maps to a separate, comma-separated argument.

context.values

An object that provides access to Values via a “getter” method.

context.values.get(valueName)

Returns the plain text data or Secret value associated with the provided value name.

Parameter Type Description
valueName string The name of the Value.

context.http

A general purpose HTTP client that exposes all HTTP service actions and is not affected by service rules.

context.http.get()

Sends an HTTP GET request to the specified URL. See http.get() for detailed reference information, including parameter definitions and return types.

exports = async function() {
  const response = await context.http.get({ url: "https://www.example.com/users" })
  // The response body is a BSON.Binary object. Parse it and return.
  return EJSON.parse(response.body.text());
};
context.http.post()

Sends an HTTP POST request to the specified URL. See http.post() for detailed reference information, including parameter definitions and return types.

exports = async function() {
  const response = await context.http.post({
    url: "https://www.example.com/messages",
    body: { msg: "This is in the body of a POST request!" },
    encodeBodyAsJSON: true
  })
  // The response body is a BSON.Binary object. Parse it and return.
  return EJSON.parse(response.body.text());
};
context.http.put()

Sends an HTTP PUT request to the specified URL. See http.put() for detailed reference information, including parameter definitions and return types.

exports = async function() {
  const response = await context.http.put({
    url: "https://www.example.com/messages",
    body: { msg: "This is in the body of a PUT request!" },
    encodeBodyAsJSON: true
  })
  // The response body is a BSON.Binary object. Parse it and return.
  return EJSON.parse(response.body.text());
};
context.http.patch()

Sends an HTTP PATCH request to the specified URL. See http.patch() for detailed reference information, including parameter definitions and return types.

exports = async function() {
  const response = await context.http.patch({
    url: "https://www.example.com/diff.txt",
    body: { msg: "This is in the body of a PATCH request!" },
    encodeBodyAsJSON: true
  })
  // The response body is a BSON.Binary object. Parse it and return.
  return EJSON.parse(response.body.text());
};
context.http.delete()

Sends an HTTP DELETE request to the specified URL. See http.delete() for detailed reference information, including parameter definitions and return types.

exports = async function() {
  const response = await context.http.delete({ url: "https://www.example.com/user/8675309" })
};
context.http.head()

Sends an HTTP HEAD request to the specified URL. See http.head() for detailed reference information, including parameter definitions and return types.

exports = async function() {
  const response = await context.http.head({ url: "https://www.example.com/users" })
  // The response body is a BSON.Binary object. Parse it and return.
  EJSON.parse(response.body.text());
};

Context Properties

context.user

A property that contains the user object of the Function’s active user.

{
    "id": <string>,
    "type": <string>,
    "data": <document>,
    "identities": <array>
}
Field Type Description
id string A string representation of the ObjectId that uniquely identifies the user.
type string

The type of the user. The following types are possible:

Type Description
“normal” The user is an application user logged in through an authentication provider other than the API Key provider.
“server” The user is a server process logged in with any type of Stitch API Key.
“system” The user is a system user that bypasses all rules.
data document

A document containing metadata that describes the user. This field combines the data for all identities associated with the user, so the exact field names and values depend on which authentication providers the user has authenticated with.

System Functions Have No User Data

In system functions, the user.data object is empty. Use context.runningAsSystem() to test if the function is running as a system user.

identities array

A list of authentication provider identities associated with the user. When a user first logs in with a specific provider, Stitch associates the user with an identity object that contains a unique identifier and additional metadata about the user from the provider. For subsequent logins, Stitch refreshes the existing identity data but does not create a new identity. Identity objects have the following form:

{
  "id": "<Unique ID>",
  "provider_type": "<Provider Name>",
  "data": {
    "<Metadata Field>": <Value>,
    ...
  }
}
Field Name Description
id A provider-generated string that uniquely identifies this identity
provider_type The type of authentication provider associated with this identity.
data Additional metadata from the authentication provider that describes the user. The exact field names and values will vary depending on which authentication providers the user has logged in with. For a provider-specific breakdown of user identity data, see User Metadata.

Example

The following context.user document reflects an Email/Password user that is associated with a single User API Key.

{
  "id": "5cbf68583025b12840664682",
  "type": "normal",
  "data": {
    "email": "someone@example.com",
    "name": "myApiKeyName"
  },
  "identities": [
    {
      "id": "5cbf68583025b12880667681",
      "provider_type": "local-userpass"
    },
    {
      "id": "5cbf6c6a922616045a388c71",
      "provider_type": "api-key"
    }
  ]
}

context.request

A property that contains information about the external HTTP request that triggered the function call. This information can help you determine the origin of the call. It may contain the following fields:

{
   "remoteIPAddress": <string>,
   "requestHeaders": <object>,
   "webhookUrl": <string>,
   "webhookMethod": <string>,
   "rawQueryString": <string>,
   "httpReferrer": <string>,
   "httpUserAgent": <string>,
}
Field Type Description
remoteIPAddress string The IP address of the client that issued the Function request.
requestHeaders object

An object where each field maps to a type of HTTP Header that was included in the request that caused the function to execute. The value of each field is an array of strings where each string maps to a header of the specified type that was included in the request.

Example

{
  "requestHeaders": {
    "Content-Type": ["application/json"],
    "Cookie": [
      "someCookie=someValue",
      "anotherCookie=anotherValue"
    ]
  }
}
webhookUrl string Optional. The webhook URL of the incoming webhook that the Function is assigned to, if applicable.
webhookMethod string Optional. The HTTP method of the request that called the incoming webhook associated with the Function, if applicable.
rawQueryString string

The query string from the URL of the incoming HTTP request that caused the function to execute. All query parameters appear in the same order as they were specified.

Stitch Removes The Secret Parameter

For security reasons, Stitch automatically removes any query string key/value pair where the key is secret. For example, if an incoming request has the query string ?secret=hello&someParam=42 then the rawQueryString for that request is "someParam=42".

httpReferrer string Optional. The URL of the page that the Function request was issued from. Derived from the Referer HTTP header.
httpUserAgent string Optional. Characteristic information that identifies the source of the request, such as the software vendor, operating system, or application type. Derived from the User-Agent HTTP header.

Note

If there is no Referer header or User-Agent header present in the request, the respective field will be omitted.

Example

The following context.request document reflects a function call issued from https://myapp.example.com/ by a user browsing with Chrome 73 on macOS High Sierra:

{
   "remoteIPAddress": "54.173.82.137",
   "httpReferrer": "https://myapp.example.com/",
   "httpUserAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"
}

Context Methods

context.runningAsSystem()

Returns true if the function is running as a System User, otherwise returns false.

const isSystemUser = context.runningAsSystem()
if(isSystemUser) {
  // Do some work that bypasses rules
} else {
  // Do some work in the context of the user that called the function.
}