Advanced

Real-life advanced usages of the supabase module.


Realtime

Based on Supabase Realtime, listen to changes in your PostgreSQL Database and broadcasts them over WebSockets.

To enable it, make sure you have turned on the Real Time API for your table.

Then, listen to changes directly in your vue page / component:

<script setup lang="ts">import type { RealtimeSubscription } from '@supabase/supabase-js'const client = useSupabaseClient()let subscription: RealtimeSubscription// Fetch collaborators and get the refresh method provided by useAsyncDataconst { data: collaborators, refresh: refreshCollaborators } = await useAsyncData('collaborators', async () => {  const { data } = await client.from('collaborators').select('name')  return data})// Once page is mounted, listen to changes on the `collaborators` table and refresh collaborators when receiving eventonMounted(() => {  subscription = client.from('collaborators').on('*', () => {    refreshCollaborators()  }).subscribe()})// Don't forget to unsubscribe when user left the pageonUnmounted(() => {  client.removeSubscription(subscription)})</script>

Auth middleware

You can protect your authenticated routes by creating a custom middleware in your project, here is an example:

middleware/auth.ts
export default defineNuxtRouteMiddleware((to, _from) => {  const user = useSupabaseUser()  if (!user.value) {    return navigateTo('/login')  }})

Then you can reference your middleware in your page with:

pages/dashboard.vue
definePageMeta({  middleware: 'auth'})

Learn more about Nuxt middleware and definePageMeta.