Build in-app and push notification systems in Google Antigravity with real-time delivery.
# Notification Systems for Google Antigravity
Build comprehensive notification systems with in-app, email, and push notifications.
## Database Schema
```sql
CREATE TABLE public.notifications (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
type TEXT NOT NULL,
title TEXT NOT NULL,
body TEXT,
data JSONB DEFAULT '{}'::jsonb,
read BOOLEAN DEFAULT false,
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX idx_notifications_user ON public.notifications(user_id, created_at DESC);
CREATE INDEX idx_notifications_unread ON public.notifications(user_id) WHERE read = false;
ALTER TABLE public.notifications ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Users can view own notifications" ON public.notifications FOR SELECT USING (auth.uid() = user_id);
CREATE POLICY "Users can update own notifications" ON public.notifications FOR UPDATE USING (auth.uid() = user_id);
```
## Notification Service
```typescript
// lib/notifications.ts
import { createClient } from "@/lib/supabase/server";
interface CreateNotificationParams {
userId: string;
type: string;
title: string;
body?: string;
data?: Record<string, unknown>;
}
export async function createNotification(params: CreateNotificationParams) {
const supabase = createClient();
const { data, error } = await supabase.from("notifications").insert(params).select().single();
if (error) throw error;
return data;
}
export async function markAsRead(notificationId: string, userId: string) {
const supabase = createClient();
await supabase.from("notifications").update({ read: true }).eq("id", notificationId).eq("user_id", userId);
}
export async function markAllAsRead(userId: string) {
const supabase = createClient();
await supabase.from("notifications").update({ read: true }).eq("user_id", userId).eq("read", false);
}
export async function getUnreadCount(userId: string): Promise<number> {
const supabase = createClient();
const { count } = await supabase.from("notifications").select("*", { count: "exact", head: true }).eq("user_id", userId).eq("read", false);
return count || 0;
}
```
## Notification Hook
```typescript
// hooks/useNotifications.ts
"use client";
import { useState, useEffect } from "react";
import { createClient } from "@/lib/supabase/client";
interface Notification {
id: string;
type: string;
title: string;
body?: string;
data: Record<string, unknown>;
read: boolean;
created_at: string;
}
export function useNotifications(userId: string) {
const [notifications, setNotifications] = useState<Notification[]>([]);
const [unreadCount, setUnreadCount] = useState(0);
const supabase = createClient();
useEffect(() => {
// Fetch initial notifications
supabase.from("notifications").select("*").eq("user_id", userId).order("created_at", { ascending: false }).limit(50).then(({ data }) => {
setNotifications(data || []);
setUnreadCount(data?.filter((n) => !n.read).length || 0);
});
// Subscribe to new notifications
const channel = supabase.channel("notifications").on("postgres_changes", { event: "INSERT", schema: "public", table: "notifications", filter: `user_id=eq.${userId}` }, (payload) => {
setNotifications((prev) => [payload.new as Notification, ...prev]);
setUnreadCount((prev) => prev + 1);
}).subscribe();
return () => { channel.unsubscribe(); };
}, [userId, supabase]);
const markAsRead = async (id: string) => {
await supabase.from("notifications").update({ read: true }).eq("id", id);
setNotifications((prev) => prev.map((n) => (n.id === id ? { ...n, read: true } : n)));
setUnreadCount((prev) => Math.max(0, prev - 1));
};
const markAllRead = async () => {
await supabase.from("notifications").update({ read: true }).eq("user_id", userId).eq("read", false);
setNotifications((prev) => prev.map((n) => ({ ...n, read: true })));
setUnreadCount(0);
};
return { notifications, unreadCount, markAsRead, markAllRead };
}
```
## Notification Bell Component
```typescript
// components/NotificationBell.tsx
"use client";
import { useState, useRef, useEffect } from "react";
import { useNotifications } from "@/hooks/useNotifications";
import { formatDistanceToNow } from "date-fns";
export function NotificationBell({ userId }: { userId: string }) {
const { notifications, unreadCount, markAsRead, markAllRead } = useNotifications(userId);
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const handleClick = (e: MouseEvent) => {
if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
};
document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, []);
return (
<div ref={ref} className="notification-bell">
<button onClick={() => setOpen(!open)} className="bell-button">
🔔 {unreadCount > 0 && <span className="badge">{unreadCount}</span>}
</button>
{open && (
<div className="notification-dropdown">
<div className="header">
<span>Notifications</span>
{unreadCount > 0 && <button onClick={markAllRead}>Mark all read</button>}
</div>
<div className="notification-list">
{notifications.length === 0 ? (
<p className="empty">No notifications</p>
) : (
notifications.map((n) => (
<div key={n.id} className={`notification-item ${n.read ? "" : "unread"}`} onClick={() => markAsRead(n.id)}>
<strong>{n.title}</strong>
{n.body && <p>{n.body}</p>}
<span className="time">{formatDistanceToNow(new Date(n.created_at))} ago</span>
</div>
))
)}
</div>
</div>
)}
</div>
);
}
```
## Push Notification Setup
```typescript
// lib/push-notifications.ts
export async function requestNotificationPermission(): Promise<boolean> {
if (!("Notification" in window)) return false;
if (Notification.permission === "granted") return true;
if (Notification.permission === "denied") return false;
const permission = await Notification.requestPermission();
return permission === "granted";
}
export async function subscribeToPush(userId: string) {
const registration = await navigator.serviceWorker.ready;
const subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY,
});
await fetch("/api/push/subscribe", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ userId, subscription }),
});
}
```
## Best Practices
1. **Real-time**: Use Supabase Realtime for instant updates
2. **Batching**: Batch notifications to avoid spam
3. **Preferences**: Let users control notification settings
4. **Cleanup**: Delete old notifications periodically
5. **Analytics**: Track notification engagementThis notifications prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their notifications implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For notifications projects, consider mentioning your framework version, coding style, and any specific libraries you're using.