Navigation

Context Modules

Realm functions have access to a global context object that contains metadata for the current function call and provides access to components and services that you've configured in your app.

The context object exposes the following modules and methods:

Property
Description
Access environment values and the current environment tag.
A client object that calls your app's functions.
A built-in HTTP client.
Describes the HTTP request that triggered this function call.
Provides access to service clients.
Describes the user that initiated the request.
Contains global static values.
Contains global static values.
Returns a boolean that, if true, indicates that the function is a system function.

An object that includes the app's current environment and any environment values for that environment.

context.environment.tag

The app's current environment.

exports = async function() {
switch(context.environment.tag) {
case "": {
return "There is no current environment"
}
case "development": {
return "The current environment is development"
}
case "testing": {
return "The current environment is testing"
}
case "qa": {
return "The current environment is qa"
}
case "production": {
return "The current environment is production"
}
}
};
context.environment.values

An object where each field maps the name of an environment values to its value in the current environment.

exports = async function() {
const baseUrl = context.environment.values.baseUrl
};

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.

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());
};

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>,
"httpMethod": <string>,
"rawQueryString": <string>,
"httpReferrer": <string>,
"httpUserAgent": <string>,
"service": <string>,
"action": <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.
httpMethod
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.

Important
Realm Removes The Secret Parameter

For security reasons, Realm 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.
service
string
Contains the name of the service called within the function.
action
string
The action executed on the service.
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"
}

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 data source in the Realm UI or in an exported application directory:

Realm UI
Refer to the Service Name column of the table on the Services page or the Realm Service Name column of the table on the Linked Data Sources page.
Application Directory
Refer to the name field of the service's config.json file.
Note
MongoDB Service Names

The default name for the MongoDB Service associated with a Realm app's linked cluster is mongodb-atlas. For a linked Data Lake, the default name is mongodb-datalake.

A property that contains the user object of the function's active user.

Note
System Functions

context.user always resolves to the authenticated application user that called the function, even if the function is a system function running without regard for Realm rules. However, some functions are not called by authenticated users, such as webhook and trigger functions. For these functions, context.user resolves to a system user object that contains no data.

{
"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 Realm API Key.
"system"
The user is the system user that bypasses all rules.
data
document

A document that contains 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.

Note
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.

custom_data
document

A document from your application's custom user data collection that specifies the user's ID. You can use the custom user data collection to store arbitrary data about your application's users. If you set the name field, Realm populates the username metadata field with the return value of name. Realm automatically fetches a new copy of the data whenever a user refreshes their access token, such as when they log in. The underlying data is a regular MongoDB document, so you can use standard CRUD operations through the MongoDB Atlas service to define and modify the user's custom data.

Note
Avoid Storing Large Custom User Data

Custom user data is limited to 16MB, the maximum size of a MongoDB document. To avoid hitting this limit, consider storing small and relatively static user data in each custom user data document, such as the user's preferred language or the URL of their avatar image. For data that is large, unbounded, or frequently updated, consider only storing a reference to the data in the custom user document or storing the data with a reference to the user's ID rather than in the custom user document.

identities
array

A list of authentication provider identities associated with the user. When a user first logs in with a specific provider, Realm associates the user with an identity object that contains a unique identifier and additional metadata about the user from the provider. For subsequent logins, Realm 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"
}
]
}

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.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.
}
Give Feedback