PubNub 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, Functions, and other PubNub services to make smarter decisions. You can also manage this data through an intuitive, no-code interface with BizOps Workspace.
What is App Context?
App Context (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.
App Context provides a set of suggested fields for your Users and Channels, as well as suggested fields for the Memberships 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.
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:
- Log into the Admin Portal
- Click on the ‘Apps’ tab on the left-hand side of the portal
- Click on an application. You will be brought to the keysets page for this application.
- 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
- Enable App Context by clicking the slider
- 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.
- 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.
- When the Membership Events setting is enabled, membership events are triggered when memberships are added, updated, or removed, as discussed later.
- The remaining options are out of scope for this article, but please refer to the App Context documentation for more information
- 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 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.
- Users can be created and managed using BizOps Workspace, 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
- APIs are exposed through each of our SDKs to create Users. If you are using our Chat SDK, then this SDK handles app context for you behind the scenes; for example, the Chat SDK 'createUser()' method will call JavaScript's setUUIDMetadata 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 API, but there are equivalents for all our APIs, including Java, Swift, Kotlin, Python, Unity, 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.
- Channels can be created and managed using BizOps Workspace. 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
- APIs are exposed through each of our SDKs to create Channels. If you are using our Chat SDK, then this handles app context for you behind the scenes; for example, the family of 'Create channel' methods will call JavaScript's setChannelMetadata() 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, Java, Swift, Kotlin, Python, Unity, 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' 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 to prevent unauthorized access.
How do I create a Membership?
Similar to Users and Channels, there are two ways to create a Membership.
- Memberships can be created and managed using BizOps Workspace without writing code. Please see the Manage Membership section of our documentation for more details.
- APIs are exposed through each of our SDKs to create Channels. If you are using our Chat SDK, then this handles app context for you behind the scenes; for example, the family of 'Create channel' methods will call JavaScript's setMemberships 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, Java, Swift, Kotlin, Python, Unity, 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. 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, registering for App Context events will look as follows:
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, Swift, Kotlin, Python (Note that Python calls the events ‘metadata’, whereas other SDKs refer to the events as ‘objects’), Unity, etc.
For a worked example and interactive demo, please refer to the article on How to Manage Users and Channels with BizOps Workspace
Receiving App Context Changes through the PubNub Chat SDK
The PubNub Chat SDK will expose App Context events through the family of streamUpdates() APIs.
Some examples, taken from the Chat SDK Demo app for web:
// Detect changes to the current User
useEffect(() => {
return currentUser.streamUpdates(updatedUser => {
if (updatedUser.name) {
setName(updatedUser.name)
}
if (updatedUser.profileUrl) {
setProfileUrl(updatedUser.profileUrl)
}
})
}, [currentUser])
// 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
App Context and PubNub Illuminate
PubNub 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 and product overview 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 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 you take is flexible, but three of the possible actions relate to App Context:
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.
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.
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.
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 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; 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
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
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.
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. 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, 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 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, Monitor and Moderate Conversations, and Securely Moderate Chat.
Finally, feel free to reach out to the DevRel team at devrel@pubnub.com or contact our Support team for help with any aspect of your PubNub development.
How can PubNub help you?
This article was originally published on PubNub.com
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 to understand the essential concepts behind every PubNub-powered app in less than 5 minutes
Get Setup
Sign up for a PubNub account for immediate access to PubNub keys for free
Get Started
The PubNub docs will get you up and running, regardless of your use case or SDK
Top comments (0)