# Notification bell

> A header button with the unread count, which updates when a notification arrives or is read.

- Block: [notifications](https://bettersupabase.com/blocks/notifications.md)
- Kind: component
- Hook: `useNotifications` from `@/hooks/use-notifications`
- Page: https://bettersupabase.com/recipes/notification-bell

## Install the block

```bash
npx better-supabase add notifications
```

## Web (Next.js)

Add the shadcn components:

```bash
npx shadcn add badge button
```

Add the glue from the better-supabase registry:

```bash
npx shadcn add @better-supabase/use-notifications @better-supabase/notifications-actions-next
```

From `apps/examples/nextjs/src/features/notifications/components/unread-badge.tsx` (https://github.com/ScaleDockHQ/better-supabase/blob/main/apps/examples/nextjs/src/features/notifications/components/unread-badge.tsx):

```tsx
"use client";

import type { NotificationCounts } from "better-supabase/blocks/notifications";

import { tenantOf } from "better-supabase/next";
import { useBlockEnv } from "better-supabase/react";
import { BellIcon } from "lucide-react";
import { useExtracted } from "next-intl";
import { useCallback } from "react";

import { Badge } from "@/components/ui/badge";
import { buttonVariants } from "@/components/ui/button";
import { useNotifications } from "@/hooks/use-notifications";
import { Link } from "@/i18n/navigation";
import { useAuth } from "@/lib/hooks";

/**
 * The badge numbers through the browser client: the `notification_counts`
 * function on the block's `api` schema, which `notifications.counts()` calls on
 * the server. Calling it directly keeps the notifications client, which renders
 * and delivers, out of the shell's first load (ADR 0643). Pass it as `load` to
 * `useNotifications`.
 */
function useNotificationCountsLoader(): () => Promise<
  readonly NotificationCounts[]
> {
  const { supabase } = useBlockEnv();
  const tenant = tenantOf(useAuth());

  return useCallback(async () => {
    if (tenant === undefined) {
      return [];
    }

    const result: { readonly data: unknown } = await supabase
      .schema("api")
      .rpc("notification_counts", { tenant, actionable: [] });

    // SAFETY: the function returns `{ unread, actionable, actionable_subjects }` as jsonb numbers.
    const counts = result.data as Record<string, number> | null;

    return counts
      ? [
          {
            unread: counts["unread"] ?? 0,
            actionable: counts["actionable"] ?? 0,
            actionableSubjects: counts["actionable_subjects"] ?? 0,
          },
        ]
      : [];
  }, [supabase, tenant]);
}

const unreadOf = (counts: readonly NotificationCounts[]): number =>
  counts[0]?.unread ?? 0;

/**
 * The unread count from the block's `counts()`, loaded again after each
 * broadcast on the caller's private topic `notifications:<user id>`.
 */
export function useUnreadCount() {
  const auth = useAuth();
  const userId = auth.user?.id;
  const load = useNotificationCountsLoader();

  const { items, count, status } = useNotifications({
    topic: userId ? `notifications:${userId}` : null,
    load,
    count: unreadOf,
  });

  return { count: items === undefined ? undefined : count, status };
}

/**
 * The header badge. Part of the static shell, so it loads from the browser
 * instead of adding a database call to every page.
 */
export function UnreadBadge() {
  const t = useExtracted("notifications");
  const { count, status } = useUnreadCount();

  return (
    <Link
      href="/notifications"
      className={buttonVariants({ variant: "ghost", size: "sm" })}
      data-testid="unread-badge"
      data-status={status}
      aria-label={t("Notifications, {count, number} unread", {
        count: count ?? 0,
      })}
    >
      <BellIcon />
      <Badge
        variant={count ? "default" : "secondary"}
        className="tabular-nums"
        data-testid="unread-count"
      >
        {count === undefined ? "–" : count >= 100 ? "99+" : count}
      </Badge>
    </Link>
  );
}
```

## Native (Expo)

The snippet uses `Pressable`, `Text`, `View` from `react-native`, so it needs no styling library.

Add the glue from the better-supabase registry:

```bash
npx shadcn add @better-supabase/use-notifications @better-supabase/blocks
```

From `apps/examples/expo-powersync/src/components/notification-bell.tsx` (https://github.com/ScaleDockHQ/better-supabase/blob/main/apps/examples/expo-powersync/src/components/notification-bell.tsx):

```tsx
import type { NotificationCounts } from "better-supabase/blocks/notifications";

import { tenantOf, useAuth, useSupabase } from "better-supabase/react";
import { Pressable, Text, View } from "react-native";

import { useNotifications } from "../hooks/use-notifications";
import { blocks } from "../lib/blocks";

const unreadOf = (counts: readonly NotificationCounts[]): number =>
  counts[0]?.unread ?? 0;

/**
 * The unread count, loaded again after each broadcast on `notifications:<user
 * id>`.
 */
export function NotificationBell({
  onPress,
}: {
  readonly onPress: () => void;
}) {
  const auth = useAuth();
  const supabase = useSupabase();
  const tenant = tenantOf(auth);
  const userId = auth.user?.id;

  const { items, count } = useNotifications({
    topic: userId ? `notifications:${userId}` : null,
    load: async () => {
      if (!tenant) {
        return [];
      }

      const result = await blocks(supabase).notifications.counts({ tenant });

      return result.ok ? [result.data] : [];
    },
    count: unreadOf,
  });

  return (
    <Pressable
      onPress={onPress}
      accessibilityRole="button"
      accessibilityLabel={`Notifications, ${String(count)} unread`}
      style={{ flexDirection: "row", alignItems: "center", gap: 8, padding: 8 }}
    >
      <Text>Notifications</Text>
      <View
        style={{
          minWidth: 24,
          borderRadius: 12,
          paddingHorizontal: 8,
          backgroundColor: count ? "#111" : "#e5e5e5",
        }}
      >
        <Text style={{ color: count ? "#fff" : "#111", textAlign: "center" }}>
          {items === undefined ? "–" : count}
        </Text>
      </View>
    </Pressable>
  );
}
```

## Prompt

Paste one of these into a coding agent to build the recipe in your app.

### Web

```text
Build "Notification bell" in a React web app that uses shadcn/ui components. A header button with the unread count, which updates when a notification arrives or is read.

It uses the better-supabase `notifications` block (Notifications). It calls the hook `useNotifications` from `@/hooks/use-notifications`.

Steps:

1. If the app doesn't have the block yet, add the SQL with `npx better-supabase add notifications` and apply the migration.
2. Add the shadcn components the recipe uses: `npx shadcn add badge button`.
3. Add the glue from the better-supabase registry: `npx shadcn add @better-supabase/use-notifications @better-supabase/notifications-actions-next`. The items are copied into the app, so edit them as needed.
4. Write the component. Call `useNotifications` from `@/hooks/use-notifications`, starting from the recipe's snippet (`apps/examples/nextjs/src/features/notifications/components/unread-badge.tsx`). Adapt it to the app's existing components, styling and data loading instead of copying it as is.
5. Check the result against the recipe and the block's docs: it typechecks, it calls the same hook, and it handles the loading and empty states the snippet handles.

Read the full code first:

- Recipe: https://bettersupabase.com/recipes/notification-bell.md
- Block docs: https://bettersupabase.com/docs/blocks/notifications
```

### Native

```text
Build "Notification bell" in a React Native app built with Expo. A header button with the unread count, which updates when a notification arrives or is read.

It uses the better-supabase `notifications` block (Notifications). It calls the hook `useNotifications` from `@/hooks/use-notifications`.

Steps:

1. If the app doesn't have the block yet, add the SQL with `npx better-supabase add notifications` and apply the migration.
2. The recipe uses `Pressable`, `Text`, `View` from `react-native`, so it needs no extra UI library. Use the app's own components if it has them.
3. Add the glue from the better-supabase registry: `npx shadcn add @better-supabase/use-notifications @better-supabase/blocks`. The items are copied into the app, so edit them as needed.
4. Write the component. Call `useNotifications` from `@/hooks/use-notifications`, starting from the recipe's snippet (`apps/examples/expo-powersync/src/components/notification-bell.tsx`). Adapt it to the app's existing components, styling and data loading instead of copying it as is.
5. Check the result against the recipe and the block's docs: it typechecks, it calls the same hook, and it handles the loading and empty states the snippet handles.

Read the full code first:

- Recipe: https://bettersupabase.com/recipes/notification-bell.md
- Block docs: https://bettersupabase.com/docs/blocks/notifications
```
