| name | push-notifications |
| description | Mobile push notification implementation and management |
| category | mobile-development |
| difficulty | intermediate |
| tags | ["mobile","notifications","firebase","apns"] |
| author | OpenCode Community |
| version | 1 |
| last_updated | 2024-01-15T00:00:00.000Z |
Push Notifications
What I Do
I am Push Notifications, a system for delivering time-sensitive messages to mobile devices even when the app is not running. I enable apps to re-engage users with relevant content, alerts, and updates through APNs (Apple Push Notification service) on iOS and Firebase Cloud Messaging on Android. I handle device token registration, notification payload construction, and delivery management. I support rich notifications with images, actions, and custom UI. I integrate with backend services for targeted messaging based on user behavior, demographics, or segments. I provide analytics on delivery rates, open rates, and user engagement. I respect user preferences and permission models, allowing users to opt in or out of notification categories.
When to Use Me
- Re-engaging users with timely updates
- Sending time-sensitive alerts (orders, appointments)
- Breaking news and content updates
- Social interactions and activity notifications
- Marketing campaigns and promotions
- Transactional notifications (payments, shipping)
- Reminders and to-do items
- Cross-platform user communication
- Silent notifications for background updates
Core Concepts
Device Tokens: Unique identifiers for each app installation, used to route notifications to specific devices.
Notification Payload: JSON structure containing notification content and configuration options.
Notification Categories: User-configurable groupings for notification preferences.
Rich Notifications: Notifications with images, videos, and custom UI extensions.
Silent Notifications: Background notifications without user-facing alerts for data sync.
Action Buttons: Custom actions from notifications (reply, acknowledge, open).
Local vs Remote: Local notifications scheduled within the app vs remote notifications from servers.
Code Examples
Example 1: Push Notification Setup (React Native)
import messaging from '@react-native-firebase/messaging'
import { Permissions, Platform } from 'react-native'
class NotificationService {
async requestPermission(): Promise<boolean> {
try {
const authStatus = await messaging().requestPermission()
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL
if (enabled) {
console.log('Push notification permission granted')
return true
}
console.log('Push notification permission denied')
return false
} catch (error) {
console.error('Permission request error:', error)
return false
}
}
async getDeviceToken(): Promise<string | null> {
{
hasPermission = .()
(!hasPermission) {
.()
}
token = ().()
.(, token)
token
} (error) {
.(, error)
}
}
(): <> {
authStatus = ().()
(
authStatus === messaging.. ||
authStatus === messaging..
)
}
(: ): <> {
{
().(topic)
.()
} (error) {
.(, error)
}
}
(: ): <> {
{
().(topic)
.()
} (error) {
.(, error)
}
}
}
notificationService = ()
Example 2: Notification Handling and Foreground Handling
import messaging from '@react-native-firebase/messaging'
import { AppRegistry } from 'react-native'
import { navigationRef } from './navigation'
class NotificationHandler {
initialize(): void {
messaging().onMessage(async (remoteMessage) => {
console.log('Foreground notification received:', remoteMessage)
this.showLocalNotification(remoteMessage)
})
messaging().setBackgroundMessageHandler(async (remoteMessage) => {
console.log('Background notification received:', remoteMessage)
this.handleBackgroundNotification(remoteMessage)
})
messaging().getInitialNotification().then((remoteMessage) => {
if (remoteMessage) {
console.log('App opened from notification:', remoteMessage)
.(remoteMessage)
}
})
().( {
.(, remoteMessage)
.(remoteMessage)
})
}
(: messaging.): {
: = {
: remoteMessage. || .().(),
: remoteMessage.?. || ,
: remoteMessage.?. || ,
: remoteMessage.,
}
}
(: messaging.): {
(remoteMessage.?. === ) {
.(remoteMessage.)
}
}
(: messaging.): {
{ screen, params } = .(remoteMessage.)
(navigationRef.()) {
navigationRef.(screen, params)
}
}
(: <, >): { : ; : } {
screen = data?. ||
params = { ...data }
params.
{ screen, params }
}
(: <, >): {
.(, data)
}
}
notificationHandler = ()
Example 3: Backend Notification Service (Node.js)
import admin from 'firebase-admin'
interface NotificationPayload {
token: string
title: string
body: string
data?: Record<string, string>
imageUrl?: string
actions?: NotificationAction[]
channelId?: string
priority?: 'high' | 'normal'
ttl?: number
}
interface NotificationAction {
action: string
title: string
icon?: string
foreground?: boolean
authenticationRequired?: boolean
}
class FirebaseNotificationService {
private admin: admin.app.App
constructor() {
this.admin = admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
})
}
(: ): <> {
: admin.. = {
: payload.,
: {
: payload.,
: payload.,
: payload.,
},
: payload. || {},
: {
: payload. === ? : ,
: {
: payload. || ,
: ,
: ,
},
},
: {
: {
: {
: ,
: payload.?. ? : ,
},
},
: {
: payload.,
},
},
}
(payload. && payload.. > ) {
message.!.!. = payload..( ({
: action.,
: action.,
: action.,
...(action. && { : }),
}))
message.!.!.!. =
}
{
response = ..().(message)
.(, response)
response
} (error) {
.(, error)
error
}
}
(
: [],
: ,
: ,
?: <, >
): <admin..> {
: admin.. = {
tokens,
: { title, body },
: data || {},
}
..().(message)
}
(
: ,
: ,
: ,
?: <, >
): <> {
: admin.. = {
topic,
: { title, body },
: data || {},
}
..().(message)
}
}
firebaseNotificationService = ()
Example 4: Notification Categories and Actions (iOS)
import UserNotifications
struct NotificationCategory {
static let messages = "MESSAGES"
static let orders = "ORDERS"
static let reminders = "REMINDERS"
}
struct NotificationAction {
static let reply = "REPLY_ACTION"
static let view = "VIEW_ACTION"
static let dismiss = "DISMISS_ACTION"
static let accept = "ACCEPT_ACTION"
static let decline = "DECLINE_ACTION"
}
class NotificationManager {
static let shared = NotificationManager()
private init() {}
func registerCategories() {
let messagesCategory = UNNotificationCategory(
identifier: NotificationCategory.messages,
actions: [
(
identifier: .reply,
title: ,
options: [.foreground]
),
(
identifier: .view,
title: ,
options: [.foreground]
),
(
identifier: .dismiss,
title: ,
options: [.destructive]
)
],
intentIdentifiers: [],
options: []
)
ordersCategory (
identifier: .orders,
actions: [
(
identifier: .view,
title: ,
options: [.foreground]
),
(
identifier: .dismiss,
title: ,
options: [.destructive]
)
],
intentIdentifiers: [],
options: []
)
remindersCategory (
identifier: .reminders,
actions: [
(
identifier: .accept,
title: ,
options: [.foreground]
),
(
identifier: .decline,
title: ,
options: [.destructive]
)
],
intentIdentifiers: [],
options: []
)
.current().setNotificationCategories([
messagesCategory,
ordersCategory,
remindersCategory
])
}
}
Example 5: Local Notifications
import PushNotification from 'react-native-push-notification'
class LocalNotificationService {
configure(): void {
PushNotification.configure({
onRegister: (token) => {
console.log('Local notification token:', token)
},
onNotification: (notification) => {
console.log('Local notification received:', notification)
this.handleNotificationAction(notification)
},
onAction: (notification) => {
console.log('Notification action:', notification.action)
this.handleNotificationAction(notification)
},
permissions: {
alert: true,
badge: true,
sound: true,
},
popInitialNotification: true,
requestPermissions: true,
})
}
createChannel(): void {
.(
{
: ,
: ,
: ,
: ,
: ,
: ,
},
.()
)
.(
{
: ,
: ,
: ,
: ,
: ,
: ,
},
.()
)
}
(
: ,
: ,
: ,
: ,
?:
): {
.({
id,
title,
: body,
date,
: ,
: ,
: data || {},
: ,
: ,
})
}
(
: ,
: ,
: ,
?:
): {
.({
: id,
: title,
: body,
: ,
: ,
: data || {},
})
}
(: ): {
.(id)
}
(): {
.()
}
(: ): {
.(count)
}
(: ): {
(notification. === ) {
.(notification)
} (notification. === ) {
.(notification)
}
}
(: ): {
.(, notification.?.)
}
(: ): {
{ screen, params } = .(notification.)
}
}
localNotificationService = ()
Best Practices
- Request notification permission early but not immediately on launch
- Provide clear value proposition for enabling notifications
- Respect user notification preferences and categories
- Use silent notifications sparingly for background sync only
- Implement notification grouping on iOS for better UX
- Provide notification center management on Android
- Use appropriate notification importance levels on Android
- Test notifications on real devices before release
- Monitor delivery and open rates for optimization
- Implement proper analytics for notification performance
Core Competencies
- APNs and Firebase Cloud Messaging integration
- Device token management
- Notification payload construction
- Rich notifications with actions
- Notification channels (Android)
- Notification categories (iOS)
- Silent background notifications
- Local notifications scheduling
- Notification analytics and tracking
- Permission management
- Deep linking from notifications
- Notification extensions
- Badge management
- Sound and vibration control
- Cross-platform implementation