How to Use App Context
Published: 2024-07-09 06:42:10

PubNub [App Context](https://www.pubnub.com/products/app-context/?) simplifies the development of complex real-time features by providing a serverless storage mechanism for User, Channel, and Membership information. App Context triggers events whenever the data changes, enabling your apps to update in real-time and the stored data can be used in [Illuminate](https://www.pubnub.com/products/illuminate/?), [Functions](https://www.pubnub.com/products/functions/?), and other PubNub services to make smarter decisions. You can also manage this data through an intuitive, no-code interface with [BizOps Workspace](https://www.pubnub.com/how-to/manage-users-and-channels-with-bizops-workspace/?).

What is App Context?
--------------------

[App Context](https://www.pubnub.com/docs/general/metadata/channel-metadata?) (formerly known as Objects) allows you to:

-   Provide meaning to the Users and Channels in your application and the relationships between them.
-   Store metadata for all of your entities on the server, making it simple to provide a global source of truth for your clients.  Note that a User does not have to represent a human being, and it is common to store device status within the user object instead.
-   Receive instant real-time events whenever an object's values change.

While any application can use App Context, it is especially popular with developers creating [Chat Solutions](https://www.pubnub.com/solutions/chat/?).

App Context provides a set of suggested fields for your [Users](https://www.pubnub.com/docs/general/metadata/users-metadata?) and [Channels](https://www.pubnub.com/docs/general/metadata/channel-metadata?), as well as suggested fields for the [Memberships](https://www.pubnub.com/docs/general/metadata/membership-metadata?) between them.  Most of these fields are optional, so you can pick and choose which fields you populate, as well as provide your own custom fields.

![Diagram showing user management, memberhip, channel management](https://www.pubnub.com/cdn/3prze68gbwl1/5ICbXWgNTJNc5kXAAQ4qJI/40b24d228d9ed97e17e47b027469bcdf/app_context_diagram.png "How-to - BizOps Workspace Manage Users and Channels - Image 01")

App Context Use Cases
---------------------

As mentioned, App Context is especially popular with developers creating Chat Solutions, but it can be used in a variety of use cases:

-   **Chat:** Store user information (name, profile photo, 'on vacation' status, job title), channel information (icon, description, audience), user roles & keep track of the last message read per channel, per user.
-   **Sports, Media & Entertainment:** Live voting and polling, live trivia, real-time bidding, CTA (call to action) overlays for merchandise or promotions.
-   **Gaming:** Real-time player stats including player level, games won, badges; leaderboard tracking and management
-   **More:** User away/active status, user trust score for fraud detection, user location tracking, IoT device statuses such as battery level or last sensor reading

How to Enable App Context
-------------------------

App Context can be enabled as follows:

1.  Log into the [Admin Portal](https://admin.pubnub.com/?)
2.  Click on the ‘Apps’ tab on the left-hand side of the portal
3.  Click on an application. You will be brought to the keysets page for this application.
4.  If you have not already done so, create a new keyset by clicking the “Create New Keyset” button. You will be brought to the configuration page for this keyset
5.  Enable App Context by clicking the slider
6.  The **Bucket Region** setting is the region where your data is stored. Please note that the region cannot be modified after saving changes to the keyset.
7.  If the **User Metadata Events** and **Channel Metadata Events** settings are enabled, the user and channel events are triggered when data is set or removed in the database, as discussed later.
8.  When the **Membership Events** setting is enabled, membership events are triggered when memberships are added, updated, or removed, as discussed later.
9.  The remaining options are out of scope for this article, but please refer to the [App Context documentation](https://www.pubnub.com/docs/general/metadata/basics#configuration?) for more information
10.  Click on **Save Changes** to save these updated changes.

User App Context
----------------

When a new user is enrolled into your application, perhaps through some external identity provider, you will have some way of uniquely identifying that user to PubNub; this is the [User ID](https://www.pubnub.com/docs/general/setup/users-and-devices?) that your user's client will use to initialize the PubNub SDK.  The PubNub User ID might not be the same as the ID you use elsewhere in your solution to identify that same user, so we recommend keeping track of that in the 'External ID' field.

User Name, Email, and Profile URL do not require explanation, but the benefit of keeping these within App Context means that if a user changes any of these fields, the changes can be propagated at scale to all listening clients using App Context events, which are supported by all of our SDKs.

### How do I create a User representation in App Context?

There are two ways to create an App Context User.

1.  Users can be created and managed using [BizOps Workspace](https://www.pubnub.com/docs/bizops-workspace/basics?), found within the PubNub admin portal. This does not require any code, and the process is explained with examples in the separate article: [How to Manage Users and Channels with BizOps Workspace](https://www.pubnub.com/how-to/manage-users-and-channels-with-bizops-workspace/?)
2.  APIs are exposed through each of our SDKs to create Users. If you are using our [Chat SDK](https://www.pubnub.com/docs/chat/chat-sdk/overview?), then this SDK handles app context for you behind the scenes; for example, the Chat SDK '[createUser()](https://www.pubnub.com/docs/chat/chat-sdk/build/features/users/create?)' method will call JavaScript's [setUUIDMetadata](https://www.pubnub.com/docs/sdks/javascript/api-reference/objects#set-user-metadata?) under the covers to create a User. Dedicated APIs are provided to modify your App Context data if you use any SDK other than the Chat SDK. I already mentioned the JavaScript [setUUIDMetadata](https://www.pubnub.com/docs/sdks/javascript/api-reference/objects#set-user-metadata?) API, but there are equivalents for all our APIs, including [Java](https://www.pubnub.com/docs/sdks/java/api-reference/objects?), [Swift](https://www.pubnub.com/docs/sdks/swift/api-reference/objects?), [Kotlin](https://www.pubnub.com/docs/sdks/kotlin/api-reference/objects?), [Python](https://www.pubnub.com/docs/sdks/python/api-reference/objects?), [Unity](https://www.pubnub.com/docs/sdks/unity/api-reference/objects?), etc.

Channel App Context
-------------------

PubNub will create channels automatically whenever a user subscribes or publishes to them, but channels probably represent something meaningful to your application, for example, in a chat app, you might have a Group Chat that uses a channel to communicate or a live event might use a dedicated channel to manage polls.

Specifying App Context for a channel will store and update any desired metadata related to that channel, with those updates being optionally propagated to all interested clients.  You might give a channel a name, e.g., 'Chat between User A and User B,' and perhaps the channel is related to some document storage, which could be tracked in a custom 'URI' field.

### How do I create a Channel representation in App Context?

Similar to Users, there are two ways to create an App Context Channel.

1.  Channels can be created and managed using [BizOps Workspace](https://www.pubnub.com/docs/bizops-workspace/basics?). This does not require any code, and the process is explained with examples in the separate article: [How to Manage Users and Channels with BizOps Workspace](https://www.pubnub.com/how-to/manage-users-and-channels-with-bizops-workspace/?)
2.  APIs are exposed through each of our SDKs to create Channels. If you are using our [Chat SDK](https://www.pubnub.com/docs/chat/chat-sdk/overview?), then this handles app context for you behind the scenes; for example, the family of '[Create](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/create?) channel' methods will call JavaScript's [setChannelMetadata()](https://www.pubnub.com/docs/sdks/javascript/api-reference/objects#set-channel-metadata?) under the covers. If you are using any SDK other than the Chat SDK, then dedicated APIs are provided to modify your App Context data, including [JavaScript](https://www.pubnub.com/docs/sdks/javascript/api-reference/objects#set-channel-metadata?), [Java](https://www.pubnub.com/docs/sdks/java/api-reference/objects?), [Swift](https://www.pubnub.com/docs/sdks/swift/api-reference/objects?), [Kotlin](https://www.pubnub.com/docs/sdks/kotlin/api-reference/objects?), [Python](https://www.pubnub.com/docs/sdks/python/api-reference/objects?), [Unity](https://www.pubnub.com/docs/sdks/unity/api-reference/objects?), etc.

Membership App Context
----------------------

Having defined App Context for both our users and channels, we can now define the relationship between the two by specifying whether users are ['members'](https://www.pubnub.com/docs/general/metadata/membership-metadata?) of a channel.

When a user joins a channel, they can receive updates about any other member of that same channel; they can be notified when users `join` or `leave` as well as whenever that user's App Context updates (e.g., they update their name).

**This is a deceptively powerful mechanism that provides a lot of value**, especially for chat app developers.  If you did not use App Context, you would need to track every user yourself, which channels they were a member of, and notify everyone else in that same channel when that user joins or leaves.  This challenge does not scale linearly, so the more users you have in your solution, the more difficult it becomes for you to try and manage all this information centrally.

By using App Context, your chat clients are provided with all the information they need to maintain their internal state, and you also have full control over that data with the PubNub [Access Manager](https://www.pubnub.com/docs/general/security/access-control?) to prevent unauthorized access.

### How do I create a Membership?

Similar to Users and Channels, there are two ways to create a Membership.

1.  Memberships can be created and managed using [BizOps Workspace](https://www.pubnub.com/docs/bizops-workspace/basics?) without writing code. Please see the [Manage Membership](https://www.pubnub.com/docs/bizops-workspace/channel-management#manage-membership?) section of our documentation for more details.
2.  APIs are exposed through each of our SDKs to create Channels. If you are using our [Chat SDK](https://www.pubnub.com/docs/chat/chat-sdk/overview?), then this handles app context for you behind the scenes; for example, the family of '[Create](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/create?) channel' methods will call JavaScript's [setMemberships](https://www.pubnub.com/docs/sdks/javascript/api-reference/objects#set-channel-memberships?) under the covers. If you are using any SDK other than the Chat SDK, then dedicated APIs are provided to modify your App Context data, including [JavaScript](https://www.pubnub.com/docs/sdks/javascript/api-reference/objects#set-channel-memberships?), [Java](https://www.pubnub.com/docs/sdks/java/api-reference/objects?), [Swift](https://www.pubnub.com/docs/sdks/swift/api-reference/objects?), [Kotlin](https://www.pubnub.com/docs/sdks/kotlin/api-reference/objects?), [Python](https://www.pubnub.com/docs/sdks/python/api-reference/objects?), [Unity](https://www.pubnub.com/docs/sdks/unity/api-reference/objects?), etc.

Receiving Real-time events when App Context Changes
---------------------------------------------------

When App Context data changes, your application will receive an event to notify you of what has changed in real-time; this allows you to create responsive apps without polling the server for updates.

### Receiving App Context Changes through the PubNub SDK (excluding Chat SDK)

All PubNub SDKs expose “Event Listeners,” and it is through these listeners that you can listen for `object events`, which are fired whenever App Context data changes.

Note that there is a slight nuance here that, at the time of writing, some of our SDKs support a new format for ‘event listeners,’ as explained in [this blog about updates to the event engine and event listeners](https://www.pubnub.com/blog/updates-to-the-event-engine-and-event-listeners/?). Regardless of the event listener format, the principle remains the same: Your app should register to receive app context events through a listener provided by the SDK.

As detailed in the [JavaScript SDK documentation](https://www.pubnub.com/docs/sdks/javascript/api-reference/publish-and-subscribe#add-listeners?), registering for App Context events will look as follows:

```js
const channel = pubnub.channel('channel_1');
const subscription = channel.subscription();
subscription.onObjects = 
  (objectsEvent) => { console.log("Objects event: ", objectsEvent); };
```

Documentation describing how to register for App Context events in other languages can be found in the following locations: [Java](https://www.pubnub.com/docs/sdks/java/api-reference/publish-and-subscribe#add-listeners?), [Swift](https://www.pubnub.com/docs/sdks/swift/api-reference/publish-and-subscribe#add-listeners?), [Kotlin](https://www.pubnub.com/docs/sdks/kotlin/api-reference/publish-and-subscribe#add-listeners?), [Python](https://www.pubnub.com/docs/sdks/python/api-reference/publish-and-subscribe#add-listeners?) (Note that Python calls the events ‘metadata’, whereas other SDKs refer to the events as ‘objects’), [Unity](https://www.pubnub.com/docs/sdks/unity/api-reference/configuration#event-listeners?), etc.

For a worked example and interactive demo, please refer to the article on [How to Manage Users and Channels with BizOps Workspace](https://www.pubnub.com/how-to/manage-users-and-channels-with-bizops-workspace/#h-7?)

### Receiving App Context Changes through the PubNub Chat SDK

The PubNub Chat SDK will expose App Context events through the family of [streamUpdates()](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/membership#get-updates?) APIs.

Some examples, taken from the [Chat SDK Demo app](https://github.com/PubNubDevelopers/Chat-SDK-Demo-Web) for web:

```js
//  Detect changes to the current User
useEffect(() => {
  return currentUser.streamUpdates(updatedUser => {
    if (updatedUser.name) {
      setName(updatedUser.name)
    }
    if (updatedUser.profileUrl) {
      setProfileUrl(updatedUser.profileUrl)
    }
  })
}, [currentUser])
```

```js
//  Detect changes to an array of Channels
useEffect(() => {
if (chat && privateGroups) {
    return Channel.streamUpdatesOn(privateGroups, channels => {
    //  The array of channels, privateGroups, has been updated
}
}, [chat, privateGroups])
```

For a worked example based on our simpler ‘getting stated’ sample for the Chat SDK, please refer to the article on [How to Manage Users and Channels with BizOps Workspace](https://www.pubnub.com/how-to/manage-users-and-channels-with-bizops-workspace/#h-10?)

App Context and PubNub Illuminate
---------------------------------

[PubNub Illuminate](https://www.pubnub.com/products/illuminate/?) is a real-time decisioning and analytics product that is customizable to an organization’s unique use case. The product is designed with the product managers and analysts in mind, allowing them to do the following:

-   Define custom real-time aggregated metrics.
-   Set up and deploy decision rules with conditions and actions.
-   Immediately visualize the metrics you’re tracking, the actions executed, and their outcome.

You can do all this in real time without pulling your engineering team away from their ongoing projects.

A full explanation of what PubNub Illuminte is, and how it can provide you with immediate actionable insights into your data, is outside the scope of this article, but please refer to our [documentation](https://www.pubnub.com/docs/illuminate/basics?) and [product overview](https://www.pubnub.com/blog/real-time-decisioning-with-illuminate/?) for more information.

In summary: You define **metrics** related to your application, i.e. things that you want to measure. For example, in an asset-tracking scenario, these might be Hours since the order was taken. When some [**condition**](https://www.pubnub.com/docs/illuminate/decisions/basics#conditions?) is met related to that metric, e.g., the ‘Hours since the order’ might exceed a certain value, then you can take some **action**.

Which [action](https://www.pubnub.com/docs/illuminate/decisions/basics#actions?) you take is flexible, but three of the possible actions relate to App Context:

![How-to - Use App Context - Image 02](https://www.pubnub.com/cdn/3prze68gbwl1/A2XZHFCSuF3nUxDjLDFjX/9b018c14ac44df085c2ad40b40619602/illuminate_app_context.png "How-to - Use App Context - Image 02")

### Update User with PubNub Illuminate

Allows you to set any predefined or custom user metadata. The screenshot below shows the User with ID 123 having their status set to the static value ‘New Status’ but it is also possible to set a dynamic value based on the **condition** that triggered the **action**.

![How-to - Use App Context - Image 03](https://www.pubnub.com/cdn/3prze68gbwl1/4Rx8xBy406xLFdGoA38Ll2/f7b62aa24fdba0df4cec6d035a8e5812/illuminate_app_context_user.png "How-to - Use App Context - Image 03")

### Update Channel with PubNub Illuminate

Allows you to set any predefined or custom channel metadata. The screenshot below shows the Channel with ID 123 having their name set to the static value ‘New Name’, but it is also possible to set a dynamic value based on the **condition** that triggered the **action**.

![How-to - Use App Context - Image 04](https://www.pubnub.com/cdn/3prze68gbwl1/5bVUjl1DTF1IENrhLv6T9v/b88e265164dce7dd1f39ed5437467611/illuminate_app_context_channel.png "How-to - Use App Context - Image 04")

### Update Memberships with PubNub Illuminate

Allows you to set any predefined or custom membership metadata. The screenshot below shows User ID 123’s membership of Channel 123 having its status set to the static value ‘New Status.’ It is also possible to set a dynamic value based on the **condition** that triggered the **action**.

![How-to - Use App Context - Image 05](https://www.pubnub.com/cdn/3prze68gbwl1/ZfrPMbbrj55hsyGpihCC3/44b519ccedde12e574bd44835ce799a3/illuminate_app_context_membership.png "How-to - Use App Context - Image 05")

App Context and PubNub Functions
--------------------------------

PubNub provides Functions to capture events that are happening on the PubNub Platform. Functions let you write code or leverage existing integrations to transform, reroute, augment, filter, and even aggregate data. Please see the [Functions documentation](https://www.pubnub.com/docs/serverless/functions/overview?) for a more thorough overview of PubNub Functions but this article will consider how PubNub Functions relate to App Context.

### Updating App Context from within PubNub Functions

The environment in which Functions run has access to the [PubNub Module](https://www.pubnub.com/docs/serverless/functions/functions-apis/pubnub-module?); this module has full access to the App Context on your keyset, and some examples taken from the documentation are given below. :

Example for [Get User App Context Metadata](https://www.pubnub.com/docs/serverless/functions/functions-apis/pubnub-module#get-user-metadata?)

```js
export default (event) => {
  const pubnub = require('pubnub');

  return pubnub.objects.getUUIDMetadata({
    uuid: 'my-uuid',
    include: {
      customFields: false,
    },
  })
  .then((resp) => {
    console.log(resp);
    return event.ok('Fetched UUID metadata successfully.');
  })
  .catch((err) => {
    console.log(err);
    return event.abort('Failed to fetch UUID metadata');
  });
};
```

Example for [Set Channel App Context Metadata](https://www.pubnub.com/docs/serverless/functions/functions-apis/pubnub-module#set-channel-metadata?)

```js
export default (event) => {
  const pubnub = require('pubnub');

  return pubnub.objects.setChannelMetadata({
    channel: 'my-channel',
    data: {
      name: 'channel-name',
      description: 'What a great channel',
      custom: {
        foo: 'bar',
      },
    },
    include: {
      customFields: false,
    },
  })
  .then((resp) => {
    console.log(resp);
    return event.ok('Set channel metadata successfully.');
  })
  .catch((error) => {
    console.log(err);
    return event.abort('Failed to set channel metadata.');
  });
};
```

For a comprehensive set of code examples, please refer to the documentation for the [PubNub Module](https://www.pubnub.com/docs/serverless/functions/functions-apis/pubnub-module?).

### Triggering a PubNub Function when App Context changes

There are numerous event types that can trigger a function, as detailed in the [Event Types documentation](https://www.pubnub.com/docs/serverless/functions/overview#event-types?). These include the ability to detect when messages and signals are sent, trigger functions after presence events occur, and execute Functions at a specified interval or on demand. At the time of writing, it is **not** possible to execute Functions after App Context updates, but if you find your application needs this, please contact our [support team](https://support.pubnub.com/hc/en-us?), who will be happy to walk through your use cases.

Next Steps
----------

To see App Context in action, you can check out our [Chat Demo](https://www.pubnub.com/demos/chat/?) that uses App Context alongside our Chat SDK to show what a chat app might look like with serverless storage. The Chat Demo allows you to set User and Channel metadata and see those changes propagate to other listeners and members in realtime.

Also, check out our related 3 part series on BizOps workspace which depends on App Context and covers how to: [Manage Users and Channels](https://www.pubnub.com/how-to/manage-users-and-channels-with-bizops-workspace/?), [Monitor and Moderate Conversations](https://www.pubnub.com/how-to/monitor-and-moderate-conversations-with-bizops-workspace/?), and [Securely Moderate Chat](https://www.pubnub.com/how-to/securely-moderate-chat-and-users/?).

Finally, feel free to reach out to the DevRel team at [devrel@pubnub.com](mailto:devrel@pubnub.com) or contact our [Support](https://support.pubnub.com/hc/en-us?) team for help with any aspect of your PubNub development.

How can PubNub help you?
========================

This article was originally published on [PubNub.com](https://www.pubnub.com/how-to/use-app-context/?)

Our platform helps developers build, deliver, and manage real-time interactivity for web apps, mobile apps, and IoT devices.

The foundation of our platform is the industry's largest and most scalable real-time edge messaging network. With over 15 points-of-presence worldwide supporting 800 million monthly active users, and 99.999% reliability, you'll never have to worry about outages, concurrency limits, or any latency issues caused by traffic spikes.

Experience PubNub
-----------------

Check out [Live Tour](https://www.pubnub.com/tour/introduction/?) to understand the essential concepts behind every PubNub-powered app in less than 5 minutes

Get Setup
---------

Sign up for a [PubNub account](https://admin.pubnub.com/signup/?) for immediate access to PubNub keys for free

Get Started
-----------

The [PubNub docs](https://www.pubnub.com/docs?) will get you up and running, regardless of your use case or [SDK](https://www.pubnub.com/docs?)