Rooks
Browser APIs

useNotification

Requests permission and sends desktop notifications via the Notifications API.

About

React hook for sending browser notifications with permission handling using the Notifications API.

Installation

npm install rooks

Usage

import { useState } from "react";
import { useNotification } from "rooks";

function NotificationDemo() {
  const { show, permission, requestPermission, isSupported } =
    useNotification();
  const [title, setTitle] = useState("");
  const [body, setBody] = useState("");

  const handleRequestPermission = async () => {
    const result = await requestPermission();
    if (result === "granted") {
      console.log("Permission granted!");
    } else {
      console.log("Permission denied");
    }
  };

  const handleShowNotification = async () => {
    if (permission === "granted") {
      await show(title, {
        body: body,
        icon: "/logo192.png",
        tag: "demo-notification",
        requireInteraction: false,
      });
    }
  };

  if (!isSupported) {
    return <div>Notifications not supported in this browser</div>;
  }

  return (
    <div>
      <h2>Browser Notifications</h2>
      <p>
        Current permission: <strong>{permission}</strong>
      </p>

      {permission === "default" && (
        <div>
          <p>You need to grant permission to show notifications</p>
          <button onClick={handleRequestPermission}>Request Permission</button>
        </div>
      )}

      {permission === "granted" && (
        <div>
          <input
            placeholder="Notification title"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
          />
          <input
            placeholder="Notification body"
            value={body}
            onChange={(e) => setBody(e.target.value)}
          />
          <button onClick={handleShowNotification}>Show Notification</button>
        </div>
      )}

      {permission === "denied" && (
        <p>
          Permission denied. Please enable notifications in browser settings.
        </p>
      )}
    </div>
  );
}

Another Example

import { useNotification } from "rooks";

function PresetNotification() {
  const { permission, requestPermission, show, isSupported } =
    useNotification();

  if (!isSupported) {
    return <p>Your browser does not support notifications.</p>;
  }

  return (
    <div>
      <p>Permission: {permission}</p>
      <button onClick={requestPermission}>Enable notifications</button>
      <button
        onClick={() =>
          show("Build finished", {
            body: "Your latest batch of examples is ready for review.",
            tag: "batch-ready",
          })
        }
      >
        Send preset notification
      </button>
    </div>
  );
}

Return Value

Returns an object with the following properties:

PropertyTypeDescription
show(title: string, options?: NotificationOptions) => Promise<Notification | null>Show a notification
permission"default" | "granted" | "denied"Current permission state
requestPermission() => Promise<NotificationPermission>Request notification permission from user
isSupportedbooleanWhether the Notification API is supported

Notification Options

The show function accepts an options object with the following properties:

OptionTypeDescription
bodystringThe body text of the notification
iconstringURL of an icon to display in the notification
badgestringURL of a badge image
tagstringUnique tag to identify the notification
dataanyCustom data to associate with the notification
requireInteractionbooleanWhether notification should remain active until clicked
silentbooleanWhether notification should be silent
vibratenumber | number[]Vibration pattern for devices that support it
imagestringURL of an image to display in the notification

Features

  • Permission management - Request and track notification permissions
  • Rich notifications - Support for icons, images, badges, and more
  • Error handling - Graceful handling of permission denials
  • Browser support detection - Automatically detects API availability
  • TypeScript support - Full type definitions included

Browser Support

The Notifications API is supported in:

  • Chrome 22+
  • Firefox 22+
  • Safari 7+
  • Edge 14+
  • Opera 25+

Notes

  • Notifications require user permission and will prompt the user on first request
  • Some browsers block notification requests if not triggered by user interaction
  • Notifications may not work in cross-origin iframes
  • Users can revoke permission at any time through browser settings
  • On mobile devices, notifications behavior varies by browser and OS

On this page