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. The exact metadata field names and values depend on the authentication providers associated with the user.

Authentication Provider Details
Anonymous Anonymous users are not associated with any metadata.
Email/Password

Email/Password users are associated with the following metadata fields:

Field Description
email The user’s email address.
API Key (Server & User)

API Key users are associated with the following metadata fields:

Field Description
name The name of the API Key.
OAuth 2.0 (Facebook & Google) OAuth 2.0 users are associated with data provided by the authentication service. The exact fields depend on the provider’s Metadata Fields configuration. Users must explicitly grant your application access to the data when they first log in or when you change the provider configuration.
Custom Custom authentication users are associated with data included in the JWT returned from the external authentication system. The exact values that appear in the user object’s data field depend on the provider’s Metadata Fields configuration.

Note

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 The list of identities associated with the user. Each authentication provider can provide an identity, and users can be associated with multiple identities.

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>,
   "httpReferrer": <string>,
   "httpUserAgent": <string>
}
Field Type Description
remoteIpAddress string The IP address of the client that issued the Function request.
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.
}