Advanced

Client Access

Access the raw Convex client instance for advanced use cases.

Basic Usage

<script setup lang="ts">
import { api } from '~/convex/_generated/api'

const convex = useConvex()

onMounted(async () => {
  if (convex) {
    // Direct client access
    const result = await convex.query(api.tasks.list)
    console.log(result)
  }
})
</script>

Return Value

TypeDescription
ConvexClient | nullThe Convex client instance, or null during SSR

Important Notes

Client-only: The ConvexClient uses WebSockets and only works in the browser. During SSR, useConvex() returns null.

const convex = useConvex()

// Always check for null when using outside onMounted
if (convex) {
  // Safe to use
}

When to Use

In most cases, prefer the higher-level composables:

Use CaseRecommended Composable
Fetching datauseConvexQuery
Modifying datauseConvexMutation
Running actionsuseConvexAction
Paginated datauseConvexPaginatedQuery
Auth stateuseConvexAuth

Use useConvex() when you need:

  • Direct access to the client for advanced patterns
  • Integration with external libraries expecting a Convex client
  • Custom subscription management
  • Access to client methods not exposed by composables

Example: Custom Subscription

<script setup lang="ts">
import { api } from '~/convex/_generated/api'

const convex = useConvex()
const notifications = ref<Notification[]>([])

onMounted(() => {
  if (!convex) return

  // Manual subscription with custom handling
  const unsubscribe = convex.onUpdate(
    api.notifications.list,
    { userId: 'user123' },
    (result) => {
      notifications.value = result
      // Custom logic: play sound, show toast, etc.
      if (result.some(n => n.unread)) {
        playNotificationSound()
      }
    }
  )

  onUnmounted(() => {
    unsubscribe()
  })
})
</script>