Name:
interface
Value:
Amplify has re-imagined the way frontend developers build fullstack applications. Develop and deploy without the hassle.

Page updated Jul 1, 2024

Subscribe to real-time events

In this guide, we will outline the benefits of enabling real-time data integrations and how to set up and filter these subscriptions. We will also cover how to unsubscribe from subscriptions.

Before you begin, you will need:

With versions of Amplify CLI @aws-amplify/cli@12.12.2 and API Category@aws-amplify/amplify-category-api@5.11.5, an improvement was made to how relational field data is handled in subscriptions when different authorization rules apply to related models in a schema. The improvement redacts the values for the relational fields, displaying them as null or empty, to prevent unauthorized access to relational data. This redaction occurs whenever it cannot be determined that the child model will be protected by the same permissions as the parent model.

Because subscriptions are tied to mutations and the selection set provided in the result of a mutation is then passed through to the subscription, relational fields in the result of mutations must be redacted.

If an authorized end-user needs access to the redacted relational field they should perform a query to read the relational data.

Additionally, subscriptions will inherit related authorization when relational fields are set as required. To better protect relational data, consider modifying the schema to use optional relational fields.

Based on the security posture of your application, you can choose to revert to the subscription behavior before this improvement was made.

To do so, use the subscriptionsInheritPrimaryAuth feature flag under graphqltransformer in the amplify/backend/cli.json file.

  • If enabled, subscriptions will inherit the primary model authorization rules for the relational fields.
  • If disabled, relational fields will be redacted in mutation response when there is a difference between auth rules between primary and related models.

Set up a real-time subscription

Subscriptions is a GraphQL feature that allows the server to send data to its clients when a specific event happens. For example, you can subscribe to an event when a new record is created, updated, or deleted through the API. You can enable real-time data integration in your app with a subscription.

import { generateClient } from 'aws-amplify/api';
import * as subscriptions from './graphql/subscriptions';
const client = generateClient();
// Subscribe to creation of Todo
const createSub = client
.graphql({ query: subscriptions.onCreateTodo })
.subscribe({
next: ({ data }) => console.log(data),
error: (error) => console.warn(error)
});
// Subscribe to update of Todo
const updateSub = client
.graphql({ query: subscriptions.onUpdateTodo })
.subscribe({
next: ({ data }) => console.log(data),
error: (error) => console.warn(error)
});
// Subscribe to deletion of Todo
const deleteSub = client
.graphql({ query: subscriptions.onDeleteTodo })
.subscribe({
next: ({ data }) => console.log(data),
error: (error) => console.warn(error)
});
// Stop receiving data updates from the subscription
createSub.unsubscribe();
updateSub.unsubscribe();
deleteSub.unsubscribe();

Set up server-side subscription filters

Subscriptions take an optional filter argument to define service-side subscription filters:

import { generateClient } from 'aws-amplify/api';
const client = generateClient();
const variables = {
filter: {
// Only receive Todo messages where the "type" field is "Personal"
type: { eq: 'Personal' }
}
};
const sub = client
.graphql({
query: subscriptions.onCreateTodo,
variables
})
.subscribe({
next: ({ data }) => console.log(data),
error: (error) => console.warn(error)
});

If you want to get all subscription events, don't specify any filter parameters.

Limitations:

  • Specifying an empty object {} as a filter is not recommended. Using {} as a filter might cause inconsistent behavior based on your data model's authorization rules.
  • If you are using dynamic group authorization and you authorize based on a single group per record, subscriptions are only supported if the user is part of five or fewer user groups.
  • Additionally, if you authorize by using an array of groups (groups: [String]),
    • subscriptions are only supported if the user is part of 20 or fewer groups
    • you can only authorize 20 or fewer user groups per record

Subscription connection status updates

Now that your application is set up and using subscriptions, you may want to know when the subscription is finally established, or reflect to your users when the subscription isn't healthy. You can monitor the connection state for changes through the Hub local eventing system.

import { CONNECTION_STATE_CHANGE, ConnectionState } from 'aws-amplify/api';
import { Hub } from 'aws-amplify/utils';
Hub.listen('api', (data: any) => {
const { payload } = data;
if (payload.event === CONNECTION_STATE_CHANGE) {
const connectionState = payload.data.connectionState as ConnectionState;
console.log(connectionState);
}
});

