Notifications API Implementation on Website
Push notifications in the browser without mobile app. User allowed — receives notifications even when tab is closed (with Service Worker). User didn't allow — use fallback in UI.
Notifications API and Push API are different. Notifications API shows notification via browser. Push API delivers event from server. For notifications with closed tab, need both.
Request Permission
Key rule — ask for permission only after explicit user action, otherwise browser automatically blocks:
async function requestNotificationPermission(): Promise<NotificationPermission> {
if (!('Notification' in window)) {
throw new Error('Notifications API not supported')
}
if (Notification.permission === 'granted') return 'granted'
if (Notification.permission === 'denied') return 'denied'
// Call only from event handler (click, submit, etc.)
return Notification.requestPermission()
}
Show Notification
interface NotificationOptions {
title: string
body?: string
icon?: string
badge?: string
tag?: string // Grouping — new notification replaces old with same tag
requireInteraction?: boolean // Don't auto-close
data?: unknown
actions?: NotificationAction[] // Buttons (Service Worker only)
}
function showNotification(options: NotificationOptions): Notification | null {
if (Notification.permission !== 'granted') return null
const { title, ...rest } = options
const notification = new Notification(title, rest)
notification.onclick = (event) => {
event.preventDefault()
window.focus()
notification.close()
// Navigate to relevant section by notification.data
}
return notification
}
Notifications via Service Worker
For closed tab notifications — only via SW:
// service-worker.ts
self.addEventListener('push', (event: PushEvent) => {
const data = event.data?.json() ?? {}
event.waitUntil(
self.registration.showNotification(data.title ?? 'New notification', {
body: data.body,
icon: '/icons/notification-icon-192.png',
badge: '/icons/badge-72.png',
tag: data.tag ?? 'default',
data: { url: data.url },
actions: [
{ action: 'open', title: 'Open' },
{ action: 'dismiss', title: 'Close' },
],
})
)
})
self.addEventListener('notificationclick', (event: NotificationEvent) => {
event.notification.close()
if (event.action === 'dismiss') return
const url = event.notification.data?.url ?? '/'
event.waitUntil(
clients.matchAll({ type: 'window' }).then((windowClients) => {
const existingClient = windowClients.find((c) => c.url === url)
if (existingClient) return existingClient.focus()
return clients.openWindow(url)
})
)
})
React Hook
function useNotifications() {
const [permission, setPermission] = useState<NotificationPermission>(
typeof Notification !== 'undefined' ? Notification.permission : 'denied'
)
const [supported] = useState(() => 'Notification' in window)
const request = useCallback(async () => {
if (!supported) return
const result = await requestNotificationPermission()
setPermission(result)
}, [supported])
const notify = useCallback(
(options: NotificationOptions) => {
if (permission !== 'granted') return null
return showNotification(options)
},
[permission]
)
return { supported, permission, request, notify }
}
Permission State Handling in UI
function NotificationSettings() {
const { supported, permission, request, notify } = useNotifications()
if (!supported) {
return <p>Notifications not supported by your browser</p>
}
return (
<div>
{permission === 'default' && (
<button onClick={request}>Enable notifications</button>
)}
{permission === 'granted' && (
<button onClick={() => notify({ title: 'Test', body: 'Notifications work' })}>
Test
</button>
)}
{permission === 'denied' && (
<p>Notifications blocked. Allow in browser settings.</p>
)}
</div>
)
}
What's Involved
Implement permission request and notification showing utilities, React hook, handle all states (default, granted, denied), optionally integrate with Service Worker for Push API and VAPID keys on backend.
Timeline: 0.5–1 day (without Push API). With Push API and backend setup — 1–2 days.







