supabase-realtime
Comprehensive guide for implementing Supabase Realtime features with best practices, scalable patterns, and migration strategies. Use when building realtime features in Supabase applications including messaging, notifications, presence, live updates, collaborative features, or migrating from postgres_changes to broadcast. Covers client setup, database triggers with realtime.broadcast_changes, RLS authorization, naming conventions, and performance optimization.
What this skill does
# Supabase Realtime
Expert implementation guide for Supabase Realtime features focusing on scalable patterns and best practices.
## Core Principles
**Always use `broadcast` over `postgres_changes`** - postgres_changes is single-threaded and doesn't scale. Use broadcast with database triggers for all database change notifications.
**Use dedicated topics** - Never broadcast to global topics. Use granular patterns like `room:123:messages`, `user:456:notifications`.
**Private channels by default** - Set `private: true` for all database-triggered channels. Enable private-only mode in production.
## Quick Reference
### Naming Conventions
- **Topics**: `scope:entity:id` (e.g., `room:123:messages`)
- **Events**: `entity_action` in snake_case (e.g., `message_created`)
### Client Setup Pattern
```javascript
const channel = supabase.channel('room:123:messages', {
config: {
broadcast: { self: true, ack: true },
private: true // Required for RLS
}
})
// Set auth before subscribing
await supabase.realtime.setAuth()
channel
.on('broadcast', { event: 'message_created' }, handler)
.subscribe((status, err) => {
if (status === 'SUBSCRIBED') console.log('Connected')
})
// Cleanup
supabase.removeChannel(channel)
```
### Database Trigger Pattern
```sql
-- Use realtime.broadcast_changes for database events
CREATE OR REPLACE FUNCTION notify_table_changes()
RETURNS TRIGGER AS $$
BEGIN
PERFORM realtime.broadcast_changes(
TG_TABLE_NAME || ':' || COALESCE(NEW.id, OLD.id)::text,
TG_OP,
TG_OP,
TG_TABLE_NAME,
TG_TABLE_SCHEMA,
NEW,
OLD
);
RETURN COALESCE(NEW, OLD);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
CREATE TRIGGER messages_broadcast_trigger
AFTER INSERT OR UPDATE OR DELETE ON messages
FOR EACH ROW EXECUTE FUNCTION notify_table_changes();
```
### RLS Authorization
```sql
-- Required for private channels
CREATE POLICY "room_members_can_read" ON realtime.messages
FOR SELECT TO authenticated
USING (
topic LIKE 'room:%' AND
EXISTS (
SELECT 1 FROM room_members
WHERE user_id = auth.uid()
AND room_id = SPLIT_PART(topic, ':', 2)::uuid
)
);
-- Required index for performance
CREATE INDEX idx_room_members_user_room ON room_members(user_id, room_id);
```
## Implementation Checklist
- ✅ Use `broadcast` not `postgres_changes`
- ✅ Dedicated topics per room/user/entity
- ✅ Set `private: true` for database triggers
- ✅ Create indexes for all RLS policy columns
- ✅ Include cleanup/unsubscribe logic
- ✅ Check channel state before subscribing
- ✅ Use consistent naming conventions
## Scripts
- **[scripts/create_broadcast_trigger.sql](scripts/create_broadcast_trigger.sql)** - Generic broadcast trigger function
- **[scripts/migrate_from_postgres_changes.sql](scripts/migrate_from_postgres_changes.sql)** - Migration helper script
## Advanced Topics
- **Framework Integration**: See [references/framework_patterns.md](references/framework_patterns.md)
- **Performance Optimization**: See [references/performance_scaling.md](references/performance_scaling.md)
- **Migration Guide**: See [references/migration_guide.md](references/migration_guide.md)
Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.