Subscription connection states

  • Connected - Connected and working with no issues.
  • ConnectedPendingDisconnect - The connection has no active subscriptions and is disconnecting.
  • ConnectedPendingKeepAlive - The connection is open, but has missed expected keep-alive messages.
  • ConnectedPendingNetwork - The connection is open, but the network connection has been disrupted. When the network recovers, the connection will continue serving traffic.
  • Connecting - Attempting to connect.
  • ConnectionDisrupted - The connection is disrupted and the network is available.
  • ConnectionDisruptedPendingNetwork - The connection is disrupted and the network connection is unavailable.
  • Disconnected - Connection has no active subscriptions and is disconnecting.
Troubleshooting
Troubleshooting connection issues and automated reconnection

Connections between your application and backend subscriptions can be interrupted for various reasons, including network outages or the device entering sleep mode. Your subscriptions will automatically reconnect when it becomes possible to do so.

While offline, your application will miss messages and will not automatically catch up when reconnected. Depending on your use case, you may want to take action for your app to catch up when it comes back online.

import { generateClient, CONNECTION_STATE_CHANGE, ConnectionState } from 'aws-amplify/api'
import { Hub } from 'aws-amplify/utils'
const client = generateClient()
const fetchRecentData = () => {
// Retrieve some/all data from AppSync
const allTodos = await client.graphql({ query: queries.listTodos });
}
let priorConnectionState: ConnectionState;
Hub.listen("api", (data: any) => {
const { payload } = data;
if (
payload.event === CONNECTION_STATE_CHANGE
) {
if (priorConnectionState === ConnectionState.Connecting && payload.data.connectionState === ConnectionState.Connected) {
fetchRecentData();
}
priorConnectionState = payload.data.connectionState;
}
});
const createSub = client.graphql(
{ query: subscriptions.onCreateTodo }
).subscribe({
next: payload => // Process incoming messages
});
const updateSub = client.graphql(
{ query: subscriptions.onUpdateTodo }
).subscribe({
next: payload => // Process incoming messages
});
const deleteSub = client.graphql(
{ query: subscriptions.onDeleteTodo }
).subscribe({
next: payload => // Process incoming messages
});
const cleanupSubscriptions = () => {
createSub.unsubscribe();
updateSub.unsubscribe();
deleteSub.unsubscribe();
}

Create a custom GraphQL subscription by ID

This brief walkthrough provides additional step-by-step guidance for creating a custom GraphQL subscription that will only be connected and triggered by a mutation containing a specific ID as an argument. Take, for example, the following GraphQL schema:

type Post @model @auth(rules: [{ allow: public }]) {
id: ID!
title: String!
content: String
comments: [Comment] @hasMany
}
type Comment @model @auth(rules: [{ allow: public }]) {
id: ID!
content: String
}

By default, subscriptions will be created for the following mutations:

# Post type
onCreatePost
onUpdatePost
onDeletePost
# Comment type
onCreateComment
onUpdateComment
onDeleteComment

One operation that is not covered is how to subscribe to comments for only a single, specific post.

Because the schema has a one-to-many relationship enabled between posts and comments, you can use the auto-generated field postCommentsId, which defines the relationship, to set this up in a new Subscription.

To implement this, update the schema with the following:

type Post @model @auth(rules: [{ allow: public }]) {
id: ID!
title: String!
content: String
comments: [Comment] @hasMany
}
type Comment @model @auth(rules: [{ allow: public }]) {
id: ID!
content: String
postCommentsId: ID!
}
type Subscription {
onCommentByPostId(postCommentsId: ID!): Comment
@aws_subscribe(mutations: ["createComment"])
}

Now you can create a custom subscription for comment creation with a specific post ID:

import { generateClient } from 'aws-amplify/api';
import { onCommentByPostId } from './graphql/subscriptions';
const client = generateClient();
client
.graphql({
query: onCommentByPostId,
variables: {
postCommentsId: '12345'
}
})
.subscribe({
next: (data) => {
console.log('data: ', data);
}
});

Unsubscribe from a subscription

You can also unsubscribe from events by using subscriptions by implementing the following:

// Stop receiving data updates from the subscription
sub.unsubscribe();

Conclusion

Congratulations! You have finished the Subscribe to real-time events guide. In this guide, you set up subscriptions for real-time events and learned how to filter and cancel these subscriptions when needed.

Next steps

Our recommended next steps include continuing to build out and customize your information architecture for your data. Some resources that will help with this work include: