The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
chore: add realtime troubleshoot guides (#40902)
Filipe Cabaço48c9d3e2a7c2
diff --git a/apps/docs/content/troubleshooting/realtime-debugging-with-logger.mdx b/apps/docs/content/troubleshooting/realtime-debugging-with-logger.mdxnew file mode 100644index 00000000000..c41e43d8978--- /dev/null+++ b/apps/docs/content/troubleshooting/realtime-debugging-with-logger.mdx@@ -0,0 +1,162 @@+---+title = "Debug Realtime with Logger and Log Levels"+github_url = ""+date_created = "2025-11-28T00:00:00+00:00"+topics = [ "realtime" ]+keywords = [ "debug", "logger", "log_level", "troubleshooting", "diagnostics" ]+database_id = ""+---++## What are logger and log_level parameters?++The Realtime client provides built-in logging to help you debug connection issues, track messages, and understand what's happening with your real-time connections. Two parameters control logging:++- **`logger`**: A custom function to handle log messages+- **`logLevel`**: Controls which messages the server logs (`info`, `warn`, or `error`)++By default, logging is disabled. When enabled, you can see:++- Messages sent and received+- Connection events (connect, disconnect, errors)+- Heartbeat status+- Channel subscriptions+- Worker events++## How to enable logging in your Realtime client++### Basic logging to console++```tsx+import { createClient } from '@supabase/supabase-js'++const supabase = createClient(SUPABASE_URL, SUPABASE_KEY, {+ realtime: {+ logger: (kind, msg, data) => {+ console.log(`${kind}: ${msg}`, data)+ },+ },+})+```++### With log levels for server-side filtering++```tsx+const supabase = createClient(SUPABASE_URL, SUPABASE_KEY, {+ realtime: {+ logLevel: 'info', // 'info' | 'warn' | 'error'+ logger: (kind, msg, data) => {+ console.log(`[${kind}] ${msg}`, data)+ },+ },+})+```++## Understanding log messages++The logger receives three parameters: `kind`, `msg`, and `data`.++**Log kinds you'll see:**++**`push`** - Messages sent to the server++```+push: realtime:chat heartbeat (42) {}+push: realtime:chat phx_join (1) { config: {...} }+```++**`receive`** - Messages received from server++```+receive: ok realtime:chat phx_reply (1) { response: {...} }+receive: realtime:chat broadcast { event: 'message', payload: {...} }+```++**`transport`** - Connection events++```+transport: connected to wss://project.supabase.co/realtime/v1+transport: heartbeat timeout. Attempting to re-establish connection+transport: close CloseEvent {...}+transport: leaving duplicate topic "realtime:chat"+```++**`error`** - Error events++```+error: error in heartbeat callback Error: ...+error: error waiting for auth on connect Error: ...+```++**`worker`** - Web Worker events++```+worker: starting default worker+worker: starting worker for from /worker.js+worker: worker error message+```++**Common debugging scenarios**++**Debug why channel won't subscribe:**++```tsx+import { createClient } from '@supabase/supabase-js'++const supabase = createClient(SUPABASE_URL, SUPABASE_KEY, {+ realtime: {+ logger: (kind, msg, data) => {+ console.log(`[${kind}] ${msg}`, data)+ },+ },+})++const channel = supabase+ .channel('debug-channel')+ .on('broadcast', { event: 'test' }, (payload) => {+ console.log('Received:', payload)+ })+ .subscribe((status, err) => {+ console.log('Subscribe status:', status, err)+ })++// Check logs for:+// push: realtime:debug-channel phx_join - subscription attempt+// receive: ok realtime:debug-channel phx_reply - successful subscription+// Or error messages if subscription failed+```++## Debug message delivery issues++```tsx+const supabase = createClient(SUPABASE_URL, SUPABASE_KEY, {+ realtime: {+ logger: (kind, msg, data) => {+ if (kind === 'push' || kind === 'receive') {+ console.log(`[${kind}] ${msg}`, data)+ }+ },+ },+})++const channel = supabase.channel('chat', { config: { broadcast: { self: true } } })++channel.on('broadcast', { event: 'message' }, (payload) => {+ console.log('Message received:', payload)+})+// Send message after subscribing+channel.subscribe((status, err) => {+ if (status == 'SUBSCRIBED') {+ channel.send({+ type: 'broadcast',+ event: 'message',+ payload: { text: 'Hello' },+ })+ } else {+ console.error({ status, err })+ }+})++// Check logs:+// push: realtime:chat broadcast - message sent+// receive: realtime:chat broadcast - message received (if self: true)+```diff --git a/apps/docs/content/troubleshooting/realtime-heartbeat-messages.mdx b/apps/docs/content/troubleshooting/realtime-heartbeat-messages.mdxnew file mode 100644index 00000000000..eb121cab7a3--- /dev/null+++ b/apps/docs/content/troubleshooting/realtime-heartbeat-messages.mdx@@ -0,0 +1,247 @@+---+title = "Understanding and Monitoring Realtime Heartbeats"+github_url = ""+date_created = "2025-11-28T00:00:00+00:00"+topics = [ "realtime" ]+keywords = [ "heartbeat", "connection", "websocket", "keep-alive", "timeout", "onHeartbeat", "heartbeatCallback", "reconnect" ]+database_id = ""+---++## What are heartbeat messages?++Heartbeat messages are periodic signals sent between the Realtime client and server to verify that the WebSocket connection is alive and functioning properly. The client sends a heartbeat message on the `phoenix` topic with the event type `heartbeat` at regular intervals (default: 25 seconds), and the server responds with a `phx_reply` message.++These messages serve as a keep-alive mechanism to detect connection issues that might not be immediately apparent, such as silent network failures or intermediary proxy timeouts.++## Why heartbeats matter++Heartbeat messages are critical for maintaining reliable real-time connections:++- **Connection health monitoring**: They detect when a connection has silently failed without triggering WebSocket close events+- **Automatic recovery**: When heartbeats time out, the client automatically attempts to reconnect+- **Network proxy compatibility**: Many network proxies and load balancers close idle connections; heartbeats keep the connection active+- **Early issue detection**: Heartbeat timeouts alert you to connection problems before users experience message delivery failures++Without heartbeats, your application might appear connected while being unable to send or receive messages.++## How to handle heartbeat messages++You can monitor heartbeat lifecycle events using the `onHeartbeat` method:++```tsx+import { useEffect } from 'react'+import { createClient } from '@supabase/supabase-js'++function MyComponent() {+ const supabase = createClient(SUPABASE_URL, SUPABASE_KEY)++ useEffect(() => {+ supabase.realtime.onHeartbeat((status) => {+ console.log('Heartbeat status:', status)+ // status can be: 'sent', 'ok', 'error', 'timeout', or 'disconnected'+ })+ }, [supabase])++ return <div>Your app content</div>+}+```++Or configure the callback during client initialization:++```tsx+const supabase = createClient(SUPABASE_URL, SUPABASE_KEY, {+ realtime: {+ heartbeatCallback: (status) => {+ console.log('Heartbeat status:', status)+ },+ },+})+```++## Troubleshooting heartbeat issues++### Frequent heartbeat timeouts++If you're seeing frequent `timeout` status in your heartbeat callback:++- **Network instability**: Check your network connection quality+- **Firewall/proxy issues**: Corporate firewalls or proxies might interfere with WebSocket connections+- **Mobile app suspension**: On mobile, the app can be suspended which can stop the heartbeat timers++**Connection not reconnecting after timeout**++The client automatically attempts reconnection with exponential backoff (1s, 2s, 5s, 10s). If you need to manually reconnect:++```tsx+import { useState, useEffect } from 'react'+import { createClient } from '@supabase/supabase-js'++function ConnectionStatus() {+ const supabase = createClient(SUPABASE_URL, SUPABASE_KEY)+ const [isConnected, setIsConnected] = useState(true)++ useEffect(() => {+ supabase.realtime.onHeartbeat((status) => {+ if (status === 'ok') {+ setIsConnected(true)+ } else if (status === 'timeout' || status === 'disconnected') {+ setIsConnected(false)+ }+ })+ }, [supabase])++ const handleReconnect = () => {+ supabase.realtime.connect()+ }++ return (+ <div>+ <p>Status: {isConnected ? 'Connected' : 'Disconnected'}</p>+ {!isConnected && <button onClick={handleReconnect}>Reconnect</button>}+ </div>+ )+}+```++### Customizing heartbeat interval++You can adjust the heartbeat frequency when creating your Supabase client in React:++```tsx+import { createClient } from '@supabase/supabase-js'+import { useMemo } from 'react'++function App() {+ const supabase = useMemo(+ () =>+ createClient(SUPABASE_URL, SUPABASE_KEY, {+ realtime: {+ heartbeatIntervalMs: 15000, // Send heartbeat every 15 seconds (default: 25000)+ },+ }),+ []+ )++ return <YourApp supabase={supabase} />+}+```++Note: Increasing the interval reduces network traffic but delays detection of connection failures. Decreasing it improves detection speed but increases overhead.++### Heartbeat errors in Web workers++For React applications with long-running connections, use Web Workers to prevent browser tab throttling:++```tsx+import { createClient } from '@supabase/supabase-js'+import { useMemo } from 'react'++function App() {+ const supabase = useMemo(+ () =>+ createClient(SUPABASE_URL, SUPABASE_KEY, {+ realtime: {+ worker: true,+ workerUrl: '/worker.js', // Optional: Place in public folder+ },+ }),+ []+ )++ return <YourApp supabase={supabase} />+}+```++If the worker fails to start, check:++- Browser Web Worker support is available+- Worker script is in the public folder and accessible+- CORS headers allow loading the worker script++## Best practices++### Show connection status to users++Display connection status with a simple indicator:++```tsx+import { useState, useEffect } from 'react'+import { createClient } from '@supabase/supabase-js'++function ConnectionIndicator() {+ const supabase = createClient(SUPABASE_URL, SUPABASE_KEY)+ const [status, setStatus] = useState('healthy')++ useEffect(() => {+ supabase.realtime.onHeartbeat((heartbeatStatus) => {+ if (heartbeatStatus === 'ok') {+ setStatus('healthy')+ } else if (heartbeatStatus === 'timeout') {+ setStatus('poor')+ } else if (heartbeatStatus === 'disconnected') {+ setStatus('disconnected')+ }+ })+ }, [supabase])++ return (+ <div>+ <span>Connection: {status}</span>+ </div>+ )+}+```++### Reconnect when React Native app comes to foreground++Ensure connection is active when user opens your app:++```tsx+import { useEffect } from 'react'+import { AppState } from 'react-native'+import { createClient } from '@supabase/supabase-js'++function App() {+ const supabase = createClient(SUPABASE_URL, SUPABASE_KEY)++ useEffect(() => {+ const subscription = AppState.addEventListener('change', (nextAppState) => {+ if (nextAppState === 'active') {+ if (!supabase.realtime.isConnected()) {+ supabase.realtime.connect()+ }+ }+ })++ return () => {+ subscription.remove()+ }+ }, [supabase])++ return <YourApp />+}+```++### Monitor connection in your entire app++Set up monitoring when you create your Supabase client:++```tsx+import { createClient } from '@supabase/supabase-js'++const supabase = createClient(SUPABASE_URL, SUPABASE_KEY, {+ realtime: {+ heartbeatCallback: (status) => {+ if (status === 'ok') {+ console.log('Connection healthy')+ } else if (status === 'timeout') {+ console.warn('Connection slow')+ } else if (status === 'disconnected') {+ console.error('Disconnected')+ }+ },+ },+})++export default supabase+```diff --git a/apps/docs/content/troubleshooting/realtime-too-many-channels-error.mdx b/apps/docs/content/troubleshooting/realtime-too-many-channels-error.mdxnew file mode 100644index 00000000000..af7bcdb0543--- /dev/null+++ b/apps/docs/content/troubleshooting/realtime-too-many-channels-error.mdx@@ -0,0 +1,247 @@+---+title = "Fixing the TooManyChannels Error"+github_url = ""+date_created = "2025-11-28T00:00:00+00:00"+topics = [ "realtime" ]+keywords = [ "channels", "useEffect", "react", "memory leak", "quota", "TooManyChannels", "ChannelRateLimitReached", "unsubscribe", "cleanup" ]+database_id = ""+---++{/* supa-mdx-lint-disable Rule003Spelling */}++## What is the TooManyChannels error?++The TooManyChannels error occurs when your application tries to create more than the allowed number of Realtime channels. When you exceed this limit, you'll see an error with the code `ChannelRateLimitReached`.++This limit exists to protect both your application and Supabase servers from resource exhaustion.++## What causes TooManyChannels errors?++{/* supa-mdx-lint-enable Rule003Spelling */}+The most common cause is accidentally creating channels without cleaning them up, especially in React applications. This happens when:++{/* supa-mdx-lint-disable Rule003Spelling */}++- Components create channels on every render without unsubscribing+- `useEffect` runs multiple times due to missing or incorrect dependencies+- Components unmount without cleaning up their channels+- Development mode in React (StrictMode) causes effects to run twice+ {/* supa-mdx-lint-enable Rule003Spelling */}++Each time you call `supabase.channel('topic').subscribe()`, a new channel is created unless you properly clean it up.+{/* supa-mdx-lint-disable Rule003Spelling */}+Here's the most common mistake that might lead to TooManyChannels errors:+{/* supa-mdx-lint-enable Rule003Spelling */}++```tsx+// ❌ WRONG - Creates new channel on every render+function ChatRoom() {+ const supabase = createClient(SUPABASE_URL, SUPABASE_KEY)++ useEffect(() => {+ const channel = supabase.channel('chat')++ channel+ .on('broadcast', { event: 'message' }, (payload) => {+ console.log(payload)+ })+ .subscribe()++ // Missing cleanup!+ }, []) // supabase is missing from dependencies++ return <div>Chat</div>+}+```++Why this fails:++- Creating `supabase` client inside component causes it to change on every render+- Missing `supabase` from dependencies array+- No cleanup function to unsubscribe the channel+- Each render creates a new channel that's never removed++## The correct approach++```tsx+// ✅ CORRECT - Properly manages channel lifecycle+import { useEffect } from 'react'+import { createClient } from '@supabase/supabase-js'++// Create client outside component (singleton)+const supabase = createClient(SUPABASE_URL, SUPABASE_KEY)++function ChatRoom() {+ useEffect(() => {+ const channel = supabase+ .channel('chat')+ .on('broadcast', { event: 'message' }, (payload) => {+ console.log(payload)+ })+ .subscribe()++ // Cleanup function - ALWAYS unsubscribe!+ return () => {+ channel.unsubscribe()+ }+ }, []) // Empty dependencies because supabase is stable++ return <div>Chat</div>+}+```++## How to debug channel creation++Check how many channels your app has created:++```tsx+import { useEffect } from 'react'++function ChannelDebugger() {+ const supabase = createClient(SUPABASE_URL, SUPABASE_KEY)++ useEffect(() => {+ const interval = setInterval(() => {+ const channels = supabase.getChannels()+ console.log(`Active channels: ${channels.length}`)+ console.log(+ 'Channel topics:',+ channels.map((c) => c.topic)+ )+ }, 2000)++ return () => clearInterval(interval)+ }, [supabase])++ return <div>Check console for channel count</div>+}+```++If you see the number climbing, you have a leak. Look for:++- Channel count increasing without user action+- Same channel topics appearing multiple times+- Count going up when navigating between pages++## Best practices for channel management++### 1. Create Supabase client outside components++```tsx+// ✅ Create once at module level+const supabase = createClient(SUPABASE_URL, SUPABASE_KEY)++function MyComponent() {+ // Use the stable client+}+```++### 2. Always unsubscribe in cleanup++```tsx+useEffect(() => {+ const channel = supabase.channel('topic').subscribe()++ return () => {+ channel.unsubscribe()+ }+}, [])+```++### 3. Use stable channel names++```tsx+// ❌ WRONG - Creates new channel topic on every render+function BadExample({ userId }) {+ useEffect(() => {+ const channel = supabase+ .channel(`user-${Math.random()}`) // Random topic!+ .subscribe()++ return () => {+ channel.unsubscribe()+ }+ }, [userId])+}++// ✅ CORRECT - Predictable channel topic+function GoodExample({ userId }) {+ useEffect(() => {+ const channel = supabase.channel(`user-${userId}`).subscribe()++ return () => {+ channel.unsubscribe()+ }+ }, [userId])+}+```++### 4. Reuse channels when possible++The Supabase client automatically reuses channels with the same topic:++```tsx+// These return the same channel instance+const channel1 = supabase.channel('chat')+const channel2 = supabase.channel('chat') // Same as channel1++console.log(channel1 === channel2) // true+```++### 5. Handle strict mode in development++{/* supa-mdx-lint-disable Rule003Spelling */}+React StrictMode intentionally runs effects twice in development. Your cleanup function will handle this:+{/* supa-mdx-lint-enable Rule003Spelling */}++```tsx+// This works correctly even in StrictMode+useEffect(() => {+ console.log('Effect running')+ const channel = supabase.channel('chat').subscribe()++ return () => {+ console.log('Cleanup running')+ channel.unsubscribe()+ }+}, [])+```++{/* supa-mdx-lint-disable Rule003Spelling */}++### 6. Clean up on unmount for dynamic channels++If you create channels based on props:++```tsx+function RoomComponent({ roomId }) {+ useEffect(() => {+ const channel = supabase+ .channel(`room:${roomId}`)+ .on('broadcast', { event: 'message' }, handleMessage)+ .subscribe()++ return () => {+ channel.unsubscribe()+ }+ }, [roomId]) // Re-subscribe when roomId changes+}+```++### 7. Remove all channels when disconnecting++When logging out or leaving your app:++```tsx+function LogoutButton() {+ const handleLogout = async () => {+ // Clean up all channels before logout+ await supabase.removeAllChannels()++ // Then handle logout+ await supabase.auth.signOut()+ }++ return <button onClick={handleLogout}>Logout</button>+}+```diff --git a/supa-mdx-lint/Rule001HeadingCase.toml b/supa-mdx-lint/Rule001HeadingCase.tomlindex 3d226c92e55..e1f6a201bb8 100644--- a/supa-mdx-lint/Rule001HeadingCase.toml+++ b/supa-mdx-lint/Rule001HeadingCase.toml@@ -179,6 +179,7 @@ may_uppercase = ["React Email","React Native","Read Replicas?",+ "Realtime","Reciprocal Ranked Fusion","Redis","RedwoodJS",@@ -217,6 +218,7 @@ may_uppercase = ["Telegram","Third-Party Auth","TimescaleDB",+ "TooManyChannels","Transformers.js","Twilio","Twitch",