Push notifications and in-app messaging with support for Amazon Pinpoint. Provides comprehensive notification capabilities including push notifications for mobile apps and in-app messaging for enhanced user engagement.
Send and manage push notifications to mobile devices and web browsers.
import {
initializePushNotifications, requestPermissions,
onNotificationReceived, onNotificationOpened
} from "aws-amplify/push-notifications";For Pinpoint-specific functionality:
import {
initializePushNotifications, requestPermissions,
onNotificationReceived, onNotificationOpened
} from "aws-amplify/push-notifications/pinpoint";Initialize and configure push notifications.
/**
* Initialize push notifications service
* @returns Promise that resolves when initialization is complete
*/
function initializePushNotifications(): Promise<void>;
/**
* Request notification permissions from the user
* @returns Promise with permission status
*/
function requestPermissions(): Promise<boolean>;
/**
* Get current notification permissions status
* @returns Promise with current permission state
*/
function getPermissionStatus(): Promise<NotificationPermissionStatus>;
type NotificationPermissionStatus = 'granted' | 'denied' | 'default';Setup Example:
import {
initializePushNotifications,
requestPermissions
} from "aws-amplify/push-notifications";
// Initialize push notifications
await initializePushNotifications();
// Request permissions
const hasPermission = await requestPermissions();
if (hasPermission) {
console.log('Push notifications enabled');
} else {
console.log('Push notifications permission denied');
}Handle incoming push notifications and user interactions.
/**
* Listen for push notifications received in foreground
* @param handler - Function to handle received notifications
* @returns Unsubscribe function
*/
function onNotificationReceived(
handler: (notification: PushNotificationMessage) => void
): () => void;
/**
* Listen for notification tap/click events
* @param handler - Function to handle notification opens
* @returns Unsubscribe function
*/
function onNotificationOpened(
handler: (notification: PushNotificationMessage) => void
): () => void;
interface PushNotificationMessage {
title?: string;
body?: string;
imageUrl?: string;
data?: Record<string, string>;
options?: {
badge?: number;
sound?: string;
tag?: string;
icon?: string;
actions?: NotificationAction[];
};
}
interface NotificationAction {
id: string;
title: string;
destructive?: boolean;
textInput?: boolean;
}Event Handling Examples:
import {
onNotificationReceived,
onNotificationOpened
} from "aws-amplify/push-notifications";
// Handle notifications received while app is open
const unsubscribeReceived = onNotificationReceived((notification) => {
console.log('Notification received:', notification.title);
// Show in-app notification or update UI
if (notification.data?.type === 'message') {
showInAppMessage(notification.body);
}
});
// Handle notification taps
const unsubscribeOpened = onNotificationOpened((notification) => {
console.log('Notification opened:', notification.title);
// Navigate to relevant screen
if (notification.data?.screen) {
navigateToScreen(notification.data.screen);
}
});
// Cleanup when component unmounts
// unsubscribeReceived();
// unsubscribeOpened();Manage device tokens for push notification targeting.
/**
* Get the current device token
* @returns Promise with device token
*/
function getDeviceToken(): Promise<string>;
/**
* Register device token with Pinpoint
* @param token - Device token to register
* @returns Promise when registration is complete
*/
function registerDevice(token?: string): Promise<void>;
/**
* Update device attributes and user data
* @param attributes - Device and user attributes
* @returns Promise when update is complete
*/
function updateDeviceAttributes(
attributes: DeviceAttributes
): Promise<void>;
interface DeviceAttributes {
address?: string;
attributes?: Record<string, string[]>;
demographic?: {
appVersion?: string;
locale?: string;
make?: string;
model?: string;
modelVersion?: string;
platform?: string;
platformVersion?: string;
timezone?: string;
};
location?: {
city?: string;
country?: string;
latitude?: number;
longitude?: number;
postalCode?: string;
region?: string;
};
metrics?: Record<string, number>;
optOut?: 'ALL' | 'NONE';
user?: {
userId?: string;
userAttributes?: Record<string, string[]>;
};
}Token Management Example:
import {
getDeviceToken,
registerDevice,
updateDeviceAttributes
} from "aws-amplify/push-notifications";
// Get and register device token
const token = await getDeviceToken();
await registerDevice(token);
// Update device information
await updateDeviceAttributes({
address: token,
attributes: {
interests: ['technology', 'gaming'],
preferences: ['push_notifications']
},
demographic: {
appVersion: '2.1.0',
platform: 'iOS',
locale: 'en-US'
},
user: {
userId: 'user123',
userAttributes: {
name: ['John Doe'],
email: ['john@example.com']
}
}
});Display contextual messages within your application.
import {
initializeInAppMessaging,
syncMessages,
displayMessage,
clearDisplayedMessages
} from "aws-amplify/in-app-messaging";For Pinpoint-specific functionality:
import {
initializeInAppMessaging,
syncMessages,
displayMessage
} from "aws-amplify/in-app-messaging/pinpoint";Initialize and configure in-app messaging.
/**
* Initialize in-app messaging service
* @returns Promise that resolves when initialization is complete
*/
function initializeInAppMessaging(): Promise<void>;
/**
* Sync messages from the server
* @returns Promise that resolves when sync is complete
*/
function syncMessages(): Promise<void>;
/**
* Check for available messages and display them
* @returns Promise that resolves when check is complete
*/
function displayMessage(): Promise<void>;
/**
* Clear all displayed messages from local storage
* @returns Promise that resolves when clearing is complete
*/
function clearDisplayedMessages(): Promise<void>;In-App Messaging Setup:
import {
initializeInAppMessaging,
syncMessages,
displayMessage
} from "aws-amplify/in-app-messaging";
// Initialize in-app messaging
await initializeInAppMessaging();
// Sync messages from server (typically done periodically)
await syncMessages();
// Display appropriate messages
await displayMessage();Handle in-app message lifecycle events.
/**
* Listen for in-app message events
* @param eventType - Type of event to listen for
* @param handler - Event handler function
* @returns Unsubscribe function
*/
function onMessageEvent(
eventType: InAppMessageEventType,
handler: (message: InAppMessage) => void
): () => void;
type InAppMessageEventType =
| 'messageReceived'
| 'messageDisplayed'
| 'messageActionTaken'
| 'messageDismissed';
interface InAppMessage {
id: string;
campaignId?: string;
treatmentId?: string;
content?: InAppMessageContent;
layout?: InAppMessageLayout;
customData?: Record<string, string>;
}
interface InAppMessageContent {
header?: {
content: string;
textColor?: string;
};
body?: {
content: string;
textColor?: string;
};
imageUrl?: string;
primaryButton?: MessageButton;
secondaryButton?: MessageButton;
}
interface MessageButton {
text: string;
action: 'CLOSE' | 'DEEP_LINK' | 'LINK';
url?: string;
}
type InAppMessageLayout = 'BANNER' | 'MODAL' | 'FULL_SCREEN' | 'CAROUSEL';Event Handling Example:
import { onMessageEvent } from "aws-amplify/in-app-messaging";
// Handle message display
const unsubscribeDisplayed = onMessageEvent('messageDisplayed', (message) => {
console.log('Message displayed:', message.id);
// Track message impression
trackEvent('message_impression', {
messageId: message.id,
campaignId: message.campaignId
});
});
// Handle message actions
const unsubscribeAction = onMessageEvent('messageActionTaken', (message) => {
console.log('Message action taken:', message.id);
// Handle button clicks or deep links
if (message.content?.primaryButton?.action === 'DEEP_LINK') {
const url = message.content.primaryButton.url;
navigateToDeepLink(url);
}
});
// Handle message dismissal
const unsubscribeDismissed = onMessageEvent('messageDismissed', (message) => {
console.log('Message dismissed:', message.id);
});Control when and how messages are displayed.
/**
* Set user attributes for message targeting
* @param attributes - User attributes for targeting
* @returns Promise when attributes are updated
*/
function setUserAttributes(
attributes: Record<string, string[]>
): Promise<void>;
/**
* Record custom events for message triggering
* @param eventType - Event type name
* @param properties - Event properties
* @returns Promise when event is recorded
*/
function recordEvent(
eventType: string,
properties?: Record<string, string>
): Promise<void>;Targeting Examples:
import { setUserAttributes, recordEvent } from "aws-amplify/in-app-messaging";
// Set user attributes for targeting
await setUserAttributes({
userLevel: ['premium'],
interests: ['technology', 'gaming'],
region: ['us-west-2']
});
// Record events that trigger messages
await recordEvent('product_viewed', {
productId: 'prod123',
category: 'electronics',
price: '299.99'
});
// Record user milestones
await recordEvent('level_completed', {
level: '5',
score: '1500'
});Override default message display with custom implementations.
/**
* Set custom message handler for displaying messages
* @param handler - Custom display handler
*/
function setMessageDisplayHandler(
handler: (message: InAppMessage) => Promise<boolean>
): void;
/**
* Manually dismiss a displayed message
* @param messageId - ID of message to dismiss
* @returns Promise when dismissal is complete
*/
function dismissMessage(messageId: string): Promise<void>;Custom Handler Example:
import {
setMessageDisplayHandler,
dismissMessage
} from "aws-amplify/in-app-messaging";
// Set custom message display logic
setMessageDisplayHandler(async (message) => {
// Custom logic to determine if message should be shown
if (shouldDisplayMessage(message)) {
// Display with custom UI
const dismissed = await showCustomMessage(message);
if (dismissed) {
await dismissMessage(message.id);
}
return true; // Message was handled
}
return false; // Message was not handled
});
function shouldDisplayMessage(message: InAppMessage): boolean {
// Custom logic based on app state, user preferences, etc.
return !isUserInCall() && !hasRecentlyDismissed(message.id);
}// Notification configuration
interface NotificationConfig {
Pinpoint?: {
appId: string;
region: string;
};
}
// Platform-specific notification options
interface PlatformNotificationOptions {
iOS?: {
badge?: number;
sound?: string;
threadId?: string;
categoryId?: string;
};
android?: {
channelId?: string;
smallIcon?: string;
largeIcon?: string;
color?: string;
priority?: 'min' | 'low' | 'default' | 'high' | 'max';
};
web?: {
icon?: string;
badge?: string;
image?: string;
tag?: string;
requireInteraction?: boolean;
};
}
// Error types
class NotificationError extends Error {
name: 'NotificationError';
message: string;
cause?: Error;
}
class PushNotificationError extends NotificationError {
name: 'PushNotificationError';
code?: string;
}
class InAppMessagingError extends NotificationError {
name: 'InAppMessagingError';
messageId?: string;
}Notification operations can encounter various errors:
import {
initializePushNotifications,
NotificationError
} from "aws-amplify/push-notifications";
try {
await initializePushNotifications();
} catch (error) {
if (error instanceof NotificationError) {
switch (error.name) {
case 'PermissionDeniedError':
console.log('Notifications permission denied');
// Prompt user to enable in settings
break;
case 'UnsupportedPlatformError':
console.log('Push notifications not supported on this platform');
break;
case 'ConfigurationError':
console.log('Invalid notification configuration');
break;
default:
console.log('Notification error:', error.message);
break;
}
} else {
console.log('Unexpected error:', error);
}
}