Page 5: Realtime Subscriptions & Best Practices

5. Realtime Subscriptions & Best Practices

Supabase provides powerful realtime capabilities, allowing your Next.js application to react instantly to database changes. This section covers implementing realtime subscriptions and general best practices.

5.1. Realtime Subscriptions

You can subscribe to changes in your database tables. This is particularly useful for building interactive features like chat applications or live dashboards.

'use client'

import { createClient } from '@/lib/supabase/client'
import { useEffect, useState } from 'react'

export default function RealtimeTodos() {
  const [todos, setTodos] = useState<any[]>([])
  const supabase = createClient()

  useEffect(() => {
    const channel = supabase
      .channel('todos-channel') // Arbitrary channel name
      .on(
        'postgres_changes',
        { event: '*', schema: 'public', table: 'todos' },
        (payload) => {
          // Handle different events: INSERT, UPDATE, DELETE
          console.log('Change received!', payload)
          // In a real app, you would update your 'todos' state here
        }
      )
      .subscribe()

    // Clean up subscription on component unmount
    return () => {
      supabase.removeChannel(channel)
    }
  }, [supabase])

  return (
    <div>
      <h2>Realtime Todos (Check Console)</h2>
      <p>Open your browser console and make changes to the 'todos' table in Supabase. You'll see updates here.</p>
    </div>
  )
}

Note: Ensure you enable Realtime for your tables in the Supabase Dashboard under Database > Realtime.

5.2. Best Practices for Supabase with Next.js (App Router)

By following these guidelines, you can build performant, secure, and real-time applications using Supabase and Next.js (App Router